C to MIPS Assembly

Bathant Hegazy

I was trying to solve this and convert it to MIPS assembly code but the answer in the book confused me.so, can anyone explain how this code get this result in c ?

B[g] = A[f] + A[f+1];

I have inserted comments for what I think that's right please correct me if I was wrong.

Assume we have variables f, g, h, i, j stored in $s0, $s1, $s2, $s3 and $s4, respectively. Assume the base addresses of arrays A and B are at $s6 and $s7.

The code:

add $t0, $s6, $s0  #This will add f bytes to the base address and it's not equal to A[f].
add $t1, $s7, $s1  #This will add g bytes to the base address and it's not equal to B[g]
lw $s0, 0($t0)     #This will point to the value in (f +base address of A +0) bytes
lw $t0, 4($t0)     #This will point to the value in (f +base address of A +4) bytes
add $t0, $t0, $s0  
sw $t0, 0($t1)
NlightNFotis

Your compiled fragment annotated by me:

add $t0, $s6, $s0  

add and store in register t0 whatever is in register s6 and s0. Since you have pointed out that f is stored in s0 and the base address of A is stored in s6, this adds the addresses in preparation for a register indirect load later on. More simply A[f] == *(A + f) in C, and this is preparing for the (A + f) de-reference later on.

add $t1, $s7, $s1  

The same thing happening for B and g. Add their contents and store them in an intermediate register, to be later used as address based de-reference targets.

lw $s0, 0($t0)     

This is loading to the s0 register, using what's known as the register-indirect addressing mode of the cpu, whatever is at the address pointed to by t0 plus 0 bytes. In c this is equal to s0 = *(A + f).

lw $t0, 4($t0)     

The same thing as above, only that this time it loads to register t0 whatever is pointed at t0 plus 4 bytes. Equal to C t0 = *(A + f + 1).

add $t0, $t0, $s0  

This is the point where it performs the addition in your code. It's equal to the C code fragment of A[f] + A[f + 1].

sw $t0, 0($t1)

This is storing the result of the previous addition to the address pointed to by t1.

~~~~~~~~~~~

If you are looking for some references for the code you have, I found both this MIPS instruction set reference useful and, of course, Matt Godbolt's interactive compiler.

If you want to see what code does what using the interactive compiler, just wrap your code in a void function, select as the compiler x86 clang and at the compiler options --target=mips. Then from the filter apply colourise, and you will be able to see what C code generates what assembly code, to get something like the image below

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related