Reputation: 303
Trying to understand how to do t0 = A[j-1]
in MIPs by looking at an example of t1=A[j]
Details
1. j is $s2, initialized to 5
2. i is $s1
3. Array is $s0
I have the example
t1=A[j]
MIPS
sll $t3, $s2, 2 //I don't really understand why we need to do a left shift of 2
add $t5, $s0, $t3
lw $1, 0($t5)
I referenced to another stackoverflow post which stated
So the instruction sll $t0, $s0, 2 is multiplying $s0 by 4 (2^2) and writing back to $t0.
But i do not see any multiplication for t0 = A[j]
Upvotes: 1
Views: 2931
Reputation: 16626
The memory in your MIPS machine is addressable by bytes, i.e. there is one byte (8 bits) of memory at address 0, one at address 1, etc.. Whole "word" on MIPS machine consist of four bytes (32 bits). So you can interpret bytes at addresses 0 to 3 as single word. And then you can interpret also bytes at addresses 1 to 4, 2 to 5, ... 4 to 7 as single words, but all of them except the last 4..7 option are partially overlapping with 0..3 bytes.
So to store array of words (32 bit integers) in memory, where each element of array has independent value, not affected by other elements, you need 4*N bytes of memory at least.
Your A
is pointing at address of first byte of first element in the array. then A+1, A+2 and A+3 addresses are still pointing at following bytes of the first element. The A+4 address is address of first byte of second element.
The C language has built-in "pointer math", where expression like *(A+2)
is identical to A[2]
, because the C compiler will check the type of the pointer, and multiply the "2" by the size of single element.
But in assembly you have to do this yourself, i.e. in byte array the address of A[j]
is simple adr = A + j
, but for word array with each element occupying four bytes the correct address calculation is adr = A + j*4
.
The shift left by two bits is, thanks to the way how binary encoding of integer works, identical to multiplying the number by value 4.
so the sll $t3, $s2, 2
is actually t3 = j * 4
, which is later added to A
address, and the final value is used as address to load word from.
Similarly to access A[j-1]
(in C syntax) in MIPS assembly you have to calculate the raw memory address as adr = A + j*4 - 4
(or adr = A + (j-1)*4
, whichever is simpler to implement ... actually usually in these kinds of loops you don't calculate the pointer every time, but keep the previous pointer value, and just do +-4 to it to move to next/previous element in memory, without multiplication/shifting).
Upvotes: 3