When I load a variable using 4-byte offset, how would I load that variable into an array?
For example... if I have the C assignment statement:
B[8] = A[i] + A[j]
lw $t0, 4j($s6) # load A[j] into $t0
lw $ti, 4i($s6) # load A[i] into $t1
add $t0, $t0, $t1 # Register $t0 gets A[i] + A[j]
sw $t0, 32($s7) # Stores A[i] + A[j] into B[8]
Would this be the correct way to do the offset for variable? The 4j and 4i part is where I'm really confused.
Edit: i and j have the registers $s3 and $s4, but I don't know how to use
The offset is a 16-bit signed integer contained in the instruction. The sum of the address in the base register with the (sign-extended) offset forms the memory address.
In MIPS you can use a register, an offset, or the addition of both; but not two registers to form an effective address.
You're pretty close, you just need to calculate the offsets:
li $s2, 4 # put constant 4 in s2
multu $s2, $s3 # multiply s3 by 4
mflo $s3 # put multiplication result back in s3
multu $s2, $s4 # multiply s4 by 4
mflo $s4 # put multiplication result back in s4
add $s4, $s6, $s4 # s4 = pointer to A[j]
add $s3, $s6, $s3 # s3 = pointer to A[i]
lw $t0, ($s4) # load A[j] into t0
lw $t1, ($s3) # load A[i] into t1
add $t0, $t0, $t1 # t0 = A[j] + A[i]
sw $t0, 32($s7) # B[8] = A[i] + A[j]
Assume $s0
stores i
and $s1
stores j
. Base address of A
and B
are $s6
, $s7
respectively.
sll $t0, $s0, 2 #offsets 4*i
sll $t1, $s1, 2 #offsets 4*j
add $t0, $t0, $s6 #Pointer to A[i]
add $t1, $t1, $s6 #Pointer to A[j]
lw $t0, 0($t0) #loads A[i] to $t0
lw $t1, 0($t1) #loads A[j] to $t1
add $t2, $t1, $t0 #A[i]+A[j]
sw $t2, 32($s7) #stores A[i]+A[j] to B[8]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With