第 79 / 187 篇

7.4.2. 汇编中的 if 语句

说明

本文是个人学习用的非官方中英对照译文,原文: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 getSmallest function in assembly. For convenience, the function is reproduced below.

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
(gdb) disas getSmallest
Dump of assembler code for function getSmallest:
0x40059a <+4>: mov %edi,-0x14(%rbp)
0x40059d <+7>: mov %esi,-0x18(%rbp)
0x4005a0 <+10>: mov -0x14(%rbp),%eax
0x4005a3 <+13>: cmp -0x18(%rbp),%eax
0x4005a6 <+16>: jle 0x4005b0 <getSmallest+26>
0x4005a8 <+18>: mov -0x18(%rbp),%eax
0x4005ae <+24>: jmp 0x4005b9 <getSmallest+35>
0x4005b0 <+26>: mov -0x14(%rbp),%eax
0x4005b9 <+35>: pop %rbp
0x4005ba <+36>: retq

这是一种与我们之前见过的不同的汇编代码视图。在这里,我们能看到每条指令对应的地址,但看不到字节。注意,为了简单起见,这段汇编代码经过了少许编辑:去掉了通常属于函数开头的那些指令(即 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 %rdi and %rsi, respectively. Since the parameters to getSmallest are of type int, the compiler places the parameters in the respective component registers %edi and %esi 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.

  • 第一条 mov 指令复制寄存器 %edi 中的值(第一个参数 x),把它放到调用栈上的内存位置 %rbp-0x14 处。指令指针(%rip)被设为下一条指令的地址,即 0x40059d。
  • The first mov instruction copies the value located in register %edi (the first parameter, x) and places it at memory location %rbp-0x14 on 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 mov instruction copies the value located in register %esi (the second parameter, y) and places it at memory location %rbp-0x18 on 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 mov instruction copies x to register %eax. Register %rip updates to point to the address of the next instruction in sequence.
  • cmp 指令把位置 %rbp-0x18 处的值(第二个参数 y)与 x 进行比较,并设置相应的条件码标志寄存器。寄存器 %rip 前进到下一条指令的地址,即 0x4005a6。
  • The cmp instruction compares the value at location %rbp-0x18 (the second parameter, y) to x and sets appropriate condition code flag registers. Register %rip advances to the address of the next instruction, or 0x4005a6.
  • 地址 0x4005a6 处的 jle 指令表示:如果 x 小于或等于 y,下一条应当执行的指令位于 <getSmallest+26>,%rip 应当被设为地址 0x4005b0;否则,%rip 被设为顺序中的下一条指令,即 0x4005a8。
  • The jle instruction at address 0x4005a6 indicates that if x is less than or equal to y, the next instruction that should execute should be at location <getSmallest+26> and that %rip should be set to address 0x4005b0. Otherwise, %rip is 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, %rip is 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), %eax instruction at <getSmallest+18> copies y to register %eax. Register %rip advances to 0x4005ae.
  • <getSmallest+24> 处的 jmp 指令把寄存器 %rip 设为地址 0x4005b9。
  • The jmp instruction at <getSmallest+24> sets register %rip to address 0x4005b9.
  • 最后执行的是 pop %rbp 指令和 retq 指令,它们清理栈并从函数调用返回。在这种情况下,y 位于返回寄存器中。
  • The last instructions to execute are the pop %rbp instruction and the retq instruction, which cleans up the stack and returns from the function call. In this case, y is in the return register.

现在,假设在 <getSmallest+16> 处走了分支。换句话说,jle 指令把寄存器 %rip 设为 0x4005b0(<getSmallest+26>)。那么,接下来执行的指令是:

Now, suppose that the branch was taken at <getSmallest+16>. In other words, the jle instruction sets register %rip to 0x4005b0 (<getSmallest+26>). Then, the next instructions to execute are:

  • 地址 0x4005b0 处的 mov -0x14(%rbp),%eax 指令把 x 复制到寄存器 %eax。寄存器 %rip 前进到 0x4005b9。
  • The mov -0x14(%rbp),%eax instruction at address 0x4005b0 copies x to register %eax. Register %rip advances to 0x4005b9.
  • 最后执行的是 pop %rbp 和 retq,它们清理栈并返回返回寄存器中的值。在这种情况下,组成部分寄存器 %eax 中存放的是 x,getSmallest 返回 x。
  • The last instructions that execute are pop %rbp and retq, which clean up the stack and returns the value in the return register. In this case, component register %eax contains x, and getSmallest returns x.

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

We can then annotate the preceding assembly as follows:

1
2
3
4
5
6
7
8
9
10
0x40059a <+4>:  mov %edi,-0x14(%rbp)          # copy x to %rbp-0x14
0x40059d <+7>: mov %esi,-0x18(%rbp) # copy y to %rbp-0x18
0x4005a0 <+10>: mov -0x14(%rbp),%eax # copy x to %eax
0x4005a3 <+13>: cmp -0x18(%rbp),%eax # compare x with y
0x4005a6 <+16>: jle 0x4005b0 <getSmallest+26> # if x<=y goto <getSmallest+26>
0x4005a8 <+18>: mov -0x18(%rbp),%eax # copy y to %eax
0x4005ae <+24>: jmp 0x4005b9 <getSmallest+35> # goto <getSmallest+35>
0x4005b0 <+26>: mov -0x14(%rbp),%eax # copy x to %eax
0x4005b9 <+35>: pop %rbp # restore %rbp (clean up stack)
0x4005ba <+36>: retq # exit function (return %eax)

把它翻译回 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;
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;
if (x <= y) {
smallest = x;
}
else {
smallest = y;
}
return smallest;
}

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

In Table 1, the variable smallest corresponds to register %eax. 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; close inspection of both functions reveals that the two programs are logically equivalent. However, the compiler first converts any 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 jump 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.

cmov 指令

The cmov Instructions

我们要介绍的最后一组条件指令是条件传送(conditional move,cmov)指令。cmp、test 和 jmp 指令在程序中实现的是有条件的控制转移。换句话说,程序的执行会向多个方向分支。这对于优化代码来说可能非常麻烦,因为这些分支的代价很高。

The last set of conditional instructions we cover are conditional move (cmov) instructions. The cmp, test, and jmp 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 these branches are very expensive.

与之不同,cmov 指令实现的是有条件的数据传送。换句话说,条件的 then_statement 和 else_statement 都会被执行,然后根据条件的结果,把数据放到相应的寄存器中。

In contrast, the cmov instruction implements a conditional transfer of data. In other words, both the then_statement and else_statement of 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 cmov instruction 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 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_cmov(int x, int y) {
return x > y ? y : x;
}

这看起来也许不是什么大的改动,但我们来看看生成的汇编。回想一下,第一个和第二个参数(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 (x and y) are stored in registers %edi and %esi, respectively.

1
2
3
4
5
6
7
8
9
0x4005d7 <+0>:   push   %rbp             #save %rbp
0x4005d8 <+1>: mov %rsp,%rbp #update %rbp
0x4005db <+4>: mov %edi,-0x4(%rbp) #copy x to %rbp-0x4
0x4005de <+7>: mov %esi,-0x8(%rbp) #copy y to %rbp-0x8
0x4005e1 <+10>: mov -0x8(%rbp),%eax #copy y to %eax
0x4005e4 <+13>: cmp %eax,-0x4(%rbp) #compare x and y
0x4005e7 <+16>: cmovle -0x4(%rbp),%eax #if (x <=y) copy x to %eax
0x4005eb <+20>: pop %rbp #restore %rbp
0x4005ec <+21>: retq #return %eax

这段汇编代码中没有跳转。比较了 x 和 y 之后,只有当 x 小于或等于 y 时,x 才会被移入返回寄存器。与跳转指令一样,cmov 指令的后缀表示进行条件传送的条件。表 3 列出了条件传送指令的集合。

This assembly code has no jumps. After the comparison of x and y, x moves into the return register only if x is less than or equal to y. Like the jump instructions, the suffix of the cmov instructions 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 (!=)
cmovs move if negative
cmovns move 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 getSmallest function, the compiler’s internal optimizer (see chapter 12) will replace the jump instructions with a cmov instruction if level 1 optimizations are turned on (i.e., -O1):

1
2
3
4
5
6
#compiled with: gcc -O1 -o getSmallest getSmallest.c
<getSmallest>:
0x400546 <+0>: cmp %esi,%edi #compare x and y
0x400548 <+2>: mov %esi,%eax #copy y to %eax
0x40054a <+4>: cmovle %edi,%eax #if (x<=y) copy x to %eax
0x40054d <+7>: retq #return %eax

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

In general, the compiler is very cautious about optimizing jump instructions into cmov instructions, 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
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 if 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.

译注

(*x)++ 是后置自增,所以函数返回的是加一之前的值,加一的结果只写回了 *x。从下面汇编中 mov (%rax),%eax(取出旧值作为返回值)和 lea 0x1(%rax),%ecx(算出新值另存)也能看出这一点。

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
0x4005ed <+0>:   push   %rbp
0x4005ee <+1>: mov %rsp,%rbp
0x4005f1 <+4>: mov %rdi,-0x8(%rbp)
0x4005f5 <+8>: cmpq $0x0,-0x8(%rbp)
0x4005fa <+13>: je 0x40060d <incrementX+32>
0x4005fc <+15>: mov -0x8(%rbp),%rax
0x400600 <+19>: mov (%rax),%eax
0x400602 <+21>: lea 0x1(%rax),%ecx
0x400605 <+24>: mov -0x8(%rbp),%rdx
0x400609 <+28>: mov %ecx,(%rdx)
0x40060b <+30>: jmp 0x400612 <incrementX+37>
0x40060d <+32>: mov $0x1,%eax
0x400612 <+37>: pop %rbp
0x400613 <+38>: retq

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

Recall that the cmov 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 jumps.