Master the fundamental concepts of optimizations through this focused micro-challenge.
Constant folding evaluates expressions with compile-time-known operands. Even -O0 Clang folds 2 + 3 to 5. JavaScript minifiers like Terser apply it on every production bundle. It enables further propagation and dead code removal.
Arithmetic, comparisons, and bitwise ops on literals. Boolean logic. Some sizeof and address-difference expressions in C. Stop before division by zero (may be runtime error) or side-effecting calls.
cLoading…
Production compilers embed this step inside a longer pipeline. GCC flows through cpp, cc1, assembly, and ld; Clang uses the driver, Sema, LLVM IR passes, and a target backend. LLVM bitcode, JVM bytecode, and WASM are other familiar IRs at the same layer. The exercise isolates one pass so you can test it alone before chaining it to the next stage.
You will implement constant folding on your IR. This exercise requires detecting instructions whose operands are all constants, replacing them with a single constant result, and enabling follow-on optimizations.
Implement constant folding as an AST optimization pass.
Implement fold_expression() that:
Handle these operations:
Handle edge cases:
Fold nested expressions:
(1 + 2) * (3 + 4) → 212 + 3 → 5 (literal node)x + 0 → x (identity optimization)x * 1 → x (identity optimization)0 * x → 0 (if no side effects)Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github