说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C7-x86_64/if_statements.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
7.4.2. if Statements in Assembly
我们来看看 getSmallest 函数的汇编。为方便起见,下面再列出这个函数。
Let’s take a look at the
getSmallestfunction in assembly. For convenience, the function is reproduced below.
1 | int getSmallest(int x, int y) { |
从 GDB 中取出的对应汇编代码类似下面这样:
The corresponding assembly code extracted from GDB looks similar to the following:
1 | (gdb) disas getSmallest |
这是一种与我们之前见过的不同的汇编代码视图。在这里,我们能看到每条指令对应的地址,但看不到字节。注意,为了简单起见,这段汇编代码经过了少许编辑:去掉了通常属于函数开头的那些指令(即 push %rbp、mov %rsp, %rbp)。按照惯例,GCC 把函数的第一个和第二个参数分别放在寄存器 %rdi 和 %rsi 中。由于 getSmallest 的参数是 int 类型,编译器把参数分别放在组成部分寄存器 %edi 和 %esi 中。为了清楚起见,我们把这两个参数分别称为 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. The instructions that are normally part of function creation (i.e.,
push %rbp,mov %rsp, %rbp) are removed. By convention, GCC places the first and second parameters of a function in registers%rdiand%rsi, respectively. Since the parameters togetSmallestare of typeint, the compiler places the parameters in the respective component registers%ediand%esiinstead. For the sake of clarity, we refer to these parameters asxandy, 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.
- 第一条
mov指令复制寄存器%edi中的值(第一个参数x),把它放到调用栈上的内存位置%rbp-0x14处。指令指针(%rip)被设为下一条指令的地址,即 0x40059d。
- The first
movinstruction copies the value located in register%edi(the first parameter,x) and places it at memory location%rbp-0x14on the call stack. The instruction pointer (%rip) is set to the address of the next instruction, or 0x40059d.
- 第二条
mov指令复制寄存器%esi中的值(第二个参数y),把它放到调用栈上的内存位置%rbp-0x18处。指令指针(%rip)更新为指向下一条指令的地址,即 0x4005a0。
- The second
movinstruction copies the value located in register%esi(the second parameter,y) and places it at memory location%rbp-0x18on the call stack. The instruction pointer (%rip) updates to point to the address of the next instruction, or 0x4005a0.
- 第三条
mov指令把x复制到寄存器%eax。寄存器%rip更新为指向顺序中下一条指令的地址。
- The third
movinstruction copiesxto register%eax. Register%ripupdates to point to the address of the next instruction in sequence.
cmp指令把位置%rbp-0x18处的值(第二个参数y)与x进行比较,并设置相应的条件码标志寄存器。寄存器%rip前进到下一条指令的地址,即 0x4005a6。
- The
cmpinstruction compares the value at location%rbp-0x18(the second parameter,y) toxand sets appropriate condition code flag registers. Register%ripadvances to the address of the next instruction, or 0x4005a6.
- 地址 0x4005a6 处的
jle指令表示:如果x小于或等于y,下一条应当执行的指令位于<getSmallest+26>,%rip应当被设为地址 0x4005b0;否则,%rip被设为顺序中的下一条指令,即 0x4005a8。
- The
jleinstruction at address 0x4005a6 indicates that ifxis less than or equal toy, the next instruction that should execute should be at location<getSmallest+26>and that%ripshould be set to address 0x4005b0. Otherwise,%ripis set to the next instruction in sequence, or 0x4005a8.
接下来要执行哪些指令,取决于程序是否在地址 0x4005a6 处走了分支(即执行了跳转)。我们先假设没有走分支。这种情况下,%rip 被设为 0x4005a8(即 <getSmallest+18>),接着执行下面的指令序列:
The next instructions to execute depend on whether the program follows the branch (i.e., executes the jump) at address 0x4005a6. Let’s first suppose that the branch was not followed. In this case,
%ripis set to 0x4005a8 (i.e.,<getSmallest+18>) and the following sequence of instructions executes:
<getSmallest+18>处的mov -0x18(%rbp), %eax指令把y复制到寄存器%eax。寄存器%rip前进到 0x4005ae。
- The
mov -0x18(%rbp), %eaxinstruction at<getSmallest+18>copiesyto register%eax. Register%ripadvances to 0x4005ae.
<getSmallest+24>处的jmp指令把寄存器%rip设为地址 0x4005b9。
- The
jmpinstruction at<getSmallest+24>sets register%ripto address 0x4005b9.
- 最后执行的是
pop %rbp指令和retq指令,它们清理栈并从函数调用返回。在这种情况下,y位于返回寄存器中。
- The last instructions to execute are the
pop %rbpinstruction and theretqinstruction, which cleans up the stack and returns from the function call. In this case,yis in the return register.
现在,假设在 <getSmallest+16> 处走了分支。换句话说,jle 指令把寄存器 %rip 设为 0x4005b0(<getSmallest+26>)。那么,接下来执行的指令是:
Now, suppose that the branch was taken at
<getSmallest+16>. In other words, thejleinstruction sets register%ripto 0x4005b0 (<getSmallest+26>). Then, the next instructions to execute are:
- 地址 0x4005b0 处的
mov -0x14(%rbp),%eax指令把x复制到寄存器%eax。寄存器%rip前进到 0x4005b9。
- The
mov -0x14(%rbp),%eaxinstruction at address 0x4005b0 copiesxto register%eax. Register%ripadvances to 0x4005b9.
- 最后执行的是
pop %rbp和retq,它们清理栈并返回返回寄存器中的值。在这种情况下,组成部分寄存器%eax中存放的是x,getSmallest返回x。
- The last instructions that execute are
pop %rbpandretq, which clean up the stack and returns the value in the return register. In this case, component register%eaxcontainsx, andgetSmallestreturnsx.
于是我们可以这样为上面的汇编加上注释:
We can then annotate the preceding assembly as follows:
1 | 0x40059a <+4>: mov %edi,-0x14(%rbp) # copy x to %rbp-0x14 |
把它翻译回 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 对应于寄存器 %eax。如果 x 小于或等于 y,代码执行语句 smallest = x,在这个函数的 goto 形式中,它与 goto 标签 assign_x 相关联。否则,执行语句 smallest = y。goto 标签 done 用来表示应当返回 smallest 中的值。
In Table 1, the variable
smallestcorresponds to register%eax. 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; close inspection of both functions reveals that the two programs are logically equivalent. However, the compiler first converts anyifstatement 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 jump 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.
cmov 指令
The cmov Instructions
我们要介绍的最后一组条件指令是条件传送(conditional move,cmov)指令。cmp、test 和 jmp 指令在程序中实现的是有条件的控制转移。换句话说,程序的执行会向多个方向分支。这对于优化代码来说可能非常麻烦,因为这些分支的代价很高。
The last set of conditional instructions we cover are conditional move (
cmov) instructions. Thecmp,test, andjmpinstructions 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 these branches are very expensive.
与之不同,cmov 指令实现的是有条件的数据传送。换句话说,条件的 then_statement 和 else_statement 都会被执行,然后根据条件的结果,把数据放到相应的寄存器中。
In contrast, the
cmovinstruction implements a conditional transfer of data. In other words, both thethen_statementandelse_statementof the conditional are executed, and the data is placed in the appropriate register based on the result of the condition.
使用 C 的三元表达式(ternary expression)常常会使编译器生成 cmov 指令来代替跳转。对于标准的 if-then-else 语句,三元表达式的形式是:
The use of C’s ternary expression often results in the compiler generating a
cmovinstruction in place of jumps. For the standard if-then-else statement, the ternary expression has the form:
1 | result = (condition) ? then_statement : else_statement; |
我们用这种格式把 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_cmov(int x, int y) { |
这看起来也许不是什么大的改动,但我们来看看生成的汇编。回想一下,第一个和第二个参数(x 和 y)分别存放在寄存器 %edi 和 %esi 中。
Although 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 registers%ediand%esi, respectively.
1 | 0x4005d7 <+0>: push %rbp #save %rbp |
这段汇编代码中没有跳转。比较了 x 和 y 之后,只有当 x 小于或等于 y 时,x 才会被移入返回寄存器。与跳转指令一样,cmov 指令的后缀表示进行条件传送的条件。表 3 列出了条件传送指令的集合。
This assembly code has no jumps. After the comparison of
xandy,xmoves into the return register only ifxis less than or equal toy. Like the jump instructions, the suffix of thecmovinstructions indicates the condition on which the conditional move occurs. Table 3 lists the set of conditional move instructions.
表 3. cmov 指令
Table 3. The cmov Instructions.
| 有符号 | 无符号 | 说明 |
|---|---|---|
cmove (cmovz) |
相等(==)时传送 | |
cmovne (cmovnz) |
不相等(!=)时传送 | |
cmovs |
为负时传送 | |
cmovns |
非负时传送 | |
cmovg (cmovnle) |
cmova (cmovnbe) |
大于(>)时传送 |
cmovge (cmovnl) |
cmovae (cmovnb) |
大于等于(>=)时传送 |
cmovl (cmovnge) |
cmovb (cmovnae) |
小于(<)时传送 |
cmovle (cmovng) |
cmovbe (cmovna) |
小于等于(<=)时传送 |
Signed Unsigned Description cmove(cmovz)move if equal (==) cmovne(cmovnz)move if not equal (!=) cmovsmove if negative cmovnsmove if non-negative cmovg(cmovnle)cmova(cmovnbe)move if greater (>) cmovge(cmovnl)cmovae(cmovnb)move if greater than or equal (>=) cmovl(cmovnge)cmovb(cmovnae)move if less (<) cmovle(cmovng)cmovbe(cmovna)move if less than or equal (<=)
对于原来的 getSmallest 函数,如果打开 1 级优化(即 -O1),编译器内部的优化器(见第 12 章)就会用一条 cmov 指令替换跳转指令:
In the case of the original
getSmallestfunction, the compiler’s internal optimizer (see chapter 12) will replace the jump instructions with acmovinstruction if level 1 optimizations are turned on (i.e.,-O1):
1 | #compiled with: gcc -O1 -o getSmallest getSmallest.c |
一般来说,编译器在把跳转指令优化成 cmov 指令时非常谨慎,尤其是在涉及副作用和指针值的情况下。表 4 展示了 incrementX 函数的两种等价写法:
In general, the compiler is very cautious about optimizing jump instructions into
cmovinstructions, especially in cases where side effects and pointer values are involved. Table 4 shows two equivalent ways of writing a function,incrementX:
表 4. 两个试图让整数 x 的值加一的函数
Table 4. 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 if it is
NULL. Ifxis notNULL, the function increments and returns the dereferenced value ofx. Otherwise, the function returns the value 1.
译注
(*x)++ 是后置自增,所以函数返回的是加一之前的值,加一的结果只写回了 *x。从下面汇编中 mov (%rax),%eax(取出旧值作为返回值)和 lea 0x1(%rax),%ecx(算出新值另存)也能看出这一点。
人们很容易以为 incrementX2 会使用 cmov 指令,因为它用的是三元表达式。然而,两个函数生成的汇编代码完全相同:
It is tempting to think that
incrementX2uses acmovinstruction since it uses a ternary expression. However, both functions yield the exact same assembly code:
1 | 0x4005ed <+0>: push %rbp |
回想一下,cmov 指令会执行条件的两个分支。换句话说,无论如何都会对 x 解引用。考虑 x 是空指针的情况。回想一下,对空指针解引用会在代码中引发空指针异常,导致段错误。为了杜绝这种情况发生的任何可能,编译器选择了稳妥的做法,使用跳转。
Recall that the
cmovinstruction 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 jumps.