Skip to content
BIASED

Compilers and LLVM

The front end → SSA IR → passes → back end pipeline, Clang/LLVM, mem2reg, and why one IR serves many languages and CPUs.

The compiler pipeline

The previous note ended with a C loop the compiler deleted at -O2: twenty million iterations took no time because the result was known in advance. This topic opens that compiler. Follow one small function through LLVM — the infrastructure behind Clang, Rust, Swift and many others — from text to SSA IR, through optimization passes, out as machine code of the kind the assembly half of the course wrote by hand.

Notation. IR is the compiler’s intermediate representation. SSA is static single assignment form. A pass reads IR and writes IR (or an analysis). LLVM IR text uses %name for values, i32 for a 32-bit integer, ptr for a pointer, and a label ending in : for a basic block.

The running example is the sum 1+2+⋯+n1 + 2 + \dots + n:

int sum_to(int n) {
    int s = 0;
    for (int i = 1; i <= n; i++)
        s += i;
    return s;
}

The simplest compiler translates one language straight into the assembly of one processor. For one pair it works. It breaks in two ways. First, the pairs multiply: with MM languages and NN processors there are M⋅NM \cdot N compilers, and each repeats the same work — the C parser once per CPU, the RISC-V tables once per language. Three languages and three processors need nine compilers; ten of each need a hundred. Second, optimization has no home: keeping values in registers, folding constants and moving work out of loops are almost the same for every language and target, yet a per-pair compiler rewrites them M⋅NM\cdot N times or not at all.

Key idea. Put one representation in the middle. A front end per language translates source into a common IR; an optimizer rewrites IR into better IR as a sequence of independent passes that know nothing about the source language or the target; a back end per processor translates IR into machine code. Then MM languages and NN processors need M+NM + N parts instead of M⋅NM \cdot N, and every optimization is written once.

Clang’s driver prints the plan with -ccc-print-phases (trimmed): input → preprocessor → compiler (to IR) → backend (to assembler) → assembler (to object). Front ends include Clang for C/C++/Objective-C, rustc for Rust, swiftc for Swift. LLVM IR exists as in-memory data structures, readable .ll text and compact .bc bitcode. The -O2 pipeline runs dozens of passes, some several times. Back ends cover x86-64, AArch64, RISC-V, GPU targets and others.

LLVM IR and SSA

Inside Clang the front end works in four steps: preprocessing (#include, macros), lexing into tokens (s += i; → identifier, +=, identifier, ;), parsing an abstract syntax tree by the grammar of C, and semantic analysis (every name declared, s += i adds two ints, return type matches). Code generation then walks the AST and emits IR.

At -O0 Clang takes the simplest correct route: every local gets a stack slot (alloca), every use loads it and every assignment stores it. The for loop becomes four basic blocks — straight-line sequences entered only at the top and left only by a branch or return: a header for.cond that tests, a body, an increment and an exit. icmp sle is a signed less-or-equal comparison; the flag nsw (“no signed wrap”) records that C makes signed overflow undefined, so the optimizer may assume it never happens.

In that -O0 IR, %s names a memory slot stored twice; asking which store a load sees means following control flow. Static single assignment removes the question: every value is assigned exactly once, so every use names exactly one definition (Cytron et al., 1991). A changing variable becomes several values. Where control flow joins, SSA places a φ node (phi) that picks according to the predecessor block.

The pass mem2reg converts non-escaping stack slots into SSA values and inserts φ nodes where definitions meet. After opt -passes=mem2reg, every alloca/load/store for s and i is gone: besides branches and the return, the function has about 5 instructions instead of 17. In for.cond, %s.0 = phi [0, %entry], [%add, %for.inc] and %i.0 likewise chooses 1 or %inc.

Worked example. For n=3n = 3, control enters for.cond four times. The pairs (%i.0,%s.0)(\%i.0, \%s.0) are (1,0)(1, 0) from entry, then (2,1)(2, 1), (3,3)(3, 3) and (4,6)(4, 6) from for.inc. Comparisons 1≤31 \le 3, 2≤32 \le 3, 3≤33 \le 3 hold and 4≤34 \le 3 fails, so the function returns 6.

A pass either computes facts (dominators, loops, aliasing) or rewrites IR. Levels -O1/-O2/-O3/-Os are fixed pass sequences. On sum_to, IndVarSimplify uses scalar evolution: %i.0 starts at 1 and grows by 1, %s.0 is a sum of an arithmetic sequence. The pass replaces the loop by a closed form equal to n(n+1)/2n(n+1)/2 (evaluated in wider integers so 32-bit wrap matches the original). LoopDeletion then removes the empty loop — the same effect that erased the countdown at -O2.

Back end and why modularity

The back end lowers IR to a concrete ISA in stages: instruction selection maps IR operations to machine instructions (or patterns of them); register allocation maps the unlimited SSA values onto the processor’s finite registers and spills the rest to stack slots; scheduling orders instructions to hide latency; emission writes assembly or an object file. The calling convention — which registers hold arguments and the return value — is the same ABI the procedures-and-stack topic used by hand. Linking and loading then turn that object file into a process image, as earlier in the course.

Modularity is why the design matters. One IR means Clang, Rust and Swift share the same optimizer; adding a RISC-V extension is a back-end change, not a rewrite of every front end. Tools that need a correct C parser — the Clang Static Analyzer, clang-tidy — sit on the same front end. The course followed one program from bits through the ISA, caches, the OS and the network; this topic closes the loop at the compiler that produced the instructions the processor fetches.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.