Constant Folding
You'll learn how compilers evaluate expressions with constants at compile-time to save work at runtime.
What is Constant Folding?
Constant folding is a compiler optimization that evaluates expressions involving only constant values during compilation rather than leaving them for runtime. When the compiler encounters 3 + 5 in your code, instead of generating instructions to add these numbers every time the program runs, it simply replaces the expression with 8 in the generated code.
Think of it like a teacher grading math homework. Instead of writing "calculate 2 × 10" as the answer, the teacher writes "20" directly. The calculation happens once during grading (compile-time), not every time someone reads the answer (runtime).
How It Works
When the compiler analyzes your intermediate representation (IR), it looks for operations where all operands are known constants. It performs the calculation immediately and replaces the operation node with the result.
For example:
x = 7 * 6 + 2becomesx = 44if (5 > 3)becomesif (true)y = 100 / 4 - 1becomesy = 24
Why It Matters
Constant folding reduces:
- Runtime computation: fewer instructions to execute
- Code size: simpler generated code
- Enables further optimizations: simplifying expressions can reveal dead code or invariant conditions
This optimization is safe because constants never change—the result will always be the same, so computing it once during compilation is both correct and efficient.
Key Takeaway: Constant folding lets the compiler do arithmetic once at compile-time instead of repeatedly at runtime, making your programs smaller and faster without changing their behavior.