Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Peephole optimisation

Peephole optimisation is a local, pattern-based compiler backend pass that scans small windows of target instructions to replace inefficient or redundant sequences with cheaper, correct ones, improving code size and speed under machine constraints.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Peephole optimisation is a small but powerful step in the compiler back end that an engineer uses when generating machine code or assembly. It cleans up and simplifies the final instruction stream to reduce size, remove redundancy, and improve runtime — without changing program behaviour — and it is often used alongside register allocation and instruction scheduling.

Key ideas

  • Pattern and replacement: a pattern is a template that matches a sequence of instructions (possibly with placeholders for registers, immediates). A replacement is the new instruction sequence that substitutes the matched sequence. The general rule syntax (to remember) is: pattern -> replacement [condition].

  • Semantics-preserving transformation (correctness condition): A replacement is valid if, for all machine states satisfying the preconditions, executing the original sequence and the replacement sequence results in the same observable behaviour. Define observable behaviour as those parts of the machine state that later code or the environment can depend on: registers that are live after the sequence, memory locations that may be read later, program-visible flags, and I/O effects. (Exact set of observables is architecture- and program-dependent; see verify.)

  • Preconditions: extra conditions required to ensure correctness. Examples: a register is not used elsewhere (liveness), memory addresses do not alias, instruction flags are not relied on, no memory-mapped I/O or volatile accesses in the window; do not assume interrupts are disabled—preserve any architecturally visible state an interrupt/exception handler could observe.

  • Liveness: a register is live-after an instruction sequence if the value it contains is used later (before being overwritten). We use Def (set of registers written), Use (set read). A typical check: a register that holds a value overwritten before any use is dead and stores to it can be removed (dead-store elimination).

  • Common peephole transformations (definitions):

    • Copy propagation: replace uses of a register that is a copy of another register by the original register (e.g., MOV R2, R1; ADD R3, R2, #4 -> ADD R3, R1, #4), provided the values are the same and no intervening writes.
    • Dead-store elimination: remove stores or moves that assign to a register or memory location whose value is never used later.
    • Constant folding (at machine level): compute arithmetic using constants known at compile time and replace sequence by immediate-loads or results.
    • Strength reduction: replace expensive op by cheaper ones that produce equivalent result for certain operands (e.g., multiply by 2 -> shift left by 1 if safe on target instruction set).
    • Algebraic simplification: use arithmetic identities (e.g., add 0, multiply by 1) removal when safe.
    • Combining adjacent instructions: merge two instructions into one target instruction (for example, two address calculations that can be fused into one indexed load) if the target supports it.
    • Branch folding / jump threading: simplify sequences of unconditional and conditional branches to reduce extra jumps.
    • Flag-aware simplifications: transform sequences while preserving or recomputing condition flags only if later code depends on them.
  • Cost model: each instruction has a cost (code size, cycles, energy). A peephole rule is applied if benefit (sum cost_old − sum cost_new) > 0, subject to correctness.

  • Ordering and fixpoint: apply transformations repeatedly until no rule applies in any window (a local fixpoint). Order of rules matters; some transformations enable or disable others. To prevent oscillation (two rules undoing each other), require a strict improvement in the chosen cost metric or remember and avoid zero-benefit back-and-forth rewrites.

  • Limitations and assumptions: peephole optimisations are local — they cannot see global register allocation decisions or long-range data flow beyond their window. They must be conservative about memory aliasing, volatile or memory-mapped I/O, and about floating-point arithmetic (non-associativity). Always record the preconditions.

Formulas

Since this is a programming/topic, learn these syntaxes and small formulas:

  • Rule syntax: pattern -> replacement [condition]

    • pattern: sequence with placeholders, e.g. MOV r1, r2; ADD r3, r1, #0
    • replacement: MOV r3, r2 (example) ; condition: r1 not live-after AND (flags not used or the replacement preserves them)
  • Cost and benefit: benefit = Σ cost(old_instructions) − Σ cost(new_instructions)

    • cost(inst): a numeric weight for an instruction (e.g., size in bytes or cycles)
    • apply rule if benefit > 0 and conditions hold
  • Liveness check (local): let Def(S) be registers written by sequence S, Use(S) be registers read. A value in register r is dead at end of S if r ∈ Def(S) and r ∉ LiveOut (LiveOut is set of registers needed after S). For peephole we often check: if a store to r is followed before any use by a write to r, the earlier store is dead.

Note: exact liveness equations for whole program rely on data-flow analysis from the compiler's earlier phases; peephole uses local liveness info that the compiler must provide.

Worked examples

Example 1 — copy propagation + dead-store elimination Input (assembly-like):

  1. MOV R2, R1
  2. ADD R3, R2, #4
  3. MOV R2, R0 Assume R2 is not live-after instruction 3, R3 is used later, and flags not used. Steps:
  • Window size 2: match instructions 1–2 with pattern MOV rX, rY; ADD rZ, rX, imm.
  • Replacement: ADD rZ, rY, imm if rX not redefined between and rY contains same value. Condition holds because instruction 3 redefines R2 but after ADD.
  • Replace lines 1–2 by ADD R3, R1, #4.
  • Now instruction 3 MOV R2, R0 assigns to R2 which is not live later — dead-store. Remove it. Final code:
  1. ADD R3, R1, #4 Result: one MOV and one ADD reduced to one ADD. Explain correctness: R3 gets same value; R2's final value was unused.

Example 2 — strength reduction (target has LSL instruction) Input:

  1. MUL R4, R5, #2
  2. ADD R6, R4, R7 Assume integer arithmetic, no overflow/flags needed. Steps:
  • Pattern MUL rA, rB, #2 can be replaced by LSL rA, rB, #1 (logical shift left by 1) on many ISAs.
  • Replace line 1 accordingly; final sequence:
  1. LSL R4, R5, #1
  2. ADD R6, R4, R7 Check preconditions: multiplication and shift semantics match for unsigned integers and for signed if two's-complement and overflow semantics are same; if overflow semantics differ or flags are observed, cannot apply.

Example 3 — branch folding Input:

  1. CMP R1, #0
  2. BEQ L1
  3. B L2 L1:
  4. ... L2:
  5. ... Steps:
  • In the window spanning instructions 2–3, see BEQ L1; B L2. If L1 is the fall-through of the conditional (i.e., it's immediately next) we can replace BEQ L1; B L2 with BNE L2 or reorder branches depending on fall-through layout. Draw diagram: show basic block with conditional branch to top of two successors. Condition: must confirm instruction layout and that flags are preserved.
  • Result: one branch replaced by one conditional branch to the other label or adjust fall-through to reduce one branch.

Common mistakes

  • Applying floating-point algebraic simplifications (like reassociating sums) without considering rounding and IEEE rules.
  • Using a strength-reduction rule (e.g., replace MUL by shift) without ensuring operand types and overflow/negative-number behavior match.
  • Not updating or consulting liveness information: removing a write that is actually used later.
  • Assuming transformations are always beneficial: sometimes a combined instruction may be slower on a target, or increases register pressure; always use a cost model.

For your exam

Question types you will see: definition (what is peephole optimisation), short notes (list common transformations and their preconditions), diagrams (draw a peephole window and show an example replacement), derivation/problem (prove correctness of a simple rule using liveness), algorithm/tracing (perform peephole passes on an instruction stream), and code-writing (write pattern->replacement rules for given ISA snippets).

What a full-marks answer includes:

  • A precise definition using the words window, pattern, replacement, and semantics-preserving.
  • Clear statement of preconditions (liveness, aliasing, flags, I/O) and why they matter.
  • One or two worked examples with step-by-step matching, condition checks, and final code.
  • A brief note on ordering/fixpoint and cost model (mention benefit computation).
  • If asked for a diagram, draw instruction boxes with window and arrow to replacement and label registers and live/dead marks.

Quick check

  1. Define peephole optimisation in one sentence.
  2. Give one precondition needed to replace MUL rX, rY, #2 by LSL rX, rY, #1.
  3. Why must you be careful about memory-mapped I/O when eliminating stores?

Answers: 1) A local compiler transformation that inspects a small contiguous window of target instructions and replaces matched inefficient sequences by cheaper ones while preserving observable behaviour. 2) Ensure integer semantics match (no different overflow or signedness behaviour) and flags are not relied on; also the target supports the shift instruction. 3) Because stores to memory-mapped I/O have side-effects the program or the environment relies on, so removing them changes observable behaviour.

Note for reviewer: I have been conservative about details tied to particular ISAs (flag semantics, signed vs unsigned multiply/shift equivalence, exact definition of observable behaviour). See verify list for the small claims I ask you to confirm.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?