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 together with constant propagation over straight-line code: evaluate every sub-expression whose operands are known constants at compile time, and substitute variables whose current value is a known constant.
One assignment per line (blank lines ignored):
cLoading…
EXPR uses integer literals, variable names, + - * / %, < <= > >= == !=, unary - and parentheses, with C precedence (comparisons lowest, then + -, then * / %, then unary -); binary operators are left-associative. Arithmetic is 64-bit signed; / and % truncate toward zero; comparisons give 1 or 0.
x * 1 stays) and no reassociation: x + 1 + 2 is (x + 1) + 2, which does not fold./ or % by a constant 0 is not folded (the program must still fault at run time); report it.Each assignment after optimisation, with the right-hand side printed as an S-expression: a constant or name as itself, (OP A B) for binary operators, (neg A) for unary minus. Append ; constant when the whole right-hand side folded to a constant. For a division by constant zero, print ; warning: division by zero instead.
Finish with folded=F propagated=P: F counts operator nodes replaced by constants, P counts variable uses replaced by constants.
Input:
cLoading…
Output:
cLoading…
In d, a - 20 becomes 20 - 20 and folds to 0; b * c can't fold because c is unknown.
Hidden tests cover comparisons, unary minus, negative results with / and %, a variable losing its constant value, and division by a constant zero.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it works