Compiler Design

Peephole Optimization (Unit 5)


Peephole Optimization (Unit 5)

Peephole optimization is a local optimization technique performed on a small sliding window (the "peephole") of generated target code. The compiler examines a few consecutive instructions and replaces them with shorter or faster sequences.

  • Redundant Load/Store Elimination:
    STORE R0, x
    LOAD  R0, x    <-- redundant! x is already in R0
    --- Replaced by ---
    STORE R0, x
  • Algebraic Simplification & Strength Reduction:
    ADD R1, R1, #0   -> eliminated
    MUL R1, R1, #2   -> SHL R1, R1, #1 (shift left is faster)
  • Unreachable Code Elimination:
    JMP L1
    MOV R1, R2       <-- unreachable! Remove it
    L1: ...
  • Flow-of-Control Optimization:
    JMP L1
    L1: JMP L2       <-- chain of jumps
    --- Replaced by ---
    JMP L2           <-- jump directly