why i need sll to add four zeros in $t1, i dont understand the need to multiply $s3 with 2 twice using sll

173 Views Asked by At

c code

while (save[i]==k)
i+=1;

put i in $s3, k in $s5 and address of k in $s6

mips code

loop: sll $t1, $s3, 2
      add $t1, $t1, $s6
      lw $t0, 0($t1)
      bne $t0, $s5, Exit
      addi $s3, $s3, 1
      j loop
Exit:
1

There are 1 best solutions below

2
On

Your save array/pointer must be of some 4-byte type (ints?). Therefore to load save[i] from memory, the index i needs to be translated to a byte offset within the array, and then added to the base address of that array. This is done by multiplying i by four:

sll $t1, $s3, 2

and then adding save:

add $t1, $t1, $s6

This doesn't look like an optimized build though. Usually the compiler can re-write this code to advance a temporary pointer in increments of four directly, thus avoiding two of the instructions in that loop.