说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C9-ARM64/loops.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
9.4.3. Loops in Assembly
与 if 语句一样,汇编中的循环也是用分支指令实现的。不过,循环能让指令根据所求条件的结果被重复执行。
Like
ifstatements, loops in assembly are also implemented using branch instructions. However, loops enable instructions to be revisited based on the result of an evaluated condition.
下面例子中的 sumUp 函数把从 1 到用户指定的整数 n 之间的所有正整数加起来。这段代码是有意写得不够优化的,以便演示 C 中的 while 循环。
The
sumUpfunction in the following example sums up all the positive integers from 1 to a user-defined integer n. 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 store some temporary values:
1 | 0x0724 <+0>: sub sp, sp, #0x20 //grow stack by 32 bytes (new stack frame) |
具体来说,它们:
Specifically, they:
- 让调用栈增长 32 字节,标出新的栈帧。
- Grow the call stack by 32 bytes, marking the new frame.
- 把第一个参数(
n)存到栈位置sp + 12处。
- Store the first parameter (
n) at stack locationsp + 12.
- 把值 0 存到栈位置
sp + 24处,表示total。
- Store the value 0 at stack location
sp + 24, indicatingtotal.
- 把值 1 复制到寄存器
w0中。
- Copy the value 1 into register
w0.
- 把值 1 存到栈位置
sp + 28处,表示i。
- Store the value 1 at stack location
sp + 28, indicatingi.
回想一下,栈上的位置存放的是函数中的临时变量。为简单起见,我们把 sp + 24 标记的位置称为 total,把 sp + 28 称为 i。sumUp 的输入参数(n)位于栈地址 sp + 12 处。尽管临时变量被放在栈上,但要记住,在第一条指令(sub sp, sp, #0x20)执行之后,栈指针就没有再改变过。
Recall that stack locations store temporary variables in a function. For simplicity we will refer to the location marked by
sp + 24astotalandsp + 28asi. The input parameter tosumUp(n) is located at stack addresssp + 12. 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 (sub sp, sp, #0x20).
循环的核心
The Heart of the Loop
sumUp 函数中接下来的 12 条指令是这个循环的核心:
The next 12 instructions in the
sumUpfunction represent the heart of the loop:
1 | 0x0738 <+20>: b 0x758 <sumUp+52> // goto <sumUp+52> |
- 第一条指令是直接跳转到
<sumUp+52>,它把程序计数器寄存器(pc)设为地址 0x758。
- The first instruction is a direct jump to
<sumUp+52>, which sets the program counter register (pc) to address 0x758.
- 接下来执行的两条指令(位于
<sumUp+52>和<sumUp+56>)把i和n分别加载到寄存器w1和w0中。
- The next two instructions that execute (at
<sumUp+52>and<sumUp+56>) loadiandninto registersw1andw0, respectively.
<sumUp+60>处的cmp指令比较i和n,设置相应的条件标志。程序计数器pc前进到下一条指令,即地址 0x764。
- The
cmpinstruction at<sumUp+60>comparesiandn, setting the appropriate condition flags. The program counterpcadvances to the next instruction, or address 0x764.
- 如果
i小于或等于n,<sumUp+64>处的b.le指令就把pc寄存器替换为地址 0x73c。
- The
b.leinstruction at<sumUp+64>replaces thepcregister with address 0x73c ifiis less than or equal ton.
如果走了分支(也就是说,如果 i <= n),程序的执行跳转到 <sumUp+24>,并执行下面的指令:
If the branch is taken (that is, if
i <= n), program execution jumps to<sumUp+24>and the following instructions execute:
<sumUp+24>和<sumUp+28>处的ldr指令把total和i分别加载到寄存器w1和w0中。
- The
ldrinstructions at<sumUp+24>and<sumUp+28>loadtotalandiinto registersw1andw0, respectively.
- 然后,
<sumUp+32>处的add指令把total加到i上(即i + total),并把结果存入w0。
- The
addinstruction at<sumUp+32>then addstotaltoi(i.e.,i + total) and stores the result inw0.
- 然后,
<sumUp+36>处的str指令用寄存器w0中的值更新total(即total = total + i)。
- The
strinstruction at<sumUp+36>then updatestotalwith the value in registerw0(i.e.,total = total + i)
<sumUp+40>处的ldr指令把i加载到寄存器w0中。
- The
ldrinstruction at<sumUp+40>loadsiinto registerw0.
<sumUp+44>处的add指令把i加 1,并把结果存入寄存器w0。
- The
addinstruction at<sumUp+44>adds 1 toiand stores the result in registerw0.
<sumUp+48>处的str指令用寄存器w0中存放的值更新i(即i = i + 1)。
- The
strinstruction at<sumUp+48>updatesiwith the value stored in registerw0(i.e.,i = i + 1)
<sumUp+52>和<sumUp+56>处的ldr指令把i和n分别加载到寄存器w1和w0中。
- The
ldrinstructions at<sumUp+52>and<sumUp+56>loadiandninto registersw1andw0, respectively.
<sumUp+60>处的cmp指令比较i和n,并设置相应的条件码标志。
- The
cmpinstruction at<sumUp+60>comparesitonand sets the appropriate condition code flags.
- 接着执行
b.le指令。如果i小于或等于n,程序的执行跳回<sumUp+24>,pc被设为 0x73c,<sumUp+24>到<sumUp+64>之间的指令再次执行。否则,寄存器pc被设为顺序中下一条指令的地址,即 0x768(<sumUp+68>)。
- The
b.leinstruction then executes. Ifiis less than or equal ton, program execution jumps back to<sumUp+24>,pcis set to 0x73c, and the instructions between<sumUp+24>and<sumUp+64>repeat execution. Otherwise, registerpcis set to the address of the next instruction in sequence, or 0x768 (<sumUp+68>).
如果没有走分支(即 i 大于 n),就执行下面的指令:
If the branch is not taken (i.e.,
iis greater thann), the following instructions execute:
1 | 0x0768 <+68>: ldr w0, [sp, #24] // w0 = total |
这些指令把 total 复制到返回寄存器 w0,通过收缩 sp 恢复调用栈,然后退出函数。因此,函数退出时返回 total。
These instructions copy
totalto the return registerw0, restore the call stack by shrinkingsp, and exit the function. Thus, the function returnstotalupon exit.
表 1 并排展示了 sumUp 函数的汇编形式和 C 的 goto 形式:
Table 1 shows the assembly and C
gotoforms of thesumUpfunction side by side:
表 1. 把 sumUp() 翻译成 goto 形式的 C 代码
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 yields identical assembly code 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 循环表示:
This 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){ |