Compilers & Code Generation

constant propagation

If you know that x is always 5, then anywhere you later use x, you might as well write 5 — and once you do, an expression like x + 3 can be computed right now as 8, with no run-time arithmetic at all. That two-part idea, replacing variables with their known constant values and then evaluating the resulting constant expressions, is constant propagation together with its partner, constant folding.

The two work hand in hand. Constant folding is the simpler half: at compile time, evaluate any expression whose operands are all constants — 3 * 4 becomes 12, 1 << 4 becomes 16. Constant propagation is the dataflow half: track which variables hold known constant values and substitute them at their uses. So if the compiler proves n = 10, it replaces later uses of n with 10, which often creates fresh all-constant expressions for folding to crunch. The two cascade: propagate, fold, and the new constants may propagate further. In SSA form this is especially clean, because each value has a single definition to trace, and a refined version (sparse conditional constant propagation) even folds away branches whose condition is now known.

It matters because this is one of the most universally applied optimizations — it cleans up the redundancy that abstraction and inlining leave behind, shrinks code, and feeds dead-code elimination (a branch whose condition folds to false makes one side dead). A caveat worth stating: the compiler may only fold when the result is provably identical to running the program, so it is careful with things like floating-point rounding and operations whose result depends on run-time values; and it will not invent a constant it cannot prove, so a value that merely happens to be constant in your test run but is read from input is not propagated.

int n = 10; int area = n * n + 0; // const-prop replaces n with 10, const-fold evaluates 10*10+0: int area = 100; // no multiply or add survives to run time

Propagating n=10 turns the expression all-constant, then folding computes it once at compile time.

The optimizer only propagates a value it can PROVE is constant on every path, not one that merely looks constant in a test run; and it stays conservative where folding might change the result (e.g. some floating-point rounding).

Also called
constant foldingconst-propsparse conditional constant propagation常數摺疊