Pipeline
Like most compilers, TinyGo is a compiler built as a pipeline of transformationsthat each translate an input to a simpler output version (also called lowering).However, most of these part are not in TinyGo itself. The frontend is mostlyimplemented by external Go libraries, and most optimizations and code generationis implemented by LLVM.
This is roughly the pipeline for TinyGo:
- Lexing, parsing, and typechecking is done by packages in thestandard library and in thegolang.org/x/tools/go library.
- SSAconstruction (a very important step) is done by thegolang.org/x/tools/go/ssapackage.
- The Go SSA is then transformed into LLVM IR by thecompiler package.Both forms are SSA, but because Go SSA is higher level and containsGo-specific constructs (like interfaces and goroutines) this is non-trivial.However, the vast majority of the work is simply lowering the available GoSSA into LLVM IR, possibly calling some runtime library intrinsics in theprocess (for example, operations on maps).
- Go does a lot of initialization at runtime, which is really bad forcode size. This includes all global variables: they are all initialized atruntime, not at compile time like C. So TinyGointerprets these functions at compile timeas far as it is able to.
- The resulting IR is then first optimized by a mixture of handpicked LLVMoptimization passes, TinyGo-specificoptimizations (escape analysis,
string
-to-[]byte
optimizations, etc.)and custom lowering. For example, this is the time when interfaces arelowered to their final form to benefit from the optimizations already doneuntil that point. - This LLVM IR is then optimized by the LLVM optimizer, which has a largearray of standard optimization passes.This is the standard optimization pipeline as is also used by Clang.
- After all optimizations have run, a few fixups are needed for AVR forglobals, because AVR has separate address spaces for flash and RAM. This isimplemented by the compiler package.
- Finally, the resulting machine code is emitted by LLVM to an object file.
This is just the compiler. TinyGo can also automatically link the file and flashit to a device, if needed.