Kaleidoscope:LLVM IR 的性质与实践技巧
Kaleidoscope:总结与其他 LLVM 技巧
本章总结 Kaleidoscope 编译器的完整实现,并讨论 LLVM IR 的 target independence、safety、language-specific optimizations,以及 portable
offsetof/sizeof和 garbage-collected stack frames 等实践技巧。
TL;DR
- Kaleidoscope 已从无用 toy 发展为包含 lexer、parser、AST、code generator、JIT、debug information 和 object-code emission 的完整小型 compiler。
- LLVM IR 通常具备 target independence,但这不等于任何 source language 或其 libraries 都天然 portable。
- LLVM IR 本身不提供 safety guarantees;safe language 需要由 language design、runtime 和必要的 OS support 共同实现。
- LLVM 会有意丢弃部分 high-level information,但可以通过扩展 IR、language-specific passes 或 front-end AST 优化来补足。
- 对 LLVM type 的 size/offset 等 target-specific 信息,可以用
getelementptr以 portable 方式计算;显式 stack frames 则可配合 CPS 和 tail calls 实现。
目录
| 章节 | 说明 |
|---|---|
| 教程总结 | Kaleidoscope 已具备的能力与后续扩展方向 |
| LLVM IR 的性质 | target independence、safety 和 language-specific optimizations |
| 实用技巧 | portable offsetof/sizeof 与 garbage-collected stack frames |
教程总结
欢迎来到“使用 LLVM 实现一门语言”教程的最后一章。在这个教程中,我们把小型 Kaleidoscope language 从一个毫无用处的 toy,发展成一个半有趣(但可能仍然没什么用)的 toy :)。
回顾整个过程很有意思:我们只用了很少的 code,就构建了完整的 lexer、parser、AST、code generator、interactive run-loop(包含 JIT),并让 standalone executables 生成 debug information;所有这些加起来不到 1000 行 non-comment/non-blank code。
这门小型 language 已经支持一些有趣的 features:user-defined binary 和 unary operators、用于立即求值的 JIT compilation,以及带有 SSA construction 的几种 control-flow constructs。
本教程的部分目标,是展示定义、构建和玩弄一门 language 可以多么容易、多么有趣。构建 compiler 不必是令人害怕或神秘的过程!既然已经了解了一些基础知识,强烈建议你拿起这份 code 继续 hack。比如可以尝试加入:
- global variables:在现代 software engineering 中,global variables 的价值可能有争议;但在 Kaleidoscope compiler 这类快速 hack 中,它们经常很有用。幸运的是,当前 setup 很容易加入 global variables:只要在拒绝 unresolved variable 之前,让 value lookup 先检查 global variable symbol table。创建新 global variable 时,构造一个 LLVM
GlobalVariableclass 的 instance 即可。 - typed variables:Kaleidoscope 当前只支持
double类型的 variables。这带来了很简洁的体验,因为只支持一种 type,就永远不需要显式写 type。不同 languages 有不同处理方式;最简单的方式是要求用户在每个 variable definition 中指定 type,并将 variable 的 type 与其Value*一起记录在 symbol table 中。 - arrays、structs、vectors 等:加入 types 后,就可以用各种方式扩展 type system。Simple arrays 很容易实现,对许多 applications 也很有用。加入它们主要是学习 LLVM
getelementptrinstruction 的过程;这个 instruction 如此精巧且不寻常,甚至有自己的 FAQ。 - standard runtime:当前 language 允许用户访问任意 external functions,并用它们实现
printd和putchard。随着 language 加入更高层的 constructs,通常让这些 constructs lower 成 language-supplied runtime 的 calls 更合理。例如,若加入 hash tables,最好把相关 routines 放入 runtime,而不是全部 inline 到生成的 code 中。 - memory management:当前只能访问 Kaleidoscope 的 stack。能够分配 heap memory 也很有用,可以调用标准 libc 的
malloc/freeinterface,也可以使用 garbage collector。如果使用 garbage collection,注意 LLVM 完全支持 Accurate Garbage Collection,包括会移动 objects、需要 scan/update stack 的 algorithms。 - exception handling support:LLVM 支持生成能够与其他 languages 编译的 code 互操作的 zero-cost exceptions。也可以隐式地让每个 function 返回 error value 并检查它,或者显式使用
setjmp/longjmp。这里有许多不同路径。 - object orientation、generics、database access、complex numbers、geometric programming 等:事实上,能够加入 language 的疯狂 features 没有尽头。
- unusual domains:前面一直讨论 LLVM 在 compiler 中的应用,但还有很多通常不会被视为 compiler 问题的领域也能使用 compiler technology。例如,LLVM 曾被用于实现 OpenGL graphics acceleration、将 C++ code 翻译为 ActionScript,以及许多其他有趣而机巧的用途。也许你会成为第一个用 LLVM 将 regular-expression interpreter JIT compile 为 native code 的人?
- Have fun:尝试做一些疯狂而不寻常的事情。像所有人过去做过的那样构建 language,远不如尝试一点疯狂或出格的想法、观察它最终如何工作有趣。如果遇到困难或想交流,可以发到 LLVM forums;那里有许多对 languages 感兴趣、也愿意提供帮助的人。
在结束本教程前,再讨论一些生成 LLVM IR 的 tips and tricks。这些细节可能一开始并不明显,但如果想利用 LLVM 的 capabilities,它们非常有用。
LLVM IR 的性质
我们经常会遇到一些关于 LLVM IR code 的问题,先在这里集中回答。
Target Independence
Kaleidoscope 是一种“portable language”的例子:用 Kaleidoscope 编写的任何 program,在它运行的不同 targets 上都应以相同方式工作。许多其他 languages 也拥有这一性质,例如 Lisp、Java、Haskell、JavaScript 和 Python(注意:这些 languages portable,并不表示它们的所有 libraries 也 portable)。
LLVM 的一个优点是,它通常能够在 IR 中保留 target independence:可以把 Kaleidoscope compiler 生成的 LLVM IR 放到 LLVM 支持的任意 target 上运行,甚至可以输出 C code,再在 LLVM 原生不支持的 target 上编译它。要判断 Kaleidoscope compiler 生成的是 target-independent code 很简单:在生成 code 时,它从未查询任何 target-specific information。
LLVM 为 code 提供 compact、target-independent representation,这让很多人兴奋。但这些人在询问 language portability 时,通常想的是 C 或 C family language。之所以说这很不幸,是因为对于完全通用的 C code,除了到处携带 source code 之外,没有真正使其 portable 的方式(当然,C source code 一般也并不真正 portable——有没有把很老的 application 从 32-bit port 到 64-bit 的经历?)。
C(再次强调,是完全通用的 C)的问题在于,它充满了 target-specific assumptions。最简单的例子之一是:preprocessor 处理 input text 时,经常会破坏 code 原本的 target independence:
#ifdef __i386__
int X = 1;
#else
int X = 42;
#endif
当然,可以为这类问题设计越来越复杂的 solutions;但要在完全通用的情况下,找到一个比携带实际 source code 更好的方案是不可能的。
话虽如此,C 的一些 interesting subsets 确实可以做到 portable。如果愿意将 primitive types 固定为固定 size(比如 int = 32-bits、long = 64-bits),不关心与已有 binaries 的 ABI compatibility,并愿意放弃一些次要 features,就可以得到 portable code。这对某些 specialized domains(例如 in-kernel language)可能很有意义。
Safety Guarantees
上面提到的许多 languages 也是“safe languages”:假设 JVM 没有 bugs,Java program 不可能破坏自己的 address space 并让 process crash。Safety 是一项有趣的 property,需要 language design、runtime support,以及通常还包括 OS support 的共同配合。
当然可以用 LLVM 实现 safe language,但 LLVM IR 本身不保证 safety。LLVM IR 允许 unsafe pointer casts、use-after-free bugs、buffer over-runs 以及各种其他问题。Safety 必须作为 LLVM 之上的一层来实现;幸运的是,已经有多个 groups 研究过这个问题。想了解更多细节,可以询问 LLVM forums。
Language-Specific Optimizations
LLVM 让许多人失去兴趣的一点是:它不会在一个 system 中解决全世界的问题。一个具体抱怨是,人们认为 LLVM 无法执行 high-level language-specific optimization,因为 LLVM “丢失了太多 information”。这里有几点观察。
首先,这个判断有一定道理:LLVM 确实会丢失 information。例如,在撰写本文时,除了 debug info 外,在 ILP32 machine 上无法从 LLVM IR 区分某个 SSA value 源自 C 的 int 还是 long。二者都会编译成 i32 value,原始来源信息已经丢失。更一般的问题是,LLVM type system 使用的是 structural equivalence,而不是 name equivalence。另一个让人意外的地方是:如果 high-level language 中有两个 structure 相同的 types(例如两个不同的 structs,但都只有一个 int field),它们会编译成单个 LLVM type,之后无法再判断原始来源。
其次,虽然 LLVM 会丢失 information,但 LLVM 不是一个 fixed target:它会持续以多种方式增强和改进。除了添加新 features(LLVM 并非从一开始就支持 exceptions 或 debug info),LLVM 也会扩展 IR,以捕获对 optimization 重要的信息,例如 argument 是 sign-extended 还是 zero-extended,以及 pointer aliasing information 等。许多 enhancements 都由 users 驱动:人们需要某个 feature,于是就会推动 LLVM 加入它。
第三,加入 language-specific optimizations 既可能又容易,而且有多种做法。最简单的例子是加入“了解某门 language 的 code”的 language-specific optimization passes。对 C family 来说,就有一个了解 standard C library functions 的 optimization pass。如果在 main() 中调用 exit(0),它知道根据 C specification,可以安全地将其优化成 return 0;。
除了了解 libraries,还可以向 LLVM IR 中嵌入各种其他 language-specific information。如果有具体需求并遇到障碍,可以在 llvm-dev list 中提出。最坏情况下,也可以把 LLVM 当作一个“dumb code generator”,在 front-end 的 language-specific AST 上实现所需的 high-level optimizations。
实用技巧
LLVM users 在工作一段时间后会逐渐掌握许多 useful tips and tricks,它们一开始并不明显。与其让每个人重新发现它们,这里集中讨论其中一些问题。
实现 portable 的 offsetof/sizeof
如果希望 compiler 生成的 code 保持 target independent,一个常见需求是知道某个 LLVM type 的 size,或者某个 field 在 LLVM structure 中的 offset。例如,可能需要把 type 的 size 传给负责分配 memory 的 function。
遗憾的是,这些信息在不同 targets 上可能差异很大;pointer 的 width 就是显而易见的 target-specific information。不过,可以巧妙地利用 getelementptr instruction,以 portable 的方式计算它们。
Garbage Collected Stack Frames
有些 languages 希望显式管理自己的 stack frames,通常是为了让 stack frames 能够被 garbage collect,或者为了更容易实现 closures。实现这些 features 通常有比显式 stack frames 更好的方式,但 LLVM 确实支持这种做法。
它要求 front-end 将 code 转换为 Continuation Passing Style,并使用 tail calls;LLVM 同样支持 tail calls。
参考资料
- 10. Kaleidoscope: Conclusion and other useful LLVM tidbits — LLVM
- 系列索引(LLVM Kaleidoscope 系列导航)
- LLVM Kaleidoscope:调试信息(上一章:debug information)
评论 (0)