IR & Optimisation
Intermediate representations (three-address code, control-flow graphs, SSA form, LLVM IR) and the classic optimisations — constant folding, dead code elimination, CSE, inlining, loop optimisations, vectorisation and escape analysis.
After semantic analysis, the compiler lowers the AST into an intermediate representation (IR) that's easier to analyse and transform. Most of a modern compiler's code and compile time goes into optimising this IR.
Kinds of IR
| IR | Shape | Used by |
|---|---|---|
| AST | Tree, close to the source | Front ends, linters, transpilers |
| Three-address code (TAC) | Linear instructions, at most one operator each: t1 = a + b | Textbooks, many compilers internally |
| Control-flow graph (CFG) | Basic blocks (straight-line code) connected by jumps | Every optimising compiler |
| SSA form | Each variable assigned exactly once | LLVM, GCC (GIMPLE), HotSpot C2, V8 TurboFan, Go |
| Stack bytecode | Push/pop operations | JVM, CPython, WebAssembly |
Control-flow graph
A basic block is a maximal sequence of instructions with one entry (the top) and one exit (the bottom). Edges are possible jumps.
int abs_sum(int a, int b) {
int s = a + b;
if (s < 0) s = -s;
return s;
}Static single assignment (SSA)
In SSA, every variable is assigned once; reassignments create new versions. Where control flow merges, a φ (phi) function picks the version from whichever predecessor ran:
B0: s1 = a + b
if s1 < 0 goto B1 else B2
B1: s2 = -s1
goto B2
B2: s3 = φ(s1 from B0, s2 from B1)
return s3Why SSA? Each use has exactly one definition, so "where does this value come from?" is trivial, which makes many optimisations simpler and faster (constant propagation, dead code elimination, register allocation).
LLVM IR
LLVM IR is a typed, SSA-based, assembly-like language:
define i32 @abs_sum(i32 %a, i32 %b) {
entry:
%s = add nsw i32 %a, %b
%neg = icmp slt i32 %s, 0
br i1 %neg, label %flip, label %done
flip:
%ns = sub nsw i32 0, %s
br label %done
done:
%r = phi i32 [ %s, %entry ], [ %ns, %flip ]
ret i32 %r
}At -O2, LLVM turns the branch into a branchless select (or a single abs-style instruction sequence) — see for yourself with clang -O2 -S -emit-llvm.
Classic optimisations
| Optimisation | Before | After |
|---|---|---|
| Constant folding | x = 60 * 60 * 24 | x = 86400 |
| Constant propagation | n = 4; y = n * 2 | y = 8 |
| Dead code elimination | t = a * b; (t never used) | removed |
| Common subexpression elimination | x = a*b + c; y = a*b + d | t = a*b; x = t + c; y = t + d |
| Copy propagation | y = x; z = y + 1 | z = x + 1 |
| Strength reduction | x * 8, i * 4 in a loop | x << 3, a running += 4 |
| Algebraic simplification | x + 0, x * 1, x - x | x, x, 0 |
| Unreachable code elimination | if (false) { … } | removed |
Inlining — the most important one
Inlining replaces a call with the callee's body. It removes call overhead, but more importantly it exposes other optimisations: after inlining, constants propagate into the body, branches fold away, and values stay in registers.
static int square(int x) { return x * x; }
int f() { return square(5) + 1; }
// after inlining + constant folding:
int f() { return 26; }The cost is code size, so compilers use heuristics (callee size, call frequency, hotness from profiles).
Loop optimisations
Programs spend most of their time in loops:
- Loop-invariant code motion (LICM): move computations that don't change across iterations out of the loop.
- Induction variable simplification / strength reduction: replace
a[i*stride]address computation with an incrementing pointer. - Loop unrolling: do 4 iterations per loop trip to reduce branch overhead and enable scheduling.
- Vectorisation: use SIMD instructions to process 4–16 elements at once (Instruction-level parallelism).
- Loop fusion / interchange / tiling: improve cache locality (Cache memory).
// Before LICM
for (int i = 0; i < n; i++) a[i] = x * y + i;
// After
int t = x * y;
for (int i = 0; i < n; i++) a[i] = t + i; // and then vectorisedOther important analyses
- Escape analysis: if an object never escapes a function, allocate it on the stack or eliminate it (scalar replacement) — big wins in Java and Go.
- Alias analysis: can two pointers refer to the same memory? If not, loads can be reordered and cached in registers. (C's
restrictand Rust's&mutuniqueness give the compiler this guarantee.) - Devirtualisation: turn a virtual call into a direct (inlinable) call when the receiver type is known.
- Tail-call elimination: turn a call in tail position into a jump, so recursion uses constant stack.
Optimisation levels and passes
Optimisers are a pipeline of passes, each doing one analysis or transform, repeated because one enables another:
| Flag | Meaning |
|---|---|
-O0 | No optimisation; fast compile, easy debugging |
-O1 / -O2 | Standard optimisations (release builds usually use -O2) |
-O3 | Aggressive inlining and vectorisation; bigger code, not always faster |
-Os / -Oz | Optimise for size |
-flto | Link-time optimisation across translation units |
PGO (-fprofile-use) | Profile-guided: optimise using data from real runs |
- IRs (three-address code, CFGs of basic blocks, SSA) make analysis and transformation tractable.
- SSA gives every variable one definition, with φ functions at merge points.
- Classic optimisations: constant folding/propagation, dead code elimination, CSE, strength reduction.
- Inlining is the most important optimisation because it enables others.
- Loop optimisations (LICM, unrolling, vectorisation) and escape/alias analysis deliver major speedups.
- Optimisers are pass pipelines; -O levels, LTO and PGO control how aggressive they are.