说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C9-ARM64/arrays.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
9.7. Arrays
回想一下,数组是同类型数据元素的有序集合,这些元素在内存中连续存放。静态分配的一维数组形如 Type arr[N],其中 Type 是数据类型,arr 是与数组关联的标识符,N 是数据元素的个数。无论是静态地声明为 Type arr[N],还是动态地写成 arr = malloc(N*sizeof(Type)),都会分配总共 N × sizeof(Type) 字节的内存。
Recall that arrays are ordered collections of data elements of the same type that are contiguously stored in memory. Statically allocated single-dimension arrays have the form
Type arr[N], whereTypeis the data type,arris the identifier associated with the array, andNis the number of data elements. Declaring an array statically asType arr[N]or dynamically asarr = malloc(N*sizeof(Type))allocates N ×sizeof(Type) total bytes of memory.
要访问数组 arr 中下标为 i 的元素,使用语法 arr[i]。编译器在翻译成汇编之前,通常会把数组引用转换成指针运算。所以,arr+i 等价于 &arr[i],*(arr+i) 等价于 arr[i]。由于 arr 中的每个数据元素都是 Type 类型,arr+i 意味着元素 i 存放在地址 arr + sizeof(Type) * i 处。
To access the element at index
iin arrayarr, use the syntaxarr[i]. Compilers commonly convert array references into pointer arithmetic prior to translating to assembly. So ,arr+iis equivalent to&arr[i], and*(arr+i)is equivalent toarr[i]. Since each data element inarris of typeType,arr+iimplies that elementiis stored at addressarr + sizeof(Type) * i.
表 1 概括了一些常见的数组操作及其对应的汇编指令。在下面的例子中,假设我们声明了一个长度为 10 的 int 数组(例如 int arr[10])。假设寄存器 x1 存放 arr 的地址,寄存器 x2 存放 int 值 i,寄存器 x0 代表某个变量 x(也是 int 类型)。回想一下,int 变量占四个字节,而 int * 变量占八个字节。
Table 1 outlines some common array operations and their corresponding assembly instructions. In the examples that follow, suppose we declare an
intarray of length 10 (e.g.,int arr[10]). Assume that registerx1stores the address ofarr, registerx2stores theintvaluei, and registerx0represents some variablex(also of typeint). Recall thatintvariables take up four bytes of space, whereasint *variables take up eight bytes.
表 1. 常见的数组操作及其对应的汇编表示
Table 1. Common Array Operations and Their Corresponding Assembly Representations
| 操作 | 类型 | 汇编表示 |
|---|---|---|
x = arr |
int * |
mov x0, x1 |
x = arr[0] |
int |
ldr w0, [x1] |
x = arr[i] |
int |
ldr w0, [x1, x2, LSL, #2] |
x = &arr[3] |
int * |
add x0, x1, #12 |
x = arr+3 |
int * |
add x0, x1, #12 |
x = *(arr+5) |
int |
ldr w0, [x1, #20] |
Operation Type Assembly Representation x = arrint *mov x0, x1x = arr[0]intldr w0, [x1]x = arr[i]intldr w0, [x1, x2, LSL, #2]x = &arr[3]int *add x0, x1, #12x = arr+3int *add x0, x1, #12x = *(arr+5)intldr w0, [x1, #20]
译注
与 9.1 节表 1 的译注相同,实际语法应写作 ldr w0, [x1, x2, lsl #2](lsl 与 #2 之间没有逗号)。另外,i 是 32 位的 int,若它只在 w2 中,严格的写法是 ldr w0, [x1, w2, sxtw #2],先符号扩展再左移。
注意,要访问元素 arr[5](或用指针运算写成 *(arr+5)),编译器是在地址 arr+5*4 而不是 arr+5 上执行内存查找。要理解为什么必须这样,回想一下,数组中下标为 i 的任何元素都存放在地址 arr + sizeof(Type) * i 处。因此,编译器必须把下标乘以数据类型的大小(这里是 4,因为 sizeof(int) = 4),才能算出正确的偏移量。再回想一下,内存是按字节编址的;偏移正确的字节数,就等同于算出了地址。
Notice that to access element
arr[5](or*(arr+5)using pointer arithmetic), the compiler performs a memory lookup on addressarr+5*4instead ofarr+5. To understand why this is necessary, recall that any element at indexiin an array is stored at addressarr + sizeof(Type) * i. The compiler must therefore multiply the index by the size of the data type (in this case 4, sincesizeof(int) = 4) to compute the correct offset. Recall also that memory is byte-addressable; offsetting by the correct number of bytes is the same as computing an address.
举个例子,考虑一个含有 10 个整数元素的示例数组(array)(图 1)。
As an example, consider a sample array (
array) with 10 integer elements ([FigArray6]).

图 1. 一个十元素整数数组在内存中的布局。每个标为 ai 的方框代表四个字节的偏移,因为每个整数需要四个字节来存储。
Figure 1. The layout of a ten-integer array in memory. Each ai-labeled box represents an offset of four bytes, as each integer requires four bytes to store.
注意,由于 array 是一个整数数组,每个元素恰好占四个字节。因此,一个有 10 个元素的整数数组占用 40 个字节的连续内存。
Notice that since
arrayis an array of integers, each element takes up exactly four bytes. Thus, an integer array with 10 elements consumes 40 bytes of contiguous memory.
为了计算元素 3 的地址,编译器把下标 3 乘以整数类型的数据大小(4),得到偏移量 12(即 0xc)。果然,图 1 中的元素 3 位于字节偏移 a12 处。
To compute the address of element 3, the compiler multiplies the index 3 by the data size of the integer type (4) to yield an offset of 12 (or 0xc). Sure enough, element 3 in Figure 1 is located at byte offset a12.
我们来看一个简单的 C 函数 sumArray,它把数组中的所有元素加起来:
Let’s take a look at a simple C function called
sumArraythat sums up all the elements in an array:
1 | int sumArray(int *array, int length) { |
sumArray 函数接收一个数组的地址和数组的长度,把数组中的所有元素加起来。现在来看 sumArray 函数对应的汇编:
The
sumArrayfunction takes the address of an array and the array’s associated length and sums up all the elements in the array. Now take a look at the corresponding assembly of thesumArrayfunction:
1 | Dump of assembler code for function sumArray: |
跟踪这段汇编代码时,要考虑被访问的数据代表的是指针还是值。例如,<sumArray+12> 处的指令使栈位置 sp + 28 存放一个 int 类型的变量,它的初值被设为 0。与之不同,存放在位置 sp + 8 处的参数是函数的第一个参数(array),它的类型是 int *,对应于数组的基地址。另一个变量(我们称之为 i)存放在位置 sp + 24 处,初值也被设为 0。
When tracing this assembly code, consider whether the data being accessed represents a pointer or a value. For example, the instruction at
<sumArray+12>results in stack locationsp + 28containing a variable of typeint, which is initially set to0. In contrast, the argument stored at locationsp + 8is the first argument to the function (array), which is of typeint *and corresponds to the base address of the array. A different variable (which we calli) is stored at locationsp + 24and is initially set to 0.
细心的读者会注意到 <sumArray+30> 这一行有一条之前没见过的指令 ldrsw。ldrsw 指令的意思是「加载寄存器有符号字」(load register signed word),它把存放在 sp + 24 处的 32 位 int 值转换成 64 位整数值,并存入 x0。这个操作是必要的,因为接下来的指令要进行指针运算。回想一下,在 64 位系统上,指针占八个字节。编译器使用 ldrsw,确保所有数据都存放在完整的 64 位寄存器而不是其 32 位组成部分中,从而简化了处理过程。
The astute reader will notice a previously unseen instruction at line
<sumArray+30>calledldrsw. Theldrswinstruction stands for “load register signed word” and converts the 32-bitintvalue stored atsp + 24to a 64-bit integer value and stores it inx0. This operation is necessary because the instructions that follow perform pointer arithmetic. Recall that on 64-bit systems, pointers take up eight bytes of space. The compiler’s use ofldrswsimplifies the process by ensuring that all data are stored in full 64-bit registers instead of their 32-bit components.
译注
按清单,ldrsw 位于 <sumArray+24>(下文第 21 段也是这么写的)。A64 指令都是 4 字节对齐的,偏移量不可能是 30。
我们来仔细看看位置 <sumArray+28> 和 <sumArray+52> 之间的七条指令:
Let’s take a closer look at the seven instructions between locations
<sumArray+28>and<sumArray+52>:
1 | 0x890 <+28>: lsl x0, x0, #2 // left shift i by 2 (i << 2, or i*4) |
编译器用 lsl 对存放在 x0 中的值 i 执行左移。这条指令执行完后,寄存器 x0 中存放的是 i << 2,即 i * 4。此时,x0 中存放的是为了算出 array[i] 的正确偏移量所需的字节数(因为 sizeof(int) = 4)。
The compiler uses
lslto perform a left shift on the valueistored inx0. When this instruction completes execution, registerx0containsi << 2, ori * 4. At this point,x0contains the number of bytes to calculate the correct offset ofarray[i](orsizeof(int) = 4).
下一条指令(ldr x1, [sp, #8])把函数的第一个参数(即 array 的基地址)加载到寄存器 x1 中。下一条指令把 x1 加到 x0 上,使 x0 存放 array + i * 4。回想一下,array 中下标为 i 的元素存放在地址 array + sizeof(T) * i 处。因此,x0 现在存放的是在汇编层面计算出的地址 &array[i]。
The next instruction (
ldr x1, [sp, #8]) loads the first argument to the function (i.e., the base address ofarray) into registerx1. Addingx1tox0in the next instruction causesx0to containarray + i * 4. Recall that the element at indexiinarrayis stored at addressarray + sizeof(T) * iTherefore,x0now contains the assembly-level computation of address&array[i].
<sumArray+40> 处的指令对位于 x0 的值解引用,把值 array[i] 放入 w1。注意这里使用的是组成部分寄存器 w1,因为 array[i] 存放的是 32 位的 int 值!与之不同,变量 i 在 <sumArray+24> 这一行被转换成了 64 位整数,因为 i 即将用于地址计算。再说一遍,地址(指针)是以 64 位字的形式存放的。
The instruction at
<sumArray+40>dereferences the value located atx0, placing the valuearray[i]intow1. Notice the use of the component registerw1, becausearray[i]contains a 32-bitintvalue! In contrast, the variableiwas changed to a 64-bit integer on line<sumArray+24>sinceiwas about to be used for address computation. Again, addresses (pointers) are stored as 64-bit words.
译注
按清单,<sumArray+40> 处是 ldr w0, [x0],array[i] 被放进的是 w0 而不是 w1;w1 是下一条指令用来存放 total 的。
<sumArray+44> 到 <sumArray+52> 之间的最后三条指令把 total 的当前值加载到组成部分寄存器 w1 中,把 array[i] 加到它上面,把结果存入组成部分寄存器 w0,然后用新的和更新位于 sp + 28 的 total。因此,<sumArray+28> 和 <sumArray+52> 之间的七条指令等价于 sumArray 函数中的 total += array[i] 这一行。
The last three instructions between
<sumArray+44>and<sumArray+52>load the current value oftotalinto component registerw1, addarray[i]to it, and store the result in component registerw0, before updatingtotalat locationsp + 28with the new sum. Therefore, the seven instructions between<sumArray+28>and<sumArray+52>are equivalent to the linetotal += array[i]in thesumArrayfunction.