1

I have tried implementing a switch case in MIPS assembly but I feel like I could have made this simpler, especially with the default case. Is there anyway I can make this better? Here is my assembly code:

$t1 = var
$t2 = i 
$t3 = 4
$t4 = 1

lw $t1,0($i)
lw $t2, 0($var)

li $t3, 4                                #load intermediate value of 4 into $t3
li $t4, 1                                #load intermediate value of 1 into #t4
lui $t5, 0xFFFF
li $t6, 0x2000A0000

bltz $t1, DEFAULT_BODY #branch to default if var less than 0 
slt $s0, $t1, $t3                   # if t1 < t3, then $s0 = 1, otherwise 0
beq $s0, $t4, DEFAULT_BODY  #if $s0=1 then branch to default
j C0_COND


C0_COND: addi $t1, $zero, 0   # case 0: set var to 0 
            beq $t1, $t1, C0_BODY
                    j C1_COND

C1_COND: addi $t1, $zero, 1
                   beq $t1, $t1, C1_BODY
           j C2_COND

C2_COND: addi $t1, $zero, 2
                   beq $t1, $t1, C2_BODY
           j END

C0_BODY: sub $t2, $t2, $t4
                   j END
C1_BODY: addi $t2, $t2, 5 
                   j END
C2_BODY: addi $t1, $zero, 0xFFFF0000
           j END


DEFAULT_BODY: addi $t1, $zero, $t5
              j END
END: sw $t7, $t6

Here is the C code that I compared it with

char i;
int var;
// ...
switch (var) {
case 0:
    i--;
    break;
case 1:
    i += 5;
    break;
case 2:
    i = 0xFFFF0000;
    break;
default:
    i = 0;
}

Thank you.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
Kreul
  • 27
  • 1
  • 7

1 Answers1

0

Jumping to the next instruction that would be automatically executed anyway is pointless. You used beq $t1, $t1 three times, but that is of course always true. Surely you made a typo. I suggest you make sure your code works correctly before you try to optimize it.

As for simplification, you could rewrite the code in a fall-through manner as:

i--;
if (var == 0) goto done;
i += 6;  /* account for the i-- above */
if (var == 1) goto done;
i = 0xFFFF0000;
if (var == 2) goto done;
i = 0;
done:
Jester
  • 56,577
  • 4
  • 81
  • 125