Essentials of Compilation:函数
Essentials of Compilation:函数
本章在 tuple / loop compiler 之上加入 top-level function definition 与 function application,并处理 function pointer、calling convention、tail call 和 function reference。
TL;DR
LangFun只允许 top-level function definition,是从简单 compiler 走向 lexically scoped function 的过渡阶段。- Function 是 first-class value;function pointer 可以存入 memory,也可以作为 argument 传递。
reveal_functions把含混的 function name reference 改写成带 arity 的FunRef,使后续 code generation 能用leaq取得 function address。- Tail call 不应使用
callq,而应恢复 caller frame 后使用 indirectjmp,从而把递归调用的 stack space 降到常数级。 - Function compiler 必须同时处理 parameter registers、callee-saved registers、root stack 和 frame layout。
名词解释
| 名词 | 含义 | 本章对应物 |
|---|---|---|
| top-level function | 不嵌套在其他 function 内的 function | map、inc |
| function pointer | 作为 data 的 function address | FunRef |
| arity | function 接受的 argument 数量 | Callq 中的 integer |
| tail call | function body 最后 action 的 function call | tail_sum 的递归调用 |
| indirect call | 通过 register 中的 address 调用 function | callq *%rax |
目录
| 章节 | 说明 |
|---|---|
| Functions | top-level function 与 function application |
The LangFun Language | function type、first-class function 和 AST |
| Interpreter | function environment 与 application |
| Type checker | 检查 parameter / argument type |
| Functions in x86 | indirect call 与 frame |
| Calling Conventions | parameter registers、root stack 与 saved registers |
| Efficient Tail Calls | 常数 stack space 的递归调用 |
| Shrink 与 Reveal Functions | 后续 compiler pass |
Functions
本章研究只允许 top-level function definition 的 Typed Racket subset。这类 function 出现在 C language 中,也是实现 lexically scoped function(lambda abstraction)的重要 stepping stone。
The LangFun Language
LangFun program 以零个或多个 function definition 开始。Definition 中的 function name 对整个 program 都处于 scope 内,包括其他 function definition,因此 definition 的书写顺序不重要。
Function application 的 concrete syntax 是一个 function expression 后跟零个或多个 argument expression:
(fun-exp arg-exp ...)
它的第一个 expression 必须求值为 function,剩余 expression 是 arguments。Abstract syntax 使用 Apply(fun, args)。
Function 是 first-class:function pointer 是 data,可以存储在 memory 中,也可以作为 parameter 传给另一个 function。因此 function 有自己的 type:
(Type₁ ... Typeₙ -> Typeᵣ)
它表示一个有 n 个 parameter、parameter types 为 Type₁ 到 Typeₙ、return type 为 Typeᵣ 的 function。
本章 function 相对 Racket function 的主要限制是:它们不是 lexically scoped。Function body 中能引用的 external entity 只有其他 globally defined function;LangFun syntax 不允许 function definition 嵌套在另一个 definition 内。
示例:map 与 inc
(define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
: (Vector Integer Integer)
(vector (f (vector-ref v 0)) (f (vector-ref v 1))))
(define (inc [x : Integer]) : Integer
(+ x 1))
(vector-ref (map inc (vector 0 41)) 1)
map 对 tuple 的两个 element 应用 function f,返回包含两个结果的新 tuple。Program 把 inc 和 (vector 0 41) 传给 map,最终结果为 42。
Interpreter
LangFun 的 definitional interpreter 需要为 top-level function definitions 建立 mutual recursion。经典的做法是 back-patching:第一遍为每个 function 建立带 mutable cons cell 的 top-level environment,此时 function value 还没有完整 environment;environment 建好后,再遍历它们,把每个 function value 更新为使用完整 top-level environment 的 lambda value。
解释 function application 时,先求值 function expression 得到 function value,再求值 arguments,把 parameters 映射到 argument values,最后在扩展后的 function environment 中解释 body。
(define interp-Lfun-class
(class interp-Lvec-class
(super-new)
(define/override ((interp-exp env) e)
(define recur (interp-exp env))
(match e
[(Apply fun args)
(define fun-val (recur fun))
(define arg-vals (for/list ([e args]) (recur e)))
(match fun-val
[`(function (,xs ...) ,body ,fun-env)
(define params-args (for/list ([x xs] [arg arg-vals])
(cons x (box arg))))
(define new-env (append params-args fun-env))
((interp-exp new-env) body)]
[else (error 'interp-exp "expected function, not ~a" fun-val)])]
[else ((super interp-exp env) e)]))
(define/public (interp-def d)
(match d
[(Def f (list `[,xs : ,ps] ...) rt _ body)
(cons f (box `(function ,xs ,body ())))]))
(define/override (interp-program p)
(match p
[(ProgramDefsExp info ds body)
(let ([top-level (for/list ([d ds]) (interp-def d))])
(for/list ([f (in-dict-values top-level)])
(set-box! f (match (unbox f)
[`(function ,xs ,body ())]
[`(function ,xs ,body ,top-level)])))
((interp-exp top-level) body))]))))
Type checker
和 interpreter 类似,ProgramDefsExp 的 type checker 先建立从每个 function name 到 function type 的 mapping,再用这张 mapping type check 整个 program。
Function application 的规则是:把 function expression 的 type 匹配为 function type,检查每个 argument expression 的 type 是否等于对应 parameter type,application 的 type 则是 function type 中的 return type。
对 function definition,先把 parameters 和它们的 types 加入 environment,type check body,并确保 body type 与声明的 return type 相同。顶层 program 的最终 expression 必须是 Integer。
Racket 版 type checker 的核心实现如下。注意它先把所有 top-level definition 加入 env,再检查每个 definition;这样 function definitions 可以互相递归引用,而且不依赖书写顺序:
(define type-check-Lfun-class
(class type-check-Lvec-class
(super-new)
(inherit check-type-equal?)
(define/public (type-check-apply env e es)
(define-values (e^ ty) ((type-check-exp env) e))
(define-values (e* ty*)
(for/lists (e* ty*) ([e (in-list es)])
((type-check-exp env) e)))
(match ty
[`(,ty^* ... -> ,rt)
(for ([arg-ty ty*] [param-ty ty^*])
(check-type-equal? arg-ty param-ty (Apply e es)))
(values e^ e* rt)]))
(define/override (type-check-exp env)
(lambda (e)
(match e
[(FunRef f n)
(values (FunRef f n) (dict-ref env f))]
[(Apply e es)
(define-values (e^ es^ rt) (type-check-apply env e es))
(values (Apply e^ es^) rt)]
[else ((super type-check-exp env) e)])))
(define/public (type-check-def env)
(lambda (d)
(match d
[(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
(define new-env (append (map cons xs ps) env))
(define-values (body^ ty^)
((type-check-exp new-env) body))
(check-type-equal? ty^ rt body)
(Def f p:t* rt info body^)])))
(define/public (fun-def-type d)
(match d
[(Def f (list `[,xs : ,ps] ...) rt info body)
`(,@ps -> ,rt)]))
(define/override (type-check-program p)
(match p
[(ProgramDefsExp info ds body)
(define env
(for/list ([d ds])
(cons (Def-name d) (fun-def-type d))))
(define ds^
(for/list ([d ds]) ((type-check-def env) d)))
(define-values (body^ ty) ((type-check-exp env) body))
(check-type-equal? ty 'Integer body)
(ProgramDefsExp info ds^ body^)]))))
对每个 Def,还需用 append (map cons xs ps) env 扩展 environment 检查 body,并验证 body type 等于声明的 return type;这一步不能只检查调用点,否则错误会被推迟到 function 被调用时才暴露。
Functions in x86
x86 提供了一些支持 function 实现的 feature。此前已经看到可以用 label 指向 instruction location;label 也可以标记 function instruction 的起点。使用 leaq 可以取得 label address,例如把 inc 的 address 放入 %rbx:
leaq inc(%rip), %rbx
此前使用 callq 跳转到 label 指定的 function,例如 read_int。本章还要支持目标 address 存储在 register 中的 indirect function call:
callq *%rbx
Calling Conventions
callq 只提供 function 的部分支持:它把 return address push 到 stack 并跳到 target,但不负责 parameter passing、frame push / pop,或决定不同 function 如何共享 registers。
Unix-based system 的 x86-64 calling convention 使用以下 6 个 register 传递 arguments:
rdi rsi rdx rcx r8 r9
超过 6 个的 arguments 会放在 caller frame 的空间中;本章为了支持 efficient tail call,安排成不需要超过 6 个 arguments。Function return value 放在 rax。
Caller 把 rsp 设置为自己 frame 的最后一个 data item;callee 不能改变 caller frame 中位于或高于 rsp 的内容,但可以使用低于 rsp 的 locations。Tuple type 的 variable 放在 root stack,因此 function prelude 要根据 tuple variable 数量移动 root stack pointer r15,conclusion 再移回去,并把本 frame 的 root stack slots 初始化为 0,以免 GC 把未初始化 bits 当作 address。
如果 callee 使用 callee-saved register,必须把它们保存到自己的 stack frame,并在 return 前恢复。因此若 register allocator 把 variable 分配到 callee-saved register,所有 function 的 prelude / conclusion 都必须保存 / 恢复它。
调用约定还规定了 frame 之间的相对布局。设 caller 保存了 j 个 callee-saved register 和 k 个 local,callee 保存了 n 个 callee-saved register 和 m 个 local,则从各自 %rbp 观察时布局如下:
| Caller view | Callee view | 内容 |
|---|---|---|
8(%rbp) | return address | |
0(%rbp) | caller 的 old %rbp | |
-8(%rbp) 到 -8j(%rbp) | caller 保存的 callee-saved registers | |
-8(j+1)(%rbp) 到 -8(j+k)(%rbp) | caller 的 locals | |
8(%rbp) | return address | |
0(%rbp) | callee 的 old %rbp | |
-8(%rbp) 到 -8n(%rbp) | callee 保存的 callee-saved registers | |
-8(n+1)(%rbp) 到 -8(n+m)(%rbp) | callee 的 locals |
这里的关键不变量是:caller 把 %rsp 放在自己 frame 的最后一个 data item 上;callee 不能修改 %rsp 所在位置及其上方的 caller frame,只能使用低于 %rsp 的空间。%rbp 作为 frame 的固定 reference point,使每个 local 都能通过固定 offset 访问。
Caller-saved registers 的内容由 caller 自己负责保护:caller 必须假定 callee 会把它们任意覆盖。因此,跨 function call 仍然 live 的 variable 不应分配到 caller-saved register。反过来,callee 如果使用 callee-saved register,就必须在自己的 frame 中保存旧值,并在返回前恢复;register allocator 对每个 function 分配出的 callee-saved register 都要纳入该 function 的 prelude/conclusion。
Efficient Tail Calls
一般来说,program 使用的 stack space 由 nested function call 的最长链决定。递归 function 可能让深度 n 很大;但某些情况下可以让长链调用只使用 constant amount 的 space。
Tail call 是 function body 中最后一个 action 的 function call。例如下面 recursive call 是 tail call:
(define (tail_sum [n : Integer] [r : Integer]) : Integer
(if (eq? n 0)
r
(tail_sum (- n 1) (+ n r))))
(+ (tail_sum 3 0) 36)
Tail call 发生时,caller frame 已经不再需要,因此可以在 tail call 前 pop caller frame。只进行 tail call 的 recursive function 最终只使用 constant stack space。像 Racket 这样的 functional language 大量依赖 recursive function,因此 Racket 要求所有 tail call 都以这种方式优化。
Tail call 的 parameter passing 需要小心:如果 arguments 超过 6 个,普通 convention 使用 caller frame;但 tail call 会 pop caller frame,不能再使用它。使用 callee frame 也有问题,因为 caller / callee frame 在 memory 中重叠,复制 arguments 时可能覆盖后续 argument 的 source。后续会用 heap 传递超过 6 个的 arguments。
Tail call 前还要执行通常放在 function conclusion 中的 frame-pop instruction,包括恢复 callee-saved register。由于 argument-passing registers 都是 caller-saved,这样安排是安全的。
Tail call 不能用 callq,因为 callee 完成后不应返回当前 function,而应返回当前 function 的 caller;stack 上已有的 return address 正是正确的 address。使用普通 jmp,并在 register 前加 * 写成 indirect jump:
jmp *%rax
建议用 rax 保存 jump target,因为 conclusion 几乎可以覆盖其他所有 register。
Tail call 中的 frame overlap
Tail call 的参数搬运不能直接套用普通 call 的 stack convention。超过第六个参数时,普通调用会把参数放到 caller frame;但 tail call 必须先 pop caller frame,因此这些位置会立即失效。若改为写入 callee frame,又会遇到 caller 与 callee frame 在 memory 中重叠的问题:复制较早参数时,目标位置可能覆盖稍后参数的 source。
因此 limit_functions 会在前端把超过 6 个的 arguments 打包到 heap tuple,由第 6 个参数传递该 tuple。这样 tail call 只需要处理 registers,不会因为 frame overlap 改变参数值。
Tail call 的 lowering 分两个阶段完成。select_instructions 先生成带有 target 和 arity 的 TailJmp pseudo-instruction,因为此时还不知道 register allocation 后的 frame size;patch_instructions 保证 target 位于保留的 %rax 中;prelude_and_conclusion 在 allocation 完成后才把它展开为恢复 frame、恢复 callee-saved registers,最后执行 jmp *%rax。这里不能使用 callq,因为它会压入新的 return address,而 tail callee 应复用当前 caller 留在 stack 上的 return address。
Shrink 与 Reveal Functions
shrink pass 引入显式的 main function,把所有 top-level expression 包起来:
ProgramDefsExp(info, defs, exp)
⇒ ProgramDefs(info, defs + (Def 'main '() 'Integer '() exp))
LangFun syntax 把 function name 的使用和 local variable 混在一起,这对 compilation 不方便:function name 与 local variable 必须使用不同的 code generation。特别是,function name 需要通过 leaq 把 x86 label 转换为 register 中的 address。
因此 reveal_functions pass 把 function reference 从 Var(f) 改成 FunRef(f, n),其中 n 是 function arity。后续 select_instructions 可以专门为 FunRef 生成取 address 的 instruction。
Limit Functions
为了简化 calling convention 和 efficient tail calls,本书把 function 参数数量限制为 6。limit_functions 处理输入语言允许的任意参数数量:前 5 个参数照常传递,其余参数打包成 tuple,作为第 6 个参数。
(Def f ([x1:T1] ... [xn:Tn]) Tr info body)
↦ (Def f ([x1:T1] ... [x5:T5]
[tup : (Vector T6 ... Tn)])
Tr info body')
body' 中原本的 xi(i > 5)替换为 (vector-ref tup (i - 6))。调用则把 e6 ... en 组成 (vector e6 ... en),作为第六个实参:
(e0 e1 ... en) ↦ (e0 e1 ... e5 (vector e6 ... en))
因此,limit_functions 不是简单截断 parameter list:它必须同时改变 definition 与所有 call site,并在 function body 中把原本的超出范围 parameter 改写成 tuple access。若原 function 只有 6 个或更少 parameters,则不需要包装;若多于 6 个,前 5 个保持独立 register arguments,第 6 个位置承载剩余 arguments 的 tuple。
Remove Complex Operands
Apply 必须分类为 complex expression,因为它会生成一段 call instructions;它的 arguments 必须是 atomic expressions。FunRef 虽然语法上简单,但需要用 leaq 把 function label 转成 address,因此也必须分类为 complex expression。输出 LangFunANF 在 LangAllocANF 上增加 FunRef 与 Apply。
Explicate Control 与 LangCFun
explicate_control 为 FunRef、Apply 增加 assignment、predicate 与 tail context 的处理:assignment/predicate 中的 Apply 变成 Call,tail position 中的 Apply 变成 TailCall。应为 function definitions 增加单独的辅助函数,并对每个 definition 的 body 构造独立 basic blocks。
LangCFun 的关键 forms 是:
Exp ::= (fun-ref label arity) | (call atom atom ...)
Tail ::= (tail-call atom atom ...)
Def ::= function label、参数、返回类型与 basic blocks
tail call 的特殊性在于它不需要保存返回值,也不应在 callee 完成后返回当前 function;它最终会被翻译为 pop 当前 frame 后的 indirect jump。
Select Instructions 与间接调用
select_instructions 输出 LangXIndCall,新增 leaq、callq *arg 和 tailjmp arg。Function reference 的翻译是:
leaq f(%rip), lhs'
function definition 的参数从 syntax 中移除,改为在 start block 开头从 argument-passing registers 移入 local variables:前六个参数使用 %rdi、%rsi、%rdx、%rcx、%r8、%r9。
普通 indirect call 先把 arguments 移入这些 registers,再调用 function address,最后把 %rax 移到 lhs:
movq arg1, %rdi
movq arg2, %rsi
callq *arg0
movq %rax, lhs
IndirectCallq 的 arity 用于 liveness analysis:它决定哪些 argument registers 会被读取。tail call 的参数传递相同,但随后要 pop 当前 frame,因此使用暂存的 TailJmp instruction,等 register allocation 确定 frame size 后再降低。
Register Allocation
增加 functions 后,liveness、interference graph 与 register allocation 都需要调整:
IndirectCallq与Callq一样,会写 caller-saved registers;IndirectCallq与TailJmp的 arity 决定被读取的 argument registers;它们的 target 也属于 read locations;- 每个 function 单独计算 interference graph,而不是整个 program 共用一个 graph;
- allocation 由
allocate_registers对每个 function definition 分别执行; - 任何在 user-defined function call 期间 live 的 tuple-typed variable,都要像跨
collectcall 一样 spill,避免 GC 找不到 pointer。
Patch Instructions
leaq 的 destination 必须是 register,因此 patch_instructions 需要为不合法的 destination 插入 temporary move。TailJmp 的 target 必须位于保留的 %rax 中,因为 tail jump 前的 frame teardown 会破坏许多其他 registers。
Prelude、Conclusion 与 Tail Call
每个 function 都有自己的 prelude/conclusion。Prelude:
- push
%rbp,设置%rbp = %rsp; - 保存本 function 使用的 callee-saved registers;
- 下移
%rsp,为普通 spills 留出并按 16-byte alignment 对齐的空间; - 上移 root stack pointer
%r15,为 tuple spills 留空间; - 将新的 root slots 清零;
- 跳转到 function 的
startblock。
main 还要先调用 initialize,并从 rootstack_begin 初始化 %r15。
Conclusion:恢复普通 stack spills、pop callee-saved registers、下移 %r15 释放 root frame、恢复 %rbp,最后 retq。
TailJmp 的最终翻译与 conclusion 相同,但最后一条不是 retq,而是 jmp *%rax。这样 callee 返回时会沿用当前 function caller 留下的 return address,实现 constant-space tail call。
An Example Translation
一个简单的:
(define (add [x : Integer] [y : Integer]) : Integer
(+ x y))
(add 40 2)
会经过 FunRef、TailCall、argument register moves 和 leaq,最终由 main 把 40、2 放入 %rdi、%rsi,将 add 的地址放入 %rax,清理当前 frame 后执行 jmp *%rax。add 从 %rdi、%rsi 取得参数,将结果放入 %rax 并通过 conclusion 返回。
原文在 explicate_control 后得到两个 basic-block program:
(define (add86 [x87 : Integer] [y88 : Integer]) : Integer
add86start:
return (+ x87 y88))
(define (main) : Integer
mainstart:
tmp89 = (fun-ref add86 2)
(tail-call tmp89 40 2))
select_instructions 会把 function definition 的 parameters 变成从 argument-passing registers 取值,并把 FunRef 变成 leaq:
add86start:
movq %rdi, x87
movq %rsi, y88
movq x87, %rax
addq y88, %rax
jmp add86conclusion
mainstart:
leaq add86(%rip), %rcx
movq $40, %rdi
movq $2, %rsi
movq %rcx, %rax
popq %rbp
jmp *%rax
经过 patch_instructions 与 prelude_and_conclusion 后,Racket edition 的最终 assembly 可以写成:
.globl add86
.align 8
add86:
pushq %rbp
movq %rsp, %rbp
jmp add86start
add86start:
movq %rdi, %rax
addq %rsi, %rax
jmp add86conclusion
add86conclusion:
popq %rbp
retq
.globl main
.align 8
main:
pushq %rbp
movq %rsp, %rbp
movq $16384, %rdi
movq $16384, %rsi
callq initialize
movq rootstack_begin(%rip), %r15
jmp mainstart
mainstart:
leaq add86(%rip), %rcx
movq $40, %rdi
movq $2, %rsi
movq %rcx, %rax
popq %rbp
jmp *%rax
mainconclusion:
popq %rbp
retq
这里 main 的 tail call 直接复用最初 caller 留在 stack 上的 return address;main 清理自己的 frame 后跳到 add86,而 add86 的 retq 就会返回到最初 caller。add86 本身没有 local 或 callee-saved register,所以它的 conclusion 只需恢复 %rbp 并执行 retq。
在最终的 main prelude 中,Racket runtime 先用 initialize 创建 root stack 与 two-space heap,再从 rootstack_begin 初始化 %r15。mainstart 的 tail call 将 %rax 保留为 jump target,恢复当前 frame 后跳到 add86;add86 完成后通过自己的 conclusion 返回到最初 caller 留下的 return address。这个例子同时展示了为什么 tail call 的 target 必须在 frame teardown 之前放入不会被覆盖的 register。
本章练习要求增加 8 个测试:传递 function、返回 function、recursive function、创建 vector 的 function,以及执行 tail call 的 function,并与此前所有测试一起运行。
参考资料
评论 (0)