第 109 / 187 篇

9.4.2. 汇编中的 if 语句

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C9-ARM64/if_statements.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

9.4.2. if Statements in Assembly

我们来看看 getSmallest 函数的汇编。为方便起见,这里再把函数列出来。

Let’s take a look at the getSmallest function in assembly. For convenience, the function is reproduced here.

1
2
3
4
5
6
7
8
9
10
int getSmallest(int x, int y) {
int smallest;
if ( x > y ) {
smallest = y;
}
else {
smallest = x;
}
return smallest;
}

从 GDB 中取出的对应汇编代码类似下面这样:

The corresponding assembly code extracted from GDB looks similar to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(gdb) disas getSmallest
Dump of assembler code for function getSmallest:
0x07f4 <+0>: sub sp, sp, #0x20
0x07f8 <+4>: str w0, [sp, #12]
0x07fc <+8>: str w1, [sp, #8]
0x0800 <+12>: ldr w1, [sp, #12]
0x0804 <+16>: ldr w0, [sp, #8]
0x0808 <+20>: cmp w1, w0
0x080c <+24>: b.le 0x81c <getSmallest+40>
0x0810 <+28>: ldr w0, [sp, #8]
0x0814 <+32>: str w0, [sp, #28]
0x0818 <+36>: b 0x824 <getSmallest+48>
0x081c <+40>: ldr w0, [sp, #12]
0x0820 <+44>: str w0, [sp, #28]
0x0824 <+48>: ldr w0, [sp, #28]
0x0828 <+52>: add sp, sp, #0x20
0x082c <+56>: ret

这是一种与我们之前见过的不同的汇编代码视图。在这里,我们能看到每条指令对应的地址,但看不到字节。注意,为了简单起见,这段汇编代码经过了少许编辑。按照惯例,GCC 把函数的第一个和第二个参数分别放在寄存器 x0 和 x1 中。由于 getSmallest 的参数是 int 类型,编译器把参数分别放在组成部分寄存器 w0 和 w1 中。为了清楚起见,我们把这两个参数分别称为 x 和 y。

This is a different view of the assembly code than we have seen before. Here, we can see the address associated with each instruction, but not the bytes. Note that this assembly segment has been lightly edited for the sake of simplicity. By convention, GCC places the first and second parameters of a function in registers x0 and x1 respectively. Since the parameters to getSmallest are of type int, the compiler places the parameters in the respective component registers w0 and w1 instead. For the sake of clarity, we refer to these parameters as x and y respectively.

我们来跟踪上面这段汇编代码的前几行。注意,在这个例子中我们不会明确地画出栈。我们把它留作读者的练习,鼓励你自己画一画,练习跟踪栈的技能。

Let’s trace through the first few lines of the previous assembly code snippet. Note that we will not draw out the stack explicitly in this example. We leave this as an exercise for the reader, and encourage you to practice your stack tracing skills by drawing it out yourself.

  • sub 指令让调用栈增长 32 字节(0x20)。
  • The sub instruction grows the call stack by 32 bytes (0x20).
  • <getSmallest+4> 和 <getSmallest+8> 处的 str 指令把 x 和 y 分别存到栈位置 sp + 12 和 sp + 8 处。
  • The str instructions at <getSmallest+4> and <getSmallest+8> store x and y at stack locations sp + 12 and sp + 8, respectively.
  • <getSmallest+12> 和 <getSmallest+16> 处的 ldr 指令把 x 和 y 分别加载到寄存器 w1 和 w0 中。注意,w0 和 w1 原来的内容互换了!
  • The ldr instructions at <getSmallest+12> and <getSmallest+16 load x and y into registers w1 and w0, respectively. Note that the original contents of w0 and w1 have swapped!
  • cmp 指令比较 w1 和 w0(即 x 和 y),并设置相应的条件码标志寄存器。
  • The cmp instruction compares w1 to w0 (i.e., x to y) and sets appropriate condition code flag registers.
  • <getSmallest+24> 处的 b.le 指令表示:如果 x 小于或等于 y,下一条应当执行的指令位于 <getSmallest+40>(即 pc = 0x81c);否则,pc 被设为顺序中的下一条指令,即 0x810。
  • The b.le instruction at <getSmallest+24> indicates that if x is less than or equal to y, the next instruction that should execute should be at location <getSmallest+40> (or pc = 0x81c). Otherwise, pc is set to the next instruction in sequence, or 0x810.

接下来执行哪些指令,取决于程序在 <getSmallest+24> 处是否走了分支(即是否执行了跳转)。我们先假设没有走分支。在这种情况下,pc 被设为 0x810(即 <getSmallest+28>),接下来执行下面这串指令:

The next instructions to execute depend on whether the program follows the branch (i.e., executes the jump) at (<getSmallest+24>). Let’s first suppose that the branch was not followed. In this case, pc is set to 0x810 (i.e., <getSmallest+28>) and the following sequence of instructions executes:

  • <getSmallest+28> 处的 ldr 指令把 y 加载到寄存器 w0。
  • The ldr instruction at <getSmallest+28> loads y to register w0.
  • <getSmallest+32> 处的 str 指令把 y 存到栈位置 sp + 28 处。
  • The str instruction at <getSmallest+32> stores y at stack location sp + 28.
  • <getSmallest+36> 处的 b 指令把寄存器 pc 设为地址 0x824。
  • The b instruction at <getSmallest+36> sets register pc to address 0x824.
  • <getSmallest+48> 处的 ldr 指令把 y 加载到寄存器 w0。
  • The ldr instruction at <getSmallest+48> loads y into register w0.
  • 最后两条指令把调用栈恢复为原来的大小,并从函数调用返回。在这种情况下,y 位于返回寄存器 w0 中,getSmallest 返回 y。
  • The last two instructions revert the call stack to its original size and return from the function call. In this case, y is in the return register, w0, and getSmallest returns y.

现在,假设在 <getSmallest+24> 处走了分支。换句话说,b.le 指令把寄存器 pc 设为 0x81c(即 <getSmallest+40>)。那么,接下来执行的指令是:

Now, suppose that the branch was taken at <getSmallest+24>. In other words, the b.le instruction sets register pc to 0x81c (i.e., <getSmallest+40>). Then, the next instructions to execute are:

  • <getSmallest+40> 处的 ldr 指令把 x 加载到寄存器 w0。
  • The ldr instruction at <getSmallest+40> loads x into register w0.
  • <getSmallest+44> 处的 str 指令把 x 存到栈位置 sp + 28 处。
  • The str instruction at <getSmallest+44> stores x at stack location sp + 28.
  • <getSmallest+48> 处的 ldr 指令把 x 加载到寄存器 w0。
  • The ldr instruction at <getSmallest+48> loads x into register w0.
  • 最后两条指令把调用栈恢复为原来的大小,并从函数调用返回。在这种情况下,x 位于返回寄存器 w0 中,getSmallest 返回 x。
  • The last two instructions revert the call stack to its original size and return from the function call. In this case, x is in the return register, w0, and getSmallest returns x.

于是我们可以这样为上面的汇编加上注释:

We can then annotate the preceding assembly as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
0x07f4 <+0>:   sub  sp, sp, #0x20          // grow stack by 32 bytes
0x07f8 <+4>: str w0, [sp, #12] // store x at sp+12
0x07fc <+8>: str w1, [sp, #8] // store y at sp+8
0x0800 <+12>: ldr w1, [sp, #12] // w1 = x
0x0804 <+16>: ldr w0, [sp, #8] // w0 = y
0x0808 <+20>: cmp w1, w0 // compare x and y
0x080c <+24>: b.le 0x81c <getSmallest+40> // if(x <= y) goto <getSmallest+40>
0x0810 <+28>: ldr w0, [sp, #8] // w0 = y
0x0814 <+32>: str w0, [sp, #28] // store y at sp+28 (smallest)
0x0818 <+36>: b 0x824 <getSmallest+48> // goto <getSmallest+48>
0x081c <+40>: ldr w0, [sp, #12] // w0 = x
0x0820 <+44>: str w0, [sp, #28] // store x at sp+28 (smallest)
0x0824 <+48>: ldr w0, [sp, #28] // w0 = smallest
0x0828 <+52>: add sp, sp, #0x20 // clean up stack
0x082c <+56>: ret // return smallest

把它翻译回 C 代码,得到:

Translating this back to C code yields:

表 1. 把 getSmallest() 翻译成 C 的 goto 形式和 C 代码

Table 1. Translating getSmallest() into goto C form and C code.

goto 形式

Goto Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int getSmallest(int x, int y) {
int smallest=y;
if (x <= y) {
goto assign_x;
}
smallest = y;
goto done;

assign_x:
smallest = x;

done:
return smallest;
}

翻译出的 C 代码

Translated C code

1
2
3
4
5
6
7
8
9
10
int getSmallest(int x, int y) {
int smallest=y;
if (x <= y) {
smallest = x;
}
else {
smallest = y;
}
return smallest;
}

在表 1 中,变量 smallest 对应于寄存器 w0。如果 x 小于或等于 y,代码执行语句 smallest = x,在这个函数的 goto 形式中,它与 goto 标签 assign_x 相关联。否则,执行语句 smallest = y。goto 标签 done 用来表示应当返回 smallest 中的值。

In Table 1, the variable smallest corresponds to register w0. If x is less than or equal to y, the code executes the statement smallest = x, which is associated with the goto label assign_x in our goto form of this function. Otherwise, the statement smallest = y is executed. The goto label done is used to indicate that the value in smallest should be returned.

注意,上面由汇编代码翻译出的 C 代码与原来的 getSmallest 函数略有不同。这些差异无关紧要;仔细检查两个函数就会发现,这两个程序在逻辑上是等价的。不过,编译器首先会把每个 if 语句转换成等价的 goto 形式,这就产生了一个略有不同但等价的版本。表 2 展示了标准的 if 语句格式及其等价的 goto 形式。

Notice that the preceding C translation of the assembly code is a bit different from the original getSmallest function. These differences don’t matter; a close inspection of both functions reveals that the two programs are logically equivalent. However, the compiler first converts each if statement into an equivalent goto form, which results in the slightly different, but equivalent, version. Table 2 shows the standard if statement format and its equivalent goto form.

表 2. 标准的 if 语句格式及其等价的 goto 形式

Table 2. Standard if statement format and its equivalent goto form.

C 的 if 语句

C if statement

1
2
3
4
5
6
if (condition) {
then_statement;
}
else {
else_statement;
}

编译器的等价 goto 形式

Compiler’s equivalent goto form

1
2
3
4
5
6
7
8
    if (!condition) {
goto else;
}
then_statement;
goto done;
else:
else_statement;
done:

编译器把代码翻译成汇编时,会在条件为真时安排分支。与之对照,if 语句的结构是在条件不为真时发生「跳转」(跳到 else)。goto 形式体现了这种逻辑上的差异。

Compilers translating code into assembly designate a branch when a condition is true. Contrast this behavior with the structure of an if statement, where a “jump” (to the else) occurs when conditions are not true. The goto form captures this difference in logic.

考虑 getSmallest 函数原来的 goto 翻译,可以看出:

Considering the original goto translation of the getSmallest function, we can see that:

  • x <= y 对应于 !(condition)。
  • x <= y corresponds to !(condition).
  • smallest = x 是 else_statement。
  • smallest = x is the else_statement.
  • smallest = y 这一行是 then_statement。
  • The line smallest = y is the then_statement.
  • 函数的最后一行是 return smallest。
  • The last line in the function is return smallest.

按照上面的注解改写原来的函数,得到:

Rewriting the original version of the function with the preceding annotations yields:

1
2
3
4
5
6
7
8
9
10
int getSmallest(int x, int y) {
int smallest;
if (x > y) { //!(x <= y)
smallest = y; //then_statement
}
else {
smallest = x; //else_statement
}
return smallest;
}

这个版本与原来的 getSmallest 函数完全相同。记住,在 C 代码层面用不同方式编写的函数,可能会被翻译成同一组汇编指令。

This version is identical to the original getSmallest function. Keep in mind that a function written in different ways at the C code level can translate to the same set of assembly instructions.

条件选择指令

The Conditional Select Instruction

我们要介绍的最后一条条件指令是条件选择(conditional select,csel)指令。cmp、tst 和 b 指令在程序中实现的是有条件的控制转移。换句话说,程序的执行会向多个方向分支。这对于优化代码来说可能非常麻烦,因为分支指令会打乱指令流水线(详见体系结构部分),执行代价通常很高。与之不同,csel 指令实现的是有条件的数据传送。换句话说,CPU 同时执行 then_statement 和 else_statement,然后根据条件的结果,把数据放到相应的寄存器中。

The final conditional instruction we cover is the conditional select (csel) instruction. The cmp, tst, and b instructions implement a conditional transfer of control in a program. In other words, the execution of the program branches in many directions. This can be very problematic for optimizing code, because branch instructions are typically very expensive to execute, due to the disruption they can cause to the instruction pipeline (details covered in the Architecture section). In contrast, the csel instruction implements a conditional transfer of data. In other words, the CPU executes both the then_statement and else_statement, and places the data in the appropriate register based on the result of the condition.

使用 C 的三元表达式(ternary expression)常常会使编译器生成 csel 指令来代替分支。对于标准的 if-then-else 语句,三元表达式的形式是:

The use of C’s ternary expression often results in the compiler generating a csel instruction in place of branches. For the standard if-then-else statement, the ternary expression has the form:

1
result = (condition) ? then_expression : else_expression;

我们用这种格式把 getSmallest 函数改写成三元表达式。记住,这个新版本函数的行为与原来的 getSmallest 函数完全相同:

Let’s use this format to rewrite the getSmallest function as a ternary expression. Keep in mind that this new version of the function behaves exactly as the original getSmallest function:

1
2
3
int getSmallest_csel(int x, int y) {
return x > y ? y : x;
}

这看起来也许不是什么大的改动,但我们来看看生成的汇编。回想一下,第一个和第二个参数(x 和 y)分别存放在寄存器 w0 和 w1 中:

While this may not seem like a big change, let’s look at the resulting assembly. Recall that the first and second parameters (x and y) are stored in registers w0 and w1, respectively:

1
2
3
4
5
6
7
8
9
10
11
12
(gdb) disas getSmallest_csel
Dump of assembler code for function getSmallest_csel:
0x0860 <+0>: sub sp, sp, #0x10 // grow stack by 16 bytes
0x0864 <+4>: str w0, [sp, #12] // store x at sp+12
0x0868 <+8>: str w1, [sp, #8] // store y at sp+8
0x086c <+12>: ldr w0, [sp, #8] // w0 = y
0x0870 <+16>: ldr w2, [sp, #12] // w2 = x
0x0874 <+20>: ldr w1, [sp, #12] // w1 = x
0x0878 <+24>: cmp w2, w0 // compare x and y
0x087c <+28>: csel w0, w1, w0, le // if (x <= y) w0 = x, else w0=y
0x0880 <+32>: add sp, sp, #0x10 // restore sp
0x0884 <+36>: ret // return (w0)

这段汇编代码中没有跳转。比较了 x 和 y 之后,只有当 x 小于或等于 y 时,x 才会被移入返回寄存器 w0。

This assembly code has no jumps. After the comparison of x and y, x moves into the return register w0 only if x is less than or equal to y.

csel 指令的结构是:

The structure of the csel instruction is:

1
csel D, R1, R2, C // if (C) D = R1 else D = R2

其中 D 表示目标寄存器,R1 和 R2 是存放待比较值的两个寄存器,C 是要求值的条件。

where D denotes the destination register, R1 and R2 are the two registers containing the values to be compared, and C is the condition to be evaluated.

译注

更准确地说,R1 和 R2 是两个候选值:比较已经由前面的 cmp 完成并记录在条件标志里,csel 只根据条件 C 是否成立,从 R1、R2 中选一个写入 D。例如上面的 csel w0, w1, w0, le 中,被比较的是 cmp w2, w0 里的 w2 和 w0。

与分支指令一样,csel 指令的 C 部分表示进行条件选择的条件。它们与条件分支后缀表中所示的完全相同。

As for the branch instructions, the C component of the csel instructions indicates the condition on which the conditional select occurs. They are identical to those shown in the conditional branch suffix table.

对于原来的 getSmallest 函数,如果打开 1 级优化(即 -O1),编译器内部的优化器(见第 12 章)就会用一条 csel 指令替换 b 指令:

In the case of the original getSmallest function, the compiler’s internal optimizer (see Chapter 12) will replace the b instructions with a csel instruction if level 1 optimizations are turned on (i.e., -O1):

1
2
3
4
5
// compiled with: gcc -O1 -o getSmallest getSmallest.c
Dump of assembler code for function getSmallest:
0x0734 <+0>: cmp w0, w1 // compare x and y
0x0738 <+4>: csel w0, w0, w1, le // if (x<=y) w0=x, else w0=y
0x073c <+8>: ret // return (w0)

一般来说,编译器在把分支指令优化成 csel 指令时非常谨慎,尤其是在涉及副作用和指针值的情况下。表 3 展示了 incrementX 函数的两种等价写法:

In general, the compiler is very cautious about optimizing branch instructions into csel instructions, especially in cases where side effects and pointer values are involved. Table 3 shows two equivalent ways of writing a function called incrementX:

表 3. 两个试图让整数 x 的值加一的函数

Table 3. Two functions that attempt to increment the value of integer x.

C 代码

C code

1
2
3
4
5
6
7
8
int incrementX(int * x) {
if (x != NULL) { //if x is not NULL
return (*x)++; //increment x
}
else { //if x is NULL
return 1; //return 1
}
}

C 三元形式

C ternary form

1
2
3
int incrementX2(int * x){
return x ? (*x)++ : 1;
}

每个函数都以一个指向整数的指针作为输入,并检查它是否为 NULL。如果 x 不为 NULL,函数让 x 所指向的值加一并返回它;否则,函数返回值 1。

Each function takes a pointer to an integer as input and checks whether it is NULL. If x is not NULL, the function increments and returns the dereferenced value of x. Otherwise, the function returns the value 1.

人们很容易以为 incrementX2 会使用 csel 指令,因为它用的是三元表达式。然而,两个函数生成的汇编代码完全相同:

It is tempting to think that incrementX2 uses a csel instruction because it uses a ternary expression. However, both functions yield the exact same assembly code:

1
2
3
4
5
6
7
8
9
// parameter x is in register x0
Dump of assembler code for function incrementX2:
0x0774 <+0>: mov w1, #0x1 // w1 = 0x1
0x0778 <+4>: cbz x0, 0x788 <incrementX2+20> // if(x==0) goto<incrementX2+20>
0x077c <+8>: ldr w1, [x0] // w1 = *x
0x0780 <+12>: add w2, w1, #0x1 // w2 = w1 + 1
0x0784 <+16>: str w2, [x0] // *x = w2
0x0788 <+20>: mov w0, w1 // w0 = *x
0x078c <+24>: ret // return (w0)

回想一下,csel 指令会执行条件的两个分支。换句话说,无论如何都会对 x 解引用。考虑 x 是空指针的情况。回想一下,对空指针解引用会在代码中引发空指针异常,导致段错误。为了杜绝这种情况发生的任何可能,编译器选择了稳妥的做法,使用分支。

Recall that the csel instruction executes both branches of the conditional. In other words, x gets dereferenced no matter what. Consider the case where x is a null pointer. Recall that dereferencing a null pointer leads to a null pointer exception in the code, causing a segmentation fault. To prevent any chance of this happening, the compiler takes the safe road and uses a branch.