I am trying to understand arrays in MIPS. I know that you need to move the stack pointer either forward one word or back (increments of 4). But I don't know how to implement that idea into MIPS code.
j = 0
x = a[j+k]
a[j+k] = a[j]
What I know for certain is to load 0 into a register (j=0), then I think you load word the base address $a0 and make a[j], then you add k to it before sw that value into 0($a0).
li $t0, 0
lw $t0 0($a0)
add $t0, $t0, $a2
sw $t0, ($a0)
We were assigned to convert this code to MIPS, and the previous was the first part of it.
# Register usage
# $a0 = base address of array
# $a1 = n, size of array
# $a2 = k, the shift amount
# j = 0
# x = a[j+k]
# a[j+k] = a[j]
# repeat n-1 times
# j = (j+k) mod n
# m = (j+k) mod n
# y = a[m]
# a[m] = x
# x = y
# end repeat
My question is how do I do the n-1 times loop in MIPS? is it a condition then just
subi $a1 $a1
And finally how to find the mod? I believe it is with div and then the $HI. This is what I have so far.
add $t1, $t0, $a2 #j+k
div $t1, $a1 #divide (j+k) by n
mfhi $t2 #move rem into t2
move $t2, $t0 #j = (j+k) mod n
add $t1, $t0, $a2 #j+k
div $t1, $a1 #divide (j+k) by n
mfhi $t2 #move rem into t2
move $t2, $t0 #m = (j+k) mod n
sw $t0, 0($t0)
lw $t3, 0($t0)
I'm confusing myself I believe. Clarification would be appreciated.