说明
本文是个人学习用的非官方中英对照译文,原文: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
getSmallestfunction in assembly. For convenience, the function is reproduced here.
1 | int getSmallest(int x, int y) { |
从 GDB 中取出的对应汇编代码类似下面这样:
The corresponding assembly code extracted from GDB looks similar to the following:
1 | (gdb) disas getSmallest |
这是一种与我们之前见过的不同的汇编代码视图。在这里,我们能看到每条指令对应的地址,但看不到字节。注意,为了简单起见,这段汇编代码经过了少许编辑。按照惯例,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
x0andx1respectively. Since the parameters togetSmallestare of typeint, the compiler places the parameters in the respective component registersw0andw1instead. For the sake of clarity, we refer to these parameters asxandyrespectively.
我们来跟踪上面这段汇编代码的前几行。注意,在这个例子中我们不会明确地画出栈。我们把它留作读者的练习,鼓励你自己画一画,练习跟踪栈的技能。
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
subinstruction grows the call stack by 32 bytes (0x20).
<getSmallest+4>和<getSmallest+8>处的str指令把x和y分别存到栈位置sp + 12和sp + 8处。
- The
strinstructions at<getSmallest+4>and<getSmallest+8>storexandyat stack locationssp + 12andsp + 8, respectively.
<getSmallest+12>和<getSmallest+16>处的ldr指令把x和y分别加载到寄存器w1和w0中。注意,w0和w1原来的内容互换了!
- The
ldrinstructions at<getSmallest+12>and<getSmallest+16loadxandyinto registersw1andw0, respectively. Note that the original contents ofw0andw1have swapped!
cmp指令比较w1和w0(即x和y),并设置相应的条件码标志寄存器。
- The
cmpinstruction comparesw1tow0(i.e.,xtoy) and sets appropriate condition code flag registers.
<getSmallest+24>处的b.le指令表示:如果x小于或等于y,下一条应当执行的指令位于<getSmallest+40>(即pc= 0x81c);否则,pc被设为顺序中的下一条指令,即 0x810。
- The
b.leinstruction at<getSmallest+24>indicates that ifxis less than or equal toy, the next instruction that should execute should be at location<getSmallest+40>(orpc= 0x81c). Otherwise,pcis 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,pcis set to 0x810 (i.e.,<getSmallest+28>) and the following sequence of instructions executes:
<getSmallest+28>处的ldr指令把y加载到寄存器w0。
- The
ldrinstruction at<getSmallest+28>loadsyto registerw0.
<getSmallest+32>处的str指令把y存到栈位置sp + 28处。
- The
strinstruction at<getSmallest+32>storesyat stack locationsp + 28.
<getSmallest+36>处的b指令把寄存器pc设为地址 0x824。
- The
binstruction at<getSmallest+36>sets registerpcto address 0x824.
<getSmallest+48>处的ldr指令把y加载到寄存器w0。
- The
ldrinstruction at<getSmallest+48>loadsyinto registerw0.
- 最后两条指令把调用栈恢复为原来的大小,并从函数调用返回。在这种情况下,
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,
yis in the return register,w0, andgetSmallestreturnsy.
现在,假设在 <getSmallest+24> 处走了分支。换句话说,b.le 指令把寄存器 pc 设为 0x81c(即 <getSmallest+40>)。那么,接下来执行的指令是:
Now, suppose that the branch was taken at
<getSmallest+24>. In other words, theb.leinstruction sets registerpcto 0x81c (i.e.,<getSmallest+40>). Then, the next instructions to execute are:
<getSmallest+40>处的ldr指令把x加载到寄存器w0。
- The
ldrinstruction at<getSmallest+40>loadsxinto registerw0.
<getSmallest+44>处的str指令把x存到栈位置sp + 28处。
- The
strinstruction at<getSmallest+44>storesxat stack locationsp + 28.
<getSmallest+48>处的ldr指令把x加载到寄存器w0。
- The
ldrinstruction at<getSmallest+48>loadsxinto registerw0.
- 最后两条指令把调用栈恢复为原来的大小,并从函数调用返回。在这种情况下,
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,
xis in the return register,w0, andgetSmallestreturnsx.
于是我们可以这样为上面的汇编加上注释:
We can then annotate the preceding assembly as follows:
1 | 0x07f4 <+0>: sub sp, sp, #0x20 // grow stack by 32 bytes |
把它翻译回 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 | int getSmallest(int x, int y) { |
翻译出的 C 代码
Translated C code
1 | int getSmallest(int x, int y) { |
在表 1 中,变量 smallest 对应于寄存器 w0。如果 x 小于或等于 y,代码执行语句 smallest = x,在这个函数的 goto 形式中,它与 goto 标签 assign_x 相关联。否则,执行语句 smallest = y。goto 标签 done 用来表示应当返回 smallest 中的值。
In Table 1, the variable
smallestcorresponds to registerw0. Ifxis less than or equal toy, the code executes the statementsmallest = x, which is associated with thegotolabelassign_xin ourgotoform of this function. Otherwise, the statementsmallest = yis executed. Thegotolabeldoneis used to indicate that the value insmallestshould 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
getSmallestfunction. 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 equivalentgotoform, which results in the slightly different, but equivalent, version. Table 2 shows the standardifstatement format and its equivalentgotoform.
表 2. 标准的 if 语句格式及其等价的 goto 形式
Table 2. Standard if statement format and its equivalent goto form.
C 的 if 语句
C if statement
1 | if (condition) { |
编译器的等价 goto 形式
Compiler’s equivalent goto form
1 | if (!condition) { |
编译器把代码翻译成汇编时,会在条件为真时安排分支。与之对照,if 语句的结构是在条件不为真时发生「跳转」(跳到 else)。goto 形式体现了这种逻辑上的差异。
Compilers translating code into assembly designate a branch when a condition is true. Contrast this behavior with the structure of an
ifstatement, where a “jump” (to theelse) occurs when conditions are not true. Thegotoform captures this difference in logic.
考虑 getSmallest 函数原来的 goto 翻译,可以看出:
Considering the original
gototranslation of thegetSmallestfunction, we can see that:
x <= y对应于!(condition)。
x <= ycorresponds to!(condition).
smallest = x是else_statement。
smallest = xis theelse_statement.
smallest = y这一行是then_statement。
- The line
smallest = yis thethen_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 | int getSmallest(int x, int y) { |
这个版本与原来的 getSmallest 函数完全相同。记住,在 C 代码层面用不同方式编写的函数,可能会被翻译成同一组汇编指令。
This version is identical to the original
getSmallestfunction. 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. Thecmp,tst, andbinstructions 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, thecselinstruction implements a conditional transfer of data. In other words, the CPU executes both thethen_statementandelse_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
cselinstruction 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
getSmallestfunction as a ternary expression. Keep in mind that this new version of the function behaves exactly as the originalgetSmallestfunction:
1 | int getSmallest_csel(int x, int y) { |
这看起来也许不是什么大的改动,但我们来看看生成的汇编。回想一下,第一个和第二个参数(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 (
xandy) are stored in registersw0andw1, respectively:
1 | (gdb) disas getSmallest_csel |
这段汇编代码中没有跳转。比较了 x 和 y 之后,只有当 x 小于或等于 y 时,x 才会被移入返回寄存器 w0。
This assembly code has no jumps. After the comparison of
xandy,xmoves into the return registerw0only ifxis less than or equal toy.
csel 指令的结构是:
The structure of the
cselinstruction is:
1 | csel D, R1, R2, C // if (C) D = R1 else D = R2 |
其中 D 表示目标寄存器,R1 和 R2 是存放待比较值的两个寄存器,C 是要求值的条件。
where
Ddenotes the destination register,R1andR2are the two registers containing the values to be compared, andCis 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
Ccomponent of thecselinstructions 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
getSmallestfunction, the compiler’s internal optimizer (see Chapter 12) will replace thebinstructions with acselinstruction if level 1 optimizations are turned on (i.e.,-O1):
1 | // compiled with: gcc -O1 -o getSmallest getSmallest.c |
一般来说,编译器在把分支指令优化成 csel 指令时非常谨慎,尤其是在涉及副作用和指针值的情况下。表 3 展示了 incrementX 函数的两种等价写法:
In general, the compiler is very cautious about optimizing branch instructions into
cselinstructions, especially in cases where side effects and pointer values are involved. Table 3 shows two equivalent ways of writing a function calledincrementX:
表 3. 两个试图让整数 x 的值加一的函数
Table 3. Two functions that attempt to increment the value of integer x.
C 代码
C code
1 | int incrementX(int * x) { |
C 三元形式
C ternary form
1 | int incrementX2(int * x){ |
每个函数都以一个指向整数的指针作为输入,并检查它是否为 NULL。如果 x 不为 NULL,函数让 x 所指向的值加一并返回它;否则,函数返回值 1。
Each function takes a pointer to an integer as input and checks whether it is
NULL. Ifxis notNULL, the function increments and returns the dereferenced value ofx. Otherwise, the function returns the value 1.
人们很容易以为 incrementX2 会使用 csel 指令,因为它用的是三元表达式。然而,两个函数生成的汇编代码完全相同:
It is tempting to think that
incrementX2uses acselinstruction because it uses a ternary expression. However, both functions yield the exact same assembly code:
1 | // parameter x is in register x0 |
回想一下,csel 指令会执行条件的两个分支。换句话说,无论如何都会对 x 解引用。考虑 x 是空指针的情况。回想一下,对空指针解引用会在代码中引发空指针异常,导致段错误。为了杜绝这种情况发生的任何可能,编译器选择了稳妥的做法,使用分支。
Recall that the
cselinstruction executes both branches of the conditional. In other words,xgets dereferenced no matter what. Consider the case wherexis 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.