In: Computer Science
Compile the following C code to MIPS assembly.
a. Assume that i and j are stored in register $s1 and $s2, respectively. i = i – 2 + j;
b. Assume base address of Array B and the variable i are stored in registers $s3 and $s1, respectively. B[1] = (B[0] x 4) - I;
Explain each step in detail!
my professor has the following answer: 1) addi $t0, $s1, -2 add $s1, $$t0, $s2
2) lw $t0, 0 ($s3) #load B[0] into a register sll $t0, $t0, 2 #shift left logical A[2] x 4 #(may have several different ways) sub $t0, $t0, $s1 # (B[0] x 4) - i sw $t0, 4($s0)
Can you explain in detail why?
(a)Register $s1 stores value of variable i
Register $s2 stores value of variable j
C code
i = i – 2 + j;
i = (i – 2) + j;
Here $t0 is temporary register, which stores result of
intermediate values
MIPS code
addi $t0, $s1, -2 # $t0 = i+(-2) = i-2
add $s1, $$t0, $s2 #$s1 = $t0 + $s2 = (i-2) + j
(b)$s3 stores base address of Array B
$s1 = i
Here $t0 is temporary register, which stores result of intermediate
values
C code
B[1] = (B[0] x 4) - i;
size of int = 4 bytes
each element in array take 4 bytes of memory, And memory is byte
addressable(i.e each address has 1 byte of data)
Address of B[0] = (base address of Array B) + 0
Address of B[1] = (base address of Array B) + 4
shifting a binary number left by 1 bit , will result
multipltying by 2 with number.
For example,
Let number = 0100 (Decimal value = 4)
shifting left by 1 bit, number = 1000 (Decimal value = 8)
MIPS code
lw $t0, 0 ($s3) #load B[0] into a register
sll $t0, $t0, 2 #shift value at register $t0 by 2 bit
left, $t0 = B[0] * 4
sub $t0, $t0, $s1 # (B[0] x 4) - i
sw $t0, 4($s0) #store value of
register $t0 in memory at address (base address of Array B) + 4
Therefore, B[1] = (B[0] * 4) - i
(B[0] * 4) This can also be done in this way
add $t0, $t0, $t0 //$t0 = B[0] + B[0] = 2*B[0]
add $t0, $t0, $t0 //$t0 = 2*B[0] + 2*B[0] = 4*B[0]