📚 Encyclopedia

Programming Languages · updated 2026-11-30

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)

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

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

Code generation without a register allocator

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

See also

Linked from

Sources: h repo (DESIGN.md, src/, runtime/libh.c, tools/fuzz_arith.py), h memory, tldr posts #1846 #1876, 2026-10-27..10-31