17. Optimization Passes

Making compiled code faster

Programmers write code for humans — with named constants, clear variable names, and small functions that each do one thing. Compilers rewrite that code for machines. The rewrites are called optimization passes, and a modern compiler runs dozens of them. Each pass reads the program, applies a transformation, and produces a new (hopefully faster) version.

The key contract: every optimization must preserve the program's observable behavior. It can change how the answer is computed, but never what the answer is.

Where optimizations happen

Optimizations can be applied at three levels:

  1. AST level — transform the tree before generating any code. Good for algebraic simplifications.
  2. IR level — transform the intermediate representation (three-address code, SSA form). This is where most serious optimizations live.
  3. Bytecode / machine code level — peephole optimizations that clean up instruction sequences after code generation.

Most compilers do a mix of all three. Let's walk through the most important optimizations, from simplest to most powerful.

Constant folding

If both operands of an expression are known at compile time, compute the result during compilation instead of at runtime.

Before:

t0 = 2 + 3
t1 = t0 * 4

After:

t0 = 5
t1 = 20

Implementation on an AST is straightforward — if both children of a binary node are number literals, replace the node with a new literal:

function foldConstants(node) {
  if (node.type !== 'BinaryExpr') return node;

  // Recurse first so nested constants bubble up
  node.left = foldConstants(node.left);
  node.right = foldConstants(node.right);

  if (node.left.type === 'NumberLiteral' && node.right.type === 'NumberLiteral') {
    const a = node.left.value, b = node.right.value;
    let result;
    switch (node.op) {
      case '+': result = a + b; break;
      case '-': result = a - b; break;
      case '*': result = a * b; break;
      case '/': result = a / b; break;
      default: return node;
    }
    return { type: 'NumberLiteral', value: result };
  }
  return node;
}

This single pass handles nested constant expressions like (2 + 3) * (4 + 1) because the recursion folds inner expressions first, turning them into literals before the outer expression is checked.

Constant propagation

If a variable is assigned a constant and never reassigned, replace all uses of that variable with the constant value.

Before:

x = 5
y = x + 3
z = x * y

After constant propagation:

x = 5
y = 5 + 3
z = 5 * y

After constant folding (second pass):

x = 5
y = 8
z = 40

This is why compilers run passes repeatedly — one optimization creates opportunities for another. The compiler keeps looping until nothing changes (a "fixed point").

function propagateConstants(instructions) {
  const constants = new Map();  // variable → constant value

  return instructions.map(instr => {
    // Substitute known constants into uses
    const newInstr = substituteUses(instr, constants);

    // If this is an assignment of a constant, record it
    if (newInstr.type === 'assign' && isConstant(newInstr.value)) {
      constants.set(newInstr.dest, newInstr.value);
    } else if (newInstr.type === 'assign') {
      // Variable is reassigned to something non-constant — forget it
      constants.delete(newInstr.dest);
    }

    return newInstr;
  });
}

Dead code elimination

Remove code whose result is never used. If a variable is assigned but never read, the assignment is dead and can be deleted.

Before:

a = expensive_computation()
b = 42
return b

After:

b = 42
return b

The assignment to a is dead — nothing ever reads a. Eliminating it saves the cost of expensive_computation() (assuming no side effects).

function eliminateDeadCode(instructions) {
  // Find all variables that are actually used
  const used = new Set();
  for (const instr of instructions) {
    for (const v of instr.uses) used.add(v);
  }

  // Keep only instructions whose definitions are used (or that have side effects)
  return instructions.filter(instr => {
    if (instr.hasSideEffects) return true;
    if (instr.defs.length === 0) return true;  // no definition (e.g., return)
    return instr.defs.some(d => used.has(d));
  });
}

The "side effects" check is crucial — you can't remove a print() call even if nobody uses its return value.

Strength reduction

Replace expensive operations with cheaper equivalents.

Before After Why
x * 2 x << 1 Shift is one cycle, multiply may be more
x * 0 0 No computation needed
x * 1 x No computation needed
x + 0 x Identity elimination
x / 4 x >> 2 For unsigned integers
x ** 2 x * x Avoids general exponentiation
function reduceStrength(node) {
  if (node.type !== 'BinaryExpr') return node;

  node.left = reduceStrength(node.left);
  node.right = reduceStrength(node.right);

  const { left, right, op } = node;

  // Multiply by power of 2 → shift
  if (op === '*' && right.type === 'NumberLiteral' && isPowerOf2(right.value)) {
    return { type: 'BinaryExpr', op: '<<', left, right: {
      type: 'NumberLiteral', value: Math.log2(right.value)
    }};
  }

  // Multiply by 0 → 0
  if (op === '*' && right.type === 'NumberLiteral' && right.value === 0) {
    return { type: 'NumberLiteral', value: 0 };
  }

  // Multiply by 1 → identity
  if (op === '*' && right.type === 'NumberLiteral' && right.value === 1) {
    return left;
  }

  // Add 0 → identity
  if (op === '+' && right.type === 'NumberLiteral' && right.value === 0) {
    return left;
  }

  return node;
}

Common subexpression elimination (CSE)

If the same expression is computed more than once and the operands haven't changed, compute it once and reuse the result.

Before:

a = b + c
d = b + c
e = a + d

After:

a = b + c
d = a        // reuse the earlier computation
e = a + d

This saves one addition. In loops or in code with complex index calculations, CSE can eliminate a large number of redundant operations.

Function inlining

Replace a function call with the body of the function. This eliminates the overhead of the call (pushing a frame, jumping, returning) and — more importantly — it exposes the function body to the caller's optimization context.

Before:

function square(x) { return x * x; }
let result = square(5);

After inlining:

let result = 5 * 5;

After constant folding:

let result = 25;

Inlining is one of the most impactful optimizations because it's an enabling optimization — it creates opportunities for constant folding, dead code elimination, and other passes that couldn't see through the function boundary before.

The downside: inlining increases code size. Compilers use heuristics — inline small functions, inline hot functions (called frequently), but don't inline recursive functions or functions that are too large.

Loop-invariant code motion

Move computations that produce the same result on every iteration of a loop to outside the loop.

Before:

for (let i = 0; i < n; i++) {
  let offset = base + stride;    // same every iteration
  arr[i] = data[i + offset];
}

After:

let offset = base + stride;      // computed once
for (let i = 0; i < n; i++) {
  arr[i] = data[i + offset];
}

If base and stride don't change inside the loop, then base + stride is a loop-invariant expression. Moving it out saves one addition per iteration.

Peephole optimization

A peephole optimizer looks at a small window (2-3 instructions) of generated code and replaces known-bad patterns with better ones. It runs after code generation as a cleanup pass.

function peephole(bytecode) {
  const result = [];

  for (let i = 0; i < bytecode.length; i++) {
    const op = bytecode[i];
    const next = bytecode[i + 1];

    // Push then immediate pop → eliminate both
    if (op.type === 'PUSH' && next && next.type === 'POP') {
      i++;  // skip both
      continue;
    }

    // Jump to next instruction → eliminate the jump
    if (op.type === 'JUMP' && op.target === i + 1) {
      continue;
    }

    // Double negation → eliminate both
    if (op.type === 'NEGATE' && next && next.type === 'NEGATE') {
      i++;  // skip both
      continue;
    }

    // Load followed by store to same location → eliminate both
    if (op.type === 'LOAD' && next && next.type === 'STORE'
        && op.slot === next.slot) {
      i++;
      continue;
    }

    result.push(op);
  }
  return result;
}

Peephole optimization is cheap and catches patterns that earlier passes miss — especially patterns created by the code generator itself.

Putting it all together

A typical optimization pipeline looks like this:

AST
 ├─ constant folding
 ├─ strength reduction
 ↓
IR (three-address code / SSA)
 ├─ constant propagation
 ├─ dead code elimination
 ├─ common subexpression elimination
 ├─ loop-invariant code motion
 ├─ function inlining
 ├─ (repeat until fixed point)
 ↓
Machine code / bytecode
 ├─ register allocation
 ├─ peephole optimization
 ↓
Final output

Each pass is simple and self-contained. The power comes from composing them — inlining exposes constants, constant propagation enables dead code elimination, dead code elimination makes register allocation easier, and so on.

GCC runs over 200 passes. LLVM's default optimization pipeline (-O2) runs about 80. Most are variations and repetitions of the core ideas above.

Try It Yourself — Optimization Explorer

Enter a simple program and watch as each optimization pass transforms the code step by step. The explorer shows which pass fired, what changed, and the final optimized result.

Result