数组作为连续元素存储在内存中。
如果@v 是数组的地址,它将是v[0] 的地址。如果数组项为 8 个字节,则 i[1] 将位于 @v+8,i[2] 将位于 @v+16,以此类推。
-------------------------------------------------------------------------------
| v[0] | v[1] | v[2] | v[3] | .... | v[i] |
-------------------------------------------------------------------------------
^ ^ ^ ^ ^
| | | | |
@v @v+8 @v+16 @v+24 @v+i*8
我们想做 v[i] = v[i] * 2
认为
- i 的副本存储在 reg x1 中
- @v 的副本存储在 x0 中
我们需要做的是
// 1. compute i*8 and put it in x0
lsl x1, x1, 3 // multiply i by 8 because vec of 8 byte ints
// 2. add i*8 to @v in order to compute @v[i] in x0
add x0, x0, x1 // add offset to base address of array
// 2. fetch v[i] === value at @x0 and write it to x2
ldr x2, [x0, 0] // load item from memory
// 3. multiply x2 by 2
lsl x2, x2, 1 // multiply it by 2.
// 4. write back this value at address x0
str x2, [x0, 0] // store it back to memory
请注意,第一条指令将 x1 乘以 8,因为 i 8 == i 2^3 == i<<3。第一条指令可能是这样的
mul x1, x1, 8 // illegal
但是在 arm asm 中不存在立即数乘法,它需要两条指令。
mov x4, 8
mul x1, x1, x4
移位指令是等效的(并且更便宜)。