1
votes

so I am currently stuck on a question and I would be really glad to see if someone can elaborate on my question.

The question is listed below

Let register $s1 be the base of the array A,

register $v0 be the variable X,

register $t0 be the index i,

then write a MIPS instructions for the following statements

K = A[i] + A[i+3];

The solution is listed as below

sll $t1, $t0, 2
add $t2, $s1, $t1
lw $t3, 0($t2)
lw $t4, 12($t2)
add $v0, $t3, $t4

My solution for this question was

addi $t1, $t0, 3  # for the $t1 <- i+3
lw $t2, 0($t1)    # for the $t2 <- A[i+3]
lw $t3, 0($t0)    # for the $t3 <- A[i]
add $v0, $t2, $t3 # for the K <- A[i+3] + A[i]

So the question is,

I don't really understand why the solution didn't add index by 3 (i+3) then load from added index.

Also the 2nd line from the solution, add $t2, $s1, $t1, how is it possible to add a base with an index(i.e. $t2 <- A+i)? Doesn't array represents the memory stack and the index as the location address for the stack?

Thanks in advance.

Any elaboration for this questions with similar question would be very grateful.

1

1 Answers

2
votes

Remember that each index of A is not 32bits. Each index of A is only 8 bits. The code above does the following:

sll $t1, $t0, 2   # take $t0 and shift it over 2 bits
                  # (equivalent to multiply by 4)
add $t2, $s1, $t1 # from the 0 index, add on $t1 to get into the register for A[i]
lw $t3, 0($t2)    # load 4 bytes (the entire 32bits) from A[i]
lw $t4, 12($t2)   # load 4 bytes (the entire 32bits) from A[i + 3] 
                  # where 3 is actually 12 because it's 8bits per index
                  # so multiply by 4
add $v0, $t3, $t4

The big thing to realize was the 8bits (byte) vs. 32bits (word) indexing of the "array."

Looking at your code:

addi $t1, $t0, 3  # actually just moves this over 3 bytes, not 3 words
lw $t2, 0($t1)    # gets the word at A[i / 4]
lw $t3, 0($t0)    # gets the word at A[(i + 3) / 4]
add $v0, $t2, $t3 # and now you can see why this would be wrong.