Peephole Optimization
1. What It Is
Peephole slides a small window (2-4 instructions) over target/machine IR and replaces patterns with shorter/faster equivalents. Last pass, machine-specific, very cheap.
2. Classic Patterns (exam list)
| Pattern → Replacement | Why |
|---|---|
MOV R,R → delete |
redundant move |
ADD R,#0 / MUL R,#1 → delete |
algebraic identity |
PUSH R; POP R → delete |
useless stack round-trip |
MUL R,#2 → SHL R,1 |
strength (shift faster) |
JMP L1; L1: → L1: |
jump to next (fall-through) |
CMP R,#0; JGE → simpler test |
use flags directly |
| Store then load same addr → keep in reg | avoid memory |
3. Worked
LD R1, x
MOV R2, R1 → delete (use R1 directly)
ADD R2, #0 → delete
MUL R2, #2 → SHL R2, 1
ST y, R2
combines with branch chaining (goto goto collapsed) and null-sequence elim.
4. Strengths/Limits
Sees only window — misses global wins; but catches codegen artifacts no high-level opt sees.
5. Exam Points
- List peephole patterns with before/after — 5-7 marks, very frequent.
- Optimize given assembly snippet — 5 marks, frequent.
- Where peephole sits (after codegen) — 3 marks, frequent.