说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C7-x86_64/loops.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
7.4.3. Loops in Assembly
与 if 语句一样,汇编中的循环也是用跳转指令实现的。不过,循环让指令可以根据对条件求值的结果被重新执行。
Like
ifstatements, loops in assembly are also implemented using jump instructions. However, loops enable instructions to be revisited based on the result of an evaluated condition.
下例中的 sumUp 函数把从 1 到用户给定整数之间的所有正整数加起来。这段代码故意写得不够优化,以便演示 C 中的 while 循环。
The
sumUpfunction shown in the following example sums up all the positive integers from 1 to a user-defined integer. This code is intentionally written suboptimally to illustrate awhileloop in C.
1 | int sumUp(int n) { |
编译这段代码并用 GDB 反汇编,得到如下汇编代码:
Compiling this code and disassembling it using GDB yields the following assembly code:
1 | Dump of assembler code for function sumUp: |
同样,在这个例子中我们不会明确地画出栈。不过,我们鼓励读者自己把栈画出来。
Again, we will not draw out the stack explicitly in this example. However, we encourage readers to draw the stack out themselves.
前五条指令
The First Five Instructions
这个函数的前五条指令为函数的执行准备好栈,并为函数执行设置好临时值:
The first five instructions of this function set the stack up for function execution and set up temporary values for function execution:
1 | 0x400526 <+0>: push %rbp # save %rbp onto the stack |
回想一下,栈上的位置存放函数中的临时变量。为了简单起见,我们把 %rbp-0x8 所标记的位置称为 total,把 %rbp - 0x4 称为 i。sumUp 的输入参数(n)被移到栈位置 %rbp-0x14。尽管临时变量被放在了栈上,但要记住,执行完第一条指令(即 push %rbp)之后,栈指针就没有再改变过。
Recall that stack locations store temporary variables in a function. For simplicity we will refer to the location marked by
%rbp-0x8astotaland%rbp - 0x4asi. The input parameter tosumUp(n) is moved to stack location%rbp-0x14. Despite the placement of temporary variables on the stack, keep in mind that the stack pointer has not changed after the execution of the first instruction (i.e.,push %rbp).
译注
这里没有用 sub 移动 %rsp,就把变量放在了 %rsp 下方,这是因为 sumUp 是叶子函数(不再调用其他函数)。x86-64 System V ABI 规定栈指针下方有 128 字节的「红区」(red zone),叶子函数可以直接使用而不必调整 %rsp。
循环的核心
The Heart of the Loop
sumUp 函数中接下来的七条指令构成了循环的核心:
The next seven instructions in the
sumUpfunction represent the heart of the loop:
1 | 0x40053b <+21>: jmp 0x400547 <sumUp+33> # goto <sumUp+33> |
- 第一条指令是直接跳转到
<sumUp+33>,它把指令指针(%rip)设为地址 0x400547。
- The first instruction is a direct jump to
<sumUp+33>, which sets the instruction pointer (%rip) to address 0x400547.
- 接下来执行的指令是
mov -0x4(%rbp),%eax,它把i的值放到寄存器%eax中。寄存器%rip更新为 0x40054a。
- The next instruction that executes is
mov -0x4(%rbp),%eax, which places the value ofiin register%eax. Register%ripis updated to 0x40054a.
<sumUp+36>处的cmp指令比较i和n,并设置相应的条件码寄存器。寄存器%rip被设为 0x40054d。
- The
cmpinstruction at<sumUp+36>comparesitonand sets the appropriate condition code registers. Register%ripis set to 0x40054d.
然后执行 jle 指令。接下来执行哪些指令,取决于是否走分支。
The
jleinstruction then executes. The instructions that execute next depend on whether or not the branch is taken.
假设走了分支(即 i <= n 为真)。那么指令指针被设为 0x40053d,程序的执行跳到 <sumUp+23>。接着依次执行以下指令:
Suppose that the branch is taken (i.e.,
i <= nis true). Then the instruction pointer is set to 0x40053d and program execution jumps to<sumUp+23>. The following instructions then execute in sequence:
<sumUp+23>处的mov指令把i复制到寄存器%eax。
- The
movinstruction at<sumUp+23>copiesito register%eax.
add %eax,-0x8(%rbp)把i加到total上(即total += i)。
- The
add %eax,-0x8(%rbp)addsitototal(i.e.,total += i).
- 接着,
<sumUp+29>处的add指令把i加 1(即i += 1)。
- The
addinstruction at<sumUp+29>then adds 1 toi(i.e.,i += 1).
<sumUp+33>处的mov指令把更新后的i值复制到寄存器%eax。
- The
movinstruction at<sumUp+33>copies the updated value ofito register%eax.
- 然后
cmp指令比较i和n,并设置相应的条件码寄存器。
- The
cmpinstruction then comparesitonand sets the appropriate condition code registers.
- 接着执行
jle。如果i小于或等于n,程序的执行再次跳到<sumUp+23>,循环(定义在<sumUp+23>和<sumUp+39>之间)重复执行。
- Next,
jleexecutes. Ifiis less than or equal ton, program execution once again jumps to<sumUp+23>and the loop (defined between<sumUp+23>and<sumUp+39>) repeats.
如果没有走分支(即 i 不小于或等于 n),则执行以下指令:
If the branch is not taken (i.e.,
iis not less than or equal ton), the following instructions execute:
1 | 0x40054f <+41>: mov -0x8(%rbp),%eax # copy total to %eax |
这些指令把 total 复制到寄存器 %eax,把 %rbp 恢复为原来的值,然后退出函数。因此,函数在退出时返回 total。
These instructions copy
totalto register%eax, restore%rbpto its original value, and exit the function. Thus, the function returnstotalupon exit.
表 1 展示了 sumUp 函数的汇编形式和 C 的 goto 形式:
Table 1 shows the assembly and C goto forms of the
sumUpfunction:
表 1. 把 sumUp 翻译成 C 的 goto 形式
Table 1. Translating sumUp into goto C form.
汇编
Assembly
1 | <sumUp>: |
翻译出的 goto 形式
Translated goto Form
1 | int sumUp(int n) { |
上面的代码也等价于下面这段不含 goto 语句的 C 代码:
The preceding code is also equivalent to the following C code without
gotostatements:
1 | int sumUp(int n) { |
汇编中的 for 循环
for Loops in Assembly
sumUp 函数中的主循环也可以写成 for 循环:
The primary loop in the
sumUpfunction can also be written as aforloop:
1 | int sumUp2(int n) { |
这个版本生成的汇编代码与我们的 while 循环示例完全相同。下面再列出这段汇编代码,并为每一行加上英文注解:
This version yields assembly code identical to our
whileloop example. We repeat the assembly code below and annotate each line with its English translation:
1 | Dump of assembler code for function sumUp2: |
要理解为什么这段代码的 for 循环版本与 while 循环版本生成的汇编完全相同,回想一下,for 循环的表示形式是:
To understand why the
forloop version of this code results in identical assembly to thewhileloop version of the code, recall that theforloop has the following representation:
1 | for ( <initialization>; <boolean expression>; <step> ){ |
它等价于下面的 while 循环表示形式:
and is equivalent to the following
whileloop representation:
1 | <initialization> |
由于每个 for 循环都可以用 while 循环表示,下面两个 C 程序都是前面那段汇编的等价表示:
Since every
forloop can be represented by awhileloop, the following two C programs are equivalent representations for the previous assembly:
表 2. 编写 sumUp 函数的两种等价方式
Table 2. Equivalent ways to write the sumUp function.
for 循环
For loop
1 | int sumUp2(int n) { |
while 循环
While loop
1 | int sumUp(int n){ |