目录
正在加载目录…
正在阅读专栏 SICP:Structure and Interpretation of Computer Programs 第 78 篇 · 共 80 篇 · 98%

SICP:5.5.5 An Example of Compiled Code

发布于 2026-09-18 13:32 · 最后编辑于 2026-09-18 15:32 · 版本 v2 · 字数 6,522 · 预计阅读 14 分钟 👁 19 次阅读

SICP:5.5.5 An Example of Compiled Code

本文逐段翻译 SICP 第二版 §5.5.5《An Example of Compiled Code》,完整跟踪 recursive factorial definition 的 compilation,保留 Figure 5.17/5.18 的 generated code、Exercises 5.33–5.38,以及脚注 43–44。

TL;DR

  • 通过 compile recursive factorial,可以把 §5.5 前面定义的所有 compiler elements 串起来。
  • Definition value 是 lambda;compiler 生成 procedure object、entry point、environment extension 与 procedure body。
  • Predicate (= n 1) 展示了 operator lookup、argument construction、primitive/compiled dispatch 和 after-call linkage。
  • Recursive false branch 需要保存 partial argl、operator procedures 与 continue;最终对 factorial 的调用使用 tail-recursive direct transfer。
  • Generated code 直接揭示 compiler 如何利用 register metadata 消除不必要的 saves/restores。

目录

章节说明
5.5.5 An Example of Compiled Coderecursive factorial compilation
Compiling the definitiondefinition 与 lambda object
Compiling the predicate and branchesif 与 procedure calls
Figure 5.17 generated codefactorial machine code
Figure 5.18 and exercisesgenerated-code reading exercises
脚注原文脚注 43–44

5.5.5 An Example of Compiled Code

现在已经看过 compiler 的所有 elements,可以检查一个 compiled-code example,看看这些 elements 如何组合起来。

我们通过调用 compile,编译 recursive factorial procedure 的 definition:

scheme
(compile
 '(define (factorial n)
    (if (= n 1)
        1
        (* (factorial (- n 1)) n)))
 'val
 'next)

这里指定 define expression 的 value 应放入 val register。我们不关心 compiled code 执行 define 后做什么,因此选择 next 作为 linkage descriptor 是 arbitrary 的。

Compiling the definition

compile 确定 expression 是一个 definition,于是调用 compile-definition:

  1. 编译计算待 assign value 的 code,target 为 val;
  2. 编译安装 definition 的 code;
  3. 编译把 define 的 value(symbol ok)放入 target register 的 code;
  4. 最后附加 linkage code。

计算 value 时要 preserve env,因为安装 definition 时需要 environment。由于 linkage 是 next,这里没有 linkage code。

Compiled code 的 skeleton 是:

scheme
<save env if modified by code to compute value>
<compilation of definition value, target val, linkage next>
<restore env if saved above>
(perform (op define-variable!)
         (const factorial)
         (reg val)
         (reg env))
(assign val (const ok))

待编译、用于产生 variable factorial value 的 expression 是一个 lambda expression;它的 value 是计算 factorial 的 procedure。

compile 调用 compile-lambda,后者:

  • compile procedure body;
  • 为 body 标记一个新的 entry point;
  • 生成 instruction,把 entry point 处的 procedure body 与 runtime environment 组合,并把 resulting procedure assign 给 val;
  • 跳过插入在当前位置的 compiled procedure code。

Procedure code 自身从 extend procedure definition environment 开始,构造一个把 formal parameter n bind 到 procedure argument 的 frame,然后是实际 procedure body。

这段用于产生 variable value 的 code 不修改 env register,所以前面 skeleton 中可能的 save/restore 并不会生成。(此时 entry2 处的 procedure code 还没有执行,因此它对 env 的使用无关。)

因此,compiled code skeleton 变为:

scheme
(assign val (op make-compiled-procedure)
             (label entry2)
             (reg env))
(goto (label after-lambda1))
entry2
 (assign env (op compiled-procedure-env) (reg proc))
 (assign env (op extend-environment)
             (const (n))
             (reg argl)
             (reg env))
 <compilation of procedure body>
after-lambda1
 (perform (op define-variable!)
          (const factorial)
          (reg val)
          (reg env))
 (assign val (const ok))

Compiling the predicate and branches

Procedure body 总是由 compile-lambda-body 编译为 target val、linkage return 的 sequence。

这里的 sequence 只有一个 if expression:

scheme
(if (= n 1)
    1
    (* (factorial (- n 1)) n))

compile-if 首先计算 predicate(target val),然后检查 result;如果 predicate false,就 branch around true branch。

Predicate code 周围 preserve env 和 continue,因为它们可能被 if expression 的 rest 使用。由于 if 是 procedure body sequence 的 final(且唯一)expression,target 是 val,linkage 是 return;因此 true/false branches 都以 target val、linkage return 编译。

也就是说,conditional 的 value(两个 branches 中任一个计算出的 value)就是 procedure 的 value。

scheme
<save continue, env if modified by predicate
 needed by branches>
<compilation of predicate, target val, linkage next>
<restore continue, env if saved above>
(test (op false?) (reg val))
(branch (label false-branch4))
true-branch5
 <compilation of true branch, target val, linkage return>
false-branch4
 <compilation of false branch, target val, linkage return>
after-if3

Predicate (= n 1) 是一个 procedure call:

  • lookup operator(symbol =),把 value 放到 proc;
  • 把 1 与 n 的 value assemble 到 argl;
  • 测试 proc 中是 primitive 还是 compound procedure;
  • dispatch 到 primitive branch 或 compound branch;
  • 两个 branches 都在 after-call label 处继续。

这个 case 中,operator 与 operands 的 evaluation 并不修改相关 registers,因此 preserve requirements 不会导致任何 register saves。

scheme
(assign proc
        (op lookup-variable-value) (const =) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch17))
compiled-branch16
 (assign continue (label after-call15))
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch17
 (assign val (op apply-primitive-procedure)
             (reg proc)
             (reg argl))
after-call15

Constant 1 的 true branch,以 target val、linkage return 编译为:

scheme
(assign val (const 1))
(goto (reg continue))

False branch 是另一个 procedure call:procedure 是 symbol * 的 value,arguments 是 n 与另一个 procedure call(对 factorial 的 call)的 result。

这些 calls 各自 setup proc 和 argl,并拥有自己的 primitive/compound branches。Figure 5.17 展示 factorial definition 的完整 compilation。

注意,前面 predicate 周围可能的 save/restore continue 和 env 实际上会生成,因为 predicate 中的 procedure call 会修改这些 registers,而 branches 中的 procedure call 与 return linkage 又需要它们。

Figure 5.17 generated code

下面保留原文 Figure 5.17 的 generated code(原文分两页):

scheme
;; construct the procedure and skip over code for the procedure body
 (assign val
         (op make-compiled-procedure) (label entry2) (reg env))
 (goto (label after-lambda1))

entry2                         ;; calls to factorial will enter here
 (assign env (op compiled-procedure-env) (reg proc))
 (assign env
         (op extend-environment) (const (n)) (reg argl) (reg env))
;; begin actual procedure body
 (save continue)
 (save env)

;; compute (= n 1)
 (assign proc (op lookup-variable-value) (const =) (reg env))
 (assign val (const 1))
 (assign argl (op list) (reg val))
 (assign val (op lookup-variable-value) (const n) (reg env))
 (assign argl (op cons) (reg val) (reg argl))
 (test (op primitive-procedure?) (reg proc))
 (branch (label primitive-branch17))
compiled-branch16
 (assign continue (label after-call15))
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch17
 (assign val (op apply-primitive-procedure) (reg proc) (reg argl))

after-call15                    ;; val now contains result of (= n 1)
 (restore env)
 (restore continue)
 (test (op false?) (reg val))
 (branch (label false-branch4))
true-branch5                    ;; return 1
 (assign val (const 1))
 (goto (reg continue))

false-branch4
;; compute and return (* (factorial (- n 1)) n)
 (assign proc (op lookup-variable-value) (const *) (reg env))
 (save continue)
 (save proc)                     ;; save * procedure
 (assign val (op lookup-variable-value) (const n) (reg env))
 (assign argl (op list) (reg val))
 (save argl)                     ;; save partial argument list for *

;; compute (factorial (- n 1)), the other argument for *
 (assign proc
         (op lookup-variable-value) (const factorial) (reg env))
 (save proc)                     ;; save factorial procedure

第二页:

scheme
;; compute (- n 1), the argument for factorial
 (assign proc (op lookup-variable-value) (const -) (reg env))
 (assign val (const 1))
 (assign argl (op list) (reg val))
 (assign val (op lookup-variable-value) (const n) (reg env))
 (assign argl (op cons) (reg val) (reg argl))
 (test (op primitive-procedure?) (reg proc))
 (branch (label primitive-branch8))
compiled-branch7
 (assign continue (label after-call6))
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch8
 (assign val (op apply-primitive-procedure) (reg proc) (reg argl))

after-call6                      ;; val now contains result of (- n 1)
 (assign argl (op list) (reg val))
 (restore proc)                  ;; restore factorial
;; apply factorial
 (test (op primitive-procedure?) (reg proc))
 (branch (label primitive-branch11))
compiled-branch10
 (assign continue (label after-call9))
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch11
 (assign val (op apply-primitive-procedure) (reg proc) (reg argl))

after-call9                      ;; val now contains result of
                                 ;; (factorial (- n 1))
 (restore argl)                  ;; restore partial argument list for *
 (assign argl (op cons) (reg val) (reg argl))
 (restore proc)                  ;; restore *
 (restore continue)
;; apply * and return its value
 (test (op primitive-procedure?) (reg proc))
 (branch (label primitive-branch14))
compiled-branch13
;; compound procedure here is called tail-recursively
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch14
 (assign val (op apply-primitive-procedure) (reg proc) (reg argl))
 (goto (reg continue))
after-call12
after-if3
after-lambda1
;; assign the procedure to variable factorial
 (perform
  (op define-variable!) (const factorial) (reg val) (reg env))
 (assign val (const ok))

这里最后对 compound procedure 的调用是 tail-recursive 的:它直接进入 procedure entry point,没有保存额外 continuation state。

Figure 5.18 and exercises

Exercise 5.33

考虑下面略有不同的 factorial definition:

scheme
(define (factorial-alt n)
  (if (= n 1)
      1
      (* n (factorial-alt (- n 1)))))

Compile 这个 procedure,并把 resulting code 与 factorial 产生的 code 比较。解释所有差异。两个 programs 中是否有一个执行得更 efficient?

Exercise 5.34

Compile iterative factorial procedure:

scheme
(define (factorial n)
  (define (iter product counter)
    (if (> counter n)
        product
        (iter (* counter product)
              (+ counter 1))))
  (iter 1 1))

Annotate resulting code,指出 iterative 与 recursive versions 的 essential difference:为什么一个 process 会 build up stack space,而另一个只使用 constant stack space。

Exercise 5.35

Figure 5.18 中的 code 是由什么 expression 编译产生的?

原文的 Figure 5.18 code:

scheme
(assign val (op make-compiled-procedure) (label entry16)
             (reg env))
(goto (label after-lambda15))
entry16
 (assign env (op compiled-procedure-env) (reg proc))
 (assign env
         (op extend-environment) (const (x)) (reg argl) (reg env))
 (assign proc (op lookup-variable-value) (const +) (reg env))
 (save continue)
 (save proc)
 (save env)
 (assign proc (op lookup-variable-value) (const g) (reg env))
 (save proc)
 (assign proc (op lookup-variable-value) (const +) (reg env))
 (assign val (const 2))
 (assign argl (op list) (reg val))
 (assign val (op lookup-variable-value) (const x) (reg env))
 (assign argl (op cons) (reg val) (reg argl))
 (test (op primitive-procedure?) (reg proc))
 (branch (label primitive-branch19))
compiled-branch18
 (assign continue (label after-call17))
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch19
 (assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call17
 (assign argl (op list) (reg val))
 (restore proc)
 (test (op primitive-procedure?) (reg proc))
 (branch (label primitive-branch22))
compiled-branch21
 (assign continue (label after-call20))
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch22
 (assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call20
 (assign argl (op list) (reg val))
 (restore env)
 (assign val (op lookup-variable-value) (const x) (reg env))
 (assign argl (op cons) (reg val) (reg argl))
 (restore proc)
 (restore continue)
 (test (op primitive-procedure?) (reg proc))
 (branch (label primitive-branch25))
compiled-branch24
 (assign val (op compiled-procedure-entry) (reg proc))
 (goto (reg val))
primitive-branch25
 (assign val (op apply-primitive-procedure) (reg proc) (reg argl))
 (goto (reg continue))
after-call23
after-lambda15
 (perform (op define-variable!) (const f) (reg val) (reg env))
 (assign val (const ok))

Exercise 5.36

我们的 compiler 为 combination operands 产生什么 evaluation order?是 left-to-right、right-to-left,还是其他顺序?

这个 order 在 compiler 的什么位置确定?修改 compiler,使它产生另一种 evaluation order。(参见 §5.4.1 explicit-control evaluator 对 operand evaluation order 的讨论。)改变 operand evaluation order 会怎样影响构造 argument list 的 code efficiency?

Exercise 5.37

理解 compiler preserving mechanism 如何优化 stack usage 的一种方法,是观察不使用这一 idea 时会生成哪些 extra operations。

修改 preserving,使它总是生成 save 和 restore operations。Compile 一些 simple expressions,找出 generated 的 unnecessary stack operations,并与保留 preserving mechanism 时生成的 code 比较。

Exercise 5.38

Compiler 很擅长避免 unnecessary stack operations,但在把 language primitive procedures 编译为 machine primitive operations 时并不 clever。

例如,考虑编译 (+ a 1) 需要多少 code:code setup argl,把 primitive addition procedure(通过在 environment 中 lookup symbol + 得到)放入 proc,然后测试 procedure 是 primitive 还是 compound。

Compiler 总是生成 test code,以及 primitive 和 compound branches 的 code(实际只执行其中一个)。我们没有展示实现 primitives 的 controller 部分,但假设这些 instructions 使用 machine data paths 中的 primitive arithmetic operations。

如果 compiler 能够 open-code primitives,也就是直接使用 primitive machine operations,会少很多 code。例如 (+ a 1) 可能编译为:^43

scheme
(assign val (op lookup-variable-value) (const a) (reg env))
(assign val (op +) (reg val) (const 1))

本练习要求扩展 compiler,使其支持 selected primitives 的 open coding。对这些 primitive procedures 的 calls 生成 special-purpose code,而不是 general procedure-application code。

为支持这一点,需要为 machine 增加 special argument registers arg1 与 arg2。Machine 的 primitive arithmetic operations 从 arg1 和 arg2 获取 inputs,results 可以放入 val、arg1 或 arg2。

Compiler 必须能够识别 source program 中对 open-coded primitive 的 application。需要扩展 compile dispatch,使它除了当前识别的 reserved words(special forms)外,也识别这些 primitives 的 names。^44

a. 与 special forms 不同,open-coded primitives 都需要 evaluate operands。为所有 open-coding code generators 编写 spread-arguments code generator。它接受 operand list,并把给定 operands 编译到 successive argument registers。注意,operand 可能包含对 open-coded primitive 的 call,因此 operand evaluation 时必须 preserve argument registers。

b. 对 =、*、-、+ 四个 primitive procedures,编写 code generator:它接受带有该 operator 的 combination、target 与 linkage descriptor,生成把 arguments spread 到 registers、然后把 operation 的 result target 到给定 target 并使用给定 linkage 的 code。只需处理两个 operands 的 expressions。让 compile dispatch 到这些 code generators。

c. 用新 compiler 编译 factorial example,并将 resulting code 与不使用 open coding 时产生的 code 比较。

d. 扩展 + 和 * 的 code generators,使其支持任意数量 operands。超过两个 operands 的 expression 必须被编译成一串每次只接受两个 inputs 的 operations。

脚注

脚注 43

这里使用同一个 symbol + 表示 source-language procedure 和 machine operation。一般来说,source language 的 primitives 与 machine 的 primitives 之间不会有 one-to-one correspondence。

脚注 44

把 primitives 变成 reserved words 通常是 bad idea,因为 user 不能再把这些 names rebind 到不同 procedures。

此外,如果向一个正在使用中的 compiler 添加 reserved words,那么已有的、用这些 names 定义 procedures 的 programs 会停止工作。参见 Exercise 5.44,那里有避免这一问题的 ideas。

小结

Recursive factorial 的 compiled output 展示了 compiler 的完整工作链:definition 生成 lambda object,lambda body 生成 entry point 与 environment extension,conditional 生成 branches,procedure applications 构造 arguments 并 dispatch,最后通过 continue 实现普通 return 或 tail-recursive direct transfer。

参考

  • Abelson, Sussman, and Sussman, Structure and Interpretation of Computer Programs, 2nd ed., §5.5.5 “An Example of Compiled Code”.
  • MIT Press HTML full text
← 返回列表
← 上一篇 SICP:5.5.4 Combining Instruction Sequences 下一篇 → SICP:5.5.6 Lexical Addressing

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论