Peephole Optimization
What You'll Learn
You'll learn how compilers improve code quality by examining and optimizing small, local sequences of generated instructions.
The Core Idea
Peephole optimization is like proofreading a few sentences at a time in a document—you look through a small "window" (the peephole) at nearby instructions and apply simple pattern-matching rules to replace inefficient sequences with better ones.
After the compiler generates code, the output often contains redundant or suboptimal instruction patterns. Rather than analyzing the entire program, peephole optimization slides a small window (typically 2-5 instructions) over the generated code, searching for recognizable patterns that can be improved.
Common Patterns
Redundant loads and stores:
store R1, x
load R2, x
Can become: copy R1 to R2 directly, eliminating the memory access.
Algebraic simplifications:
add R1, R2, 0
Can become: mov R1, R2 (or eliminated entirely if R1 already equals R2).
Strength reduction:
mul R1, R2, 2
Can become: add R1, R2, R2 or a left shift, which is faster.
Unreachable code:
jump L1
...dead instructions...
L1:
The instructions between the jump and label can be removed.
How It Works
The optimizer maintains a sliding window over the instruction stream, checking each position against a library of pattern-replacement rules. When a match is found, it substitutes the improved sequence and may continue examining the same location (since new patterns might emerge).
Key Takeaway: Peephole optimization improves code quality through localized, pattern-based transformations of small instruction sequences, catching inefficiencies that emerge during code generation without requiring global program analysis.