Code Generation

The compiler back end — instruction selection, register allocation (graph colouring, linear scan, spilling), instruction scheduling, calling conventions and stack frames, and what assemblers and linkers do afterwards.

Advanced 4 min readLesson 6 of 8

The back end turns optimised IR into machine code for a specific CPU. It solves three main problems: which instructions to use, which registers hold which values, and in what order to issue instructions.

Instruction selection

IR operations must be mapped to the target's instructions. Real ISAs offer many ways to do the same thing, and good selection picks the cheapest pattern covering several IR operations at once:

IR:   t1 = b * 4
      t2 = a + t1
      t3 = load t2

x86-64 (one instruction covers all three via addressing modes):
      mov eax, DWORD PTR [rdi + rsi*4]

Techniques: tree pattern matching / tiling (cover the IR tree with instruction "tiles" of minimum cost), and DAG-based selectors (LLVM's SelectionDAG and GlobalISel). Target descriptions (LLVM's TableGen files) list each instruction's pattern and cost.

Register allocation

IR assumes unlimited virtual registers; real CPUs have few (16 general-purpose on x86-64, 31 on ARM64). The allocator assigns virtual registers to physical ones and, when there aren't enough, spills some to the stack (memory is ~100× slower than a register, so spilling costs).

Liveness and interference

A variable is live at a point if its current value may be read later. Two variables that are live at the same time interfere — they can't share a register.

a = 1           live: a
b = 2           live: a b
c = a + b       live: b c          (a dies here)
d = c * b       live: d            (b, c die)
return d

Graph colouring

Build an interference graph (nodes = variables, edges = interference) and colour it with K colours (K = number of registers) so that no adjacent nodes share a colour. Graph colouring is NP-hard in general, so compilers use heuristics (Chaitin–Briggs): repeatedly remove nodes with fewer than K neighbours; if stuck, pick a node to spill.

abcd
Interference graph colourable with 2 registers: a, c, d share one (never live together); b gets the other

Linear scan

JIT compilers can't afford graph colouring's compile time. Linear scan sorts variables' live intervals and walks them once, assigning free registers and spilling the interval that ends furthest away. It's much faster with slightly worse code — used by HotSpot C1, V8 and many JITs.

Coalescing removes register-to-register moves by assigning both sides of b = a to the same register when they don't interfere.

Instruction scheduling

Modern CPUs are pipelined and superscalar (Pipelining). Scheduling reorders independent instructions to hide latencies — e.g. issuing a load early so its result is ready when needed — while respecting data dependencies. Out-of-order CPUs do much of this in hardware, but scheduling still matters for in-order cores and for exposing parallelism.

Calling conventions and stack frames

Separately compiled functions must agree on an ABI (application binary interface): where arguments go, who saves which registers, how the stack is laid out. On x86-64 Linux/macOS (System V ABI):

ItemConvention
Integer/pointer argumentsrdi, rsi, rdx, rcx, r8, r9, then the stack
Float argumentsxmm0–xmm7
Return valuerax (and rdx), xmm0 for floats
Callee-savedrbx, rbp, r12–r15 (a function must restore them)
Caller-savedEverything else (may be clobbered by calls)
Stack alignment16 bytes at call sites

(Windows x64 uses rcx, rdx, r8, r9 and a 32-byte "shadow space".)

long add3(long a, long b, long c) { return a + b + c; }

add3:                       ; a in rdi, b in rsi, c in rdx
    lea  rax, [rdi + rsi]   ; rax = a + b
    add  rax, rdx           ; rax += c
    ret                     ; result in rax

A function that needs stack space sets up a stack frame with a prologue and epilogue:

f:
    push rbp                ; save caller's frame pointer
    mov  rbp, rsp           ; new frame pointer
    sub  rsp, 32            ; space for locals and spills
    ...
    mov  rsp, rbp           ; epilogue
    pop  rbp
    ret

Stack frames hold the return address, saved registers, spilled values and locals — the same structure you see in a debugger's backtrace (Processes).

Assembling and linking

  1. Assembler: turns assembly text into an object file (ELF on Linux, Mach-O on macOS, PE/COFF on Windows) containing machine code in sections (.text code, .data initialised globals, .bss zeroed globals, .rodata constants), a symbol table, and relocations — placeholders for addresses not yet known.
  2. Linker: combines object files and libraries, resolves symbols (each call to printf must find exactly one definition — otherwise "undefined reference" or "multiple definition" errors), assigns final addresses, and patches relocations.
LinkingHowTrade-off
StaticLibrary code copied into the executableSelf-contained, larger binary
DynamicShared libraries (.so, .dylib, .dll) loaded at runtime via PLT/GOT indirectionSmaller, shared in memory, patchable; "DLL hell"
  1. Loader: the OS maps the executable's segments into memory, loads shared libraries, and jumps to the entry point (_start, which calls main).

Other targets

  • WebAssembly: a stack-based virtual ISA; compilers emit Wasm and the browser's engine compiles it to native code.
  • GPUs: shaders and CUDA kernels compile to PTX/SPIR-V and then to vendor-specific machine code.
  • Bytecode: javac and CPython's compiler emit VM bytecode instead of machine code (Interpreters and VMs).
Key takeaways
  • Instruction selection maps IR to the cheapest covering instruction patterns.
  • Register allocation assigns unlimited virtual registers to few physical ones; graph colouring for AOT compilers, linear scan for JITs; spills go to the stack.
  • Instruction scheduling reorders independent instructions to hide latency.
  • The ABI fixes argument registers, callee/caller-saved registers and stack frame layout.
  • Assemblers produce object files with symbols and relocations; linkers resolve symbols statically or dynamically; loaders map the program into memory.