Writing a native compiler in C that emits x86-64 assembly
compilersx86-64assemblyctype-checkingpratt-parserfuzzingtestingh-language
How the hc compiler for the H language (Designing a programming language's syntax and semantics (lessons from H)) turns source
into a native Linux executable with nothing but C, a hand-written front end, GNU assembler text
and the system C compiler. No LLVM, no IR yet. The structure and the gotchas apply to any small
compiler that wants to produce real machine code quickly. Repo ~/dev/h.
Pipeline
game._ ──► hc (C11) ──► game.s (AT&T x86-64) ──► cc (as + ld) ──► ./game
▲
libh.a (runtime in C: printing, input,
strings, lists, errors, later a GC)
- Lexer: hand-written and table-driven (keywords and punctuation are data, so renaming them is cheap later).
- Parser: recursive descent for statements, Pratt parsing for operators (binding powers
per operator; the pipe
|binds between assignment and||). The tree prints as S-expressions (hc --tree), which makes parser tests readable. - Checker (
check.c): resolves names through a stack of block scopes, gives every variable a stack slot (sibling blocks reuse slots), and computes static types. - Code generator: emits assembly text directly from the tree. The driver then runs
ccto assemble and link with the runtime library, so the C toolchain does the object-file work. - The runtime is ordinary C linked into every executable:
main()calls the generatedh_main(). Compiled code and runtime talk through the System V ABI, so calling C from generated code is just acall.
Grow it one working compiler at a time
Follow Abdulaziz Ghuloum's An Incremental Approach to Compiler Construction (2006): every
milestone ends with a compiler that builds real executables and passes all tests. H went M0
(tooling), M1 (echo 42; end to end), M2 (arithmetic, booleans, if expressions), M3 (typed
variables and a checker), M4 (functions, recursion), M5 (strings, input, lazy streams),
M6 (heap lists). The first milestone that matters is the smallest program that goes all the way
to a running binary; every later step only extends a pipeline that already works. Also useful:
Nystrom's Crafting Interpreters (scanner and parser chapters) and Rui Ueyama's chibicc for
assembly-emission patterns.
Tests that scale with the language
tests/ok/NAME._must compile and print exactlyNAME.out(optionalNAME.inas stdin,NAME.statusfor the exit code).tests/err/NAME._must fail, and stderr must contain each line ofNAME.err(substring match, so message wording can improve).- Run the whole suite under gcc and clang, and again with the compiler built under ASan + UBSan in a separate build directory. A compiler is a pointer-heavy C program; the sanitizer build catches its memory bugs before they become wrong code.
- Set a fixed random seed in tests (an environment variable the runtime reads) so programs using
random()have stable output.
Differential fuzzing against a reference
Write a generator of random programs, compute the expected answer with an independent
implementation that shares the semantics, and compare. For arithmetic, Python is the oracle when
the language uses floor division and modulo (as H does): generate random nested + - * / % and
negation expressions, evaluate them with ast (rewriting / to //), compile each one with the
real compiler, run it, and compare output. The details that make it useful:
- Check every intermediate value against the language's integer range in the oracle, so the
fuzzer predicts exactly which expressions must fail with an overflow or division-by-zero runtime
error, and treats "error" as an expected output.
- Bias the leaves toward edge values (0, 1, 2^31, 2^40, the maximum) instead of uniform randoms;
uniform numbers almost never hit the boundaries.
- Use a fixed seed so a mismatch is reproducible, and print the failing expression.
- Wire it into the build (make fuzz) so it runs like any other test.
The same idea works for any feature with a trusted reference: string functions vs Python,
a parser vs a known-good parser, an optimized path vs the simple one.
Values and runtime representation
- Tagged 64-bit words: integers are fixnums with the low bit set (so 63-bit integers);
pointers to 8-byte-aligned heap objects have low bit 0;
false,trueand nil are reserved immediates (H uses 0x02, 0x0A, 0x12, low bits010). - Every heap object starts with a header word
(length << 8) | type. String literals are static objects of the same layout in.rodata, so literals and run-time strings are handled by the same code. - No real value is the word 0, so 0 can mean "not initialized yet". H keeps top-level variables
in
.bss(zero at start), and inside functions every use of a global first checks for 0 and reports "used before its declaration ran". - One text-to-int routine shared by compiler and runtime (
src/textint.h): the compile-time check ofint("123")and the run-time conversion can never disagree.
Code generation without a register allocator
- Stack machine: the current value lives in
%rax; a binary operator evaluates the left side, pushes it, evaluates the right side, pops the left into another register, and combines. Simple, correct, and fast enough to start with. - Keep
%rsp16-byte aligned at everycall. The System V ABI requires it, and C library functions (anything using SSE,printfincluded) can crash when it is wrong. With a stack machine the push depth varies, so the code generator tracks the depth and pads before calls. - Runtime checks jump to per-site error stubs placed after the function bodies. Each stub loads
that site's file, line and column and calls a runtime error function, so the fast path stays a
single conditional jump (
joafter the add for overflow, a compare for division by zero), and the message isfile:line:col: runtime error: .... - Calling convention for the language's own functions can be simpler than the C ABI: H pushes
arguments left to right, calls, and pops; parameter
iofkis at16+8*(k-1-i)(%rbp). Calls into the C runtime use the System V registers (%rdi,%rsi, ...). Mistakes in the 32-bit register name table (%edivs%esioffsets) produce bugs that look like runtime-library bugs. - Symbol mangling: pick a character the source language cannot use in names. H names may end in
?, which assemblers do not accept, sofn alive?becomesh_fn.alive.p(.cannot appear in an H name, so no collision is possible). returnjumps to the epilogue, whereleavediscards anything still pushed;breakpops the words pushed since the loop began.
Static types as bit sets
Give each expression the set of types it can produce (TY_INT | TY_STR | TY_BOOL | TY_NIL, plus
one bit per list type). if c { 1 } is "int or nil"; arithmetic demands exactly int; a variable
accepts exactly its own type. Control transfers (return, break, an endless loop) have the
empty set, "nothing", so if c { return 1; } else { 2 } is plain int with no special casing.
Literal [] gets its own "empty list" type that fits any list type. Keep the runtime type checks
as a safety net until the compiler can prove them unnecessary.
One bit per list type runs out (the 25th distinct list or function type stopped the build). The replacement, an interned type table that keeps the bit set for built-in kinds, is described in Garbage collection, exceptions, records and modules in a small native compiler.
Streams and pipelines without closures
A pipeline whose stages are literal functions (src | each (x) { body }) compiles to nested loops:
make an iterator, call next() until it returns 0, store the item, run the body inline. The body
then needs no closure and can read and write the enclosing variables directly. Files are read
lazily in 64 KB chunks, so a pipeline over a large file uses constant memory.
Definite-assignment tracking
Give each variable a state in the checker: set, unset, or maybe. Snapshot the states before a branch, check each arm from the snapshot, and merge (set only if set on every arm that falls through). Pre-scan loop bodies for what they may assign and mark those "maybe" before checking the body. Reading an unset variable is a compile error; reading a "maybe" one sets a flag on that node so codegen emits a compare against a reserved "no value" bit pattern stored by the declaration, jumping to a shared error stub. Globals read inside functions are always checked at run time.
Closures before escaping closures
The first step of function literals reaches outer variables through a static link: each closure
frame stores its defining frame's base pointer at a fixed slot (16(%rbp), with arguments starting at
24), and an outer variable is found by following the link. That is correct only while closures
cannot escape their frame; once they can be returned or stored, shared variables must move to heap
cells (boxes) or frames to the heap. Ship the non-escaping version first, keep function types
unnamed until then, and the static link never becomes a dangling pointer. A break in an each
body targets the whole pipeline: the code generator records the pipeline's exit label as the
current loop target so the jump leaves every nested stage loop.
Stack overflow as an error, not a crash
Deep recursion would just segfault. Install a SIGSEGV handler that runs on an alternate signal
stack (sigaltstack; the normal stack is exactly what overflowed) and print
runtime error: stack overflow (recursion too deep).
Gotchas
- With sanitizers, gcc can emit a false
-Wformat-overflow"null destination" warning forsprintfinto arena memory. Marking the arena allocator__attribute__((returns_nonnull))(and usingmemcpy) silenced it. - If keyword checks use enum ranges (
KW_CONST..KW_FLOAT= "starts a declaration"), new keywords must be added outside the range, or they silently become declaration keywords. - Strings allocated by the runtime are never freed until there is a GC (added later as mark and
sweep at safe points, see Garbage collection, exceptions, records and modules in a small native compiler); run sanitizer checks of
compiled programs with
ASAN_OPTIONS=detect_leaks=0. - An error that points at the right line but the wrong token (the
=instead of the variable name) is still worth a test; error positions are part of the interface.
See also
- Designing a programming language's syntax and semantics (lessons from H)
- Garbage collection, exceptions, records and modules in a small native compiler
- umlol, a programming language whose source is a flowchart
- Parallel reductions and associativity (std::transform_reduce as the case study)