C to MIPS Conversion Practice Set 1
Full MIPS solutions are provided below so you can blank out fields as needed.
Assumptions:
- Calling convention: arguments in $a0, $a1, $a2, return with jr $ra
- 32-bit MIPS
- short is 16 bits, int is 32 bits
1) Function f1
C code:
/* ptr: $a0, i: $a1, val: $a2 */
void f1(short *ptr, int i, unsigned val)
{
int tmp = val / 32;
ptr[tmp] = 5;
ptr[i] = val % 4;
}
MIPS solution:
f1:
s____ $t0, $__, 5
sll $t1, $t0, ___
add $t1, ____, $t1
addi $t2, $zero, ___
___ $t2, 0($t1)
andi $t3, $a2, ___
sll $t4, $a1, ___
add $t4, ___, $t4
___ $t3, 0($t4)
jr $ra
2) Function f2
C code:
/* data: $a0, val: $a1 */
void f2(int *data, int val)
{
if (val > 0 && val < 8) {
data[val] = data[0];
}
else {
data[1] = 0x55AAAA55;
}
}
MIPS solution:
f2:
slt $t0, $zero, $a1
b__ $t0, $zero, L_else
____ $t1, $a1, 8
b__ $t1, $zero, L_else
sll $t2, $a1, ___
add $t3, ___, $t2
l__ $t4, ______
s__ $t4, ______
b L_done
L_else:
___ $t5, 0x55AA
ori $t5, $t5, 0xAA55
sw $t5, 4($a0)
L_done:
jr $ra
f1 Solutions
f1:
srl $t0, $a2, 5
sll $t1, $t0, 1
add $t1, $a0, $t1
addi $t2, $zero, 5
sh $t2, 0($t1)
andi $t3, $a2, 3
sll $t4, $a1, 1
add $t4, $a0, $t4
sh $t3, 0($t4)
jr $ra
f2 Solutions
f2:
slt $t0, $zero, $a1
beq $t0, $zero, L_else
slti $t1, $a1, 8
beq $t1, $zero, L_else
sll $t2, $a1, 2
add $t3, $a0, $t2
lw $t4, 0($a0)
sw $t4, 0($t3)
b L_done
L_else:
lui $t5, 0x55AA
ori $t5, $t5, 0xAA55
sw $t5, 4($a0)
L_done:
jr $ra