Statements
For each statement, I'll show the C code (I chose C over other languages as the generated assembly is very minimal and easy to understand), and the relative MIPS implementation; under details I'll leave the x_86 assembly generated by cl.exe
on Windows and gcc
on Linux.
Conditions
If-Else
int main() {
int x = 0;
if (x > 0)
x += 5;
else
x += 10;
}
.text
li $t0, 0 #; x = 0
blez $t0, else #; if x <= 0, goto else
if:
addi $t0, $t0, 5 #; add 5 to x if x > 0
j end #; don't execute else part
else:
addi $t0, $s1, 10 #; add 10 to x if x <= 0
end:
Switch
int main() {
int x = 1;
switch (x) {
case 0:
x += 16;
break;
case 1:
x += 16 * 2;
break;
case 2:
x += 16 * 3;
break;
}
}
.data
dest: .word case0, case1, case2
.text
#; sll $t0, $t0, 2 #; choose the case
li $t0, 0 #; first case
addi $t0, $t0, 4 #; jump one case
#; addi $t0, $t0, 8 #; jump two cases
lw $t1, dest($t0) #; load case address to $t1
jr $t1 #; Jump to the case address in $t1 (case0, case1 etc...)
li $t2, 0
case0:
addi $t2, $zero, 0x10
j break
case1:
addi $t2, $zero, 0x20
j break
case2:
addi $t2, $zero, 0x30
j break
break:
Iterations
Do-While
int main() {
int x = 0, i = 0;
do {
x += 4;
i += 1;
} while (i < 10);
}
.text
li $t0, 0 #; x = 0
li $t1, 0 #; i = 0
do:
addi $t0, $t0, 4 #; x += 4
addi $t1, $t1, 1 #; i += 1
blt $t1, 10, do #; if i < 10, repeat the cicle
While
int main() {
int x = 0, i = 0;
while (i < 10) {
x += 4;
i += 1;
}
}
.text
li $t0, 0 #; x = 0
li $t1, 0 #; i = 0
while:
bge $t1, 10, end #; if i >= 10, end the while loop
addi $t0, $t0, 4 #; x += 4
addi $t1, $t1, 1 #; i += 1
j while #; repeat cicle
end:
For
int main() {
int x = 0;
for (int i = 0; i <= 10; i++)
x += i;
}
.text
li $t0, 0 #; x = 0
li $t1, 0 #; i = 0
for:
beq $t1, 10, end #; if i == 10, end loop
add $t0, $t0, $t1 #; x += i
addi $t1, $t1, 1 #; i += 1
j for
end: