Compiler Design

Peephole Optimization


Peephole Optimization

Peephole Optimization is a machine-dependent, local optimization technique applied on a small, sliding window (the "peephole") of consecutive target code instructions. The optimizer examines 2 to 10 instructions at a time and replaces inefficient sequences with faster or shorter equivalents.

Removes back-to-back load/store pairs where the result is immediately undone, provided there is no label (entry point) before the second instruction.

// Original:
STORE R1, a
LOAD  a, R1   <-- Redundant!

// Optimized:
STORE R1, a

Uses simple algebraic identities to eliminate operations entirely.

x = x + 0;   // Eliminated
y = y * 1;   // Eliminated
z = z / 1;   // Eliminated

Evaluates constant expressions at compile time rather than at runtime.

// Original:
a = 2 * 3.14

// Optimized (at compile time):
a = 6.28

Replaces expensive operations (like multiplication or division) with cheaper equivalents (like addition or bit-shifts).

x = y * 2;   // Replace with: x = y + y (or y << 1)
z = x / 2;   // Replace with: z = x >> 1

Removes instructions that can never be executed (e.g., code appearing immediately after an unconditional jump, with no label).

Simplifies jumps that immediately target other jumps.

// Original:
     goto L1
     ...
L1:  goto L2

// Optimized:
     goto L2
     ...
L1:  goto L2