Code Optimization

Optimization improves the intermediate code so it runs faster or uses less memory, without changing what the program does.

Basic Blocks and Flow Graphs

A basic block is a maximal sequence of statements with one entry and one exit. Leaders are: (1) the first statement, (2) any target of a jump, (3) any statement immediately after a jump.

Optimization Techniques

TechniqueBeforeAfter
Constant foldingx = 2 * 3.14x = 6.28
Constant propagationn = 5; y = n * 2y = 10
Common subexpression eliminationa = b*c; d = b*c + et = b*c; a = t; d = t + e
Copy propagationx = y; z = x + 1z = y + 1
Dead code eliminationif (false) {...}(removed)
Strength reductionx * 2, i * 4 in loopx + x, t = t + 4
Loop-invariant code motionfor(...) { y = a*b; ... }y = a*b; for(...) {...}
Loop unrollingfor i in 0..3: s += a[i]s += a[0]+a[1]+a[2]+a[3]

DAG for a Basic Block

Text
a = b + c
b = a - d
c = b + c
d = a - d       ← same as line 2 (a - d already computed)  ⇒  d = b

Optimized:
a = b + c
b = a - d
c = b + c
d = b

Peephole Optimization

Examines a small window of target code to remove redundant loads and stores, eliminate unreachable code, simplify jump chains and apply algebraic simplifications (x + 0 → x).

Text
MOV R0, a
MOV a, R0      ← redundant (a already in R0): delete
Track your progress through the Compiler Design course