Machine-independent optimisations
Machine-independent optimisations are compiler transformations done on an intermediate representation to reduce work, improve locality or reduce resource use without depending on the target machine.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Compilers perform machine-independent optimisations to make programs faster, smaller or use fewer registers before target-specific code generation. Engineers use these optimisations in the compiler back-end (on the intermediate representation) and when assessing whether a change in high-level code will be optimised away.
Key ideas
Start with definitions (I define each bold term before using it).
- Optimisation (compiler): a program transformation that preserves the observable behaviour of the source program (under the assumed semantics) while improving some metric (time, code size, energy, etc.).
- Machine-independent optimisation: an optimisation that is applied to an intermediate representation (IR) and does not depend on specific hardware features (e.g., instruction set or pipeline). Examples: constant folding, common subexpression elimination, dead-code elimination, loop-invariant code motion.
- Intermediate representation (IR): a program form between front end and back end; typical forms are three-address code and Static Single Assignment (SSA).
- Control Flow Graph (CFG): a directed graph whose nodes are basic blocks and edges represent possible flow of control.
- Basic block: a sequence of instructions with one entry and one exit.
- Data-flow problem: a problem where information (properties) flows along the CFG edges; formulated by equations for IN and OUT sets for each node and solved to a fixed point.
- Lattice: a partially ordered set with a meet (greatest lower bound). In classical bitvector data-flow analyses we typically use the powerset lattice; with subset order, meet is intersection and join is union. For must-analyses we take intersection across predecessors; for may-analyses we take union across predecessors (equivalently, order the lattice by superset so that union is the meet).
- Monotone framework: a data-flow framework where transfer functions are monotone on the lattice; monotonicity ensures that iterative solution reaches a fixed point.
Important machine-independent optimisations and their conditions
- Constant folding: replace an operation with a constant when operands are constants (applies locally in a basic block). Requires that the operation is pure (no side effect) and the constant values fit the semantics (e.g., integer overflow behaviour must be considered).
- Constant propagation: propagate known constant values through the program using a data-flow analysis that maps variables to constants or to ⊥ (unreachable/no information yet) or ⊤ (non-constant/unknown). Must consider control flow: propagate a constant to a use only when all reaching paths agree on the same constant (the lattice meet yields that constant; otherwise the value becomes ⊤); SSA form can carry conditional information more precisely.
- Common subexpression elimination (CSE): if expression E is computed earlier and its operands have not changed, reuse the previous value instead of recomputing. Requires reaching-definitions/available-expressions analysis to prove safety.
- Copy propagation: replace uses of a variable that is a direct copy of another (x = y) by the source y where safe.
- Algebraic simplification and strength reduction: replace expensive ops by cheaper ones (e.g., replace multiplication by 2 with addition or shift) provided semantics preserved (watch integer overflow and floating-point rounding differences).
- Dead-code elimination (DCE): remove computations whose results are not used in any observable effect (non-live). Requires liveness analysis and care with side effects (I/O, volatile memory, exceptions).
- Loop-invariant code motion (hoisting): move computations out of a loop if their value does not change across iterations and moving does not change semantics (e.g., no dependency on loop-carried values, no side effects). Preheader blocks are often created to hold hoisted code.
- Induction variable simplification: transform and combine induction variables to reduce arithmetic inside loops (e.g., strength reduction of index updates).
- Peephole optimisations (small instruction-window): technically machine-dependent often, but some peephole-like local rewrites on IR are machine-independent (e.g., remove x = x + 0).
Data-flow formulation (general method)
- For each basic block B we compute IN[B] and OUT[B] sets.
- A typical forward may-analysis: OUT[B] = f_B(IN[B]) and IN[B] = meet_{p in preds(B)} OUT[p]. For backward analyses the equations reverse.
- Choose lattice, direction, transfer functions f_B, and a confluence operator: intersection for must-analyses, union for may-analyses (or choose the lattice order so this operator is the meet). Use iterative worklist until no set changes (fixed point).
Precise example problems students must know (statements used in exams):
- Available expressions (a forward, must-analysis): An expression e is available at point p if on every path to p, e has been computed and none of its operands was subsequently redefined. Meet = intersection. Useful for CSE.
- Reaching definitions (forward, may-analysis): A definition d of variable x reaches point p if there exists a path from d to p with no intervening redefinition of x. Meet = union. Useful for copy propagation and some DCE.
- Live variables (backward, may-analysis): A variable v is live at point p if its value may be used along some path from p before being redefined. Meet = union. Useful for DCE and register allocation.
Soundness and safety: All transformations must preserve observable behaviour under the language semantics assumptions used by the compiler. Some optimisations are only safe under additional guarantees (e.g., no integer overflow wrap-around) or when program has no undefined behaviour.
What to draw in diagrams (explain exactly):
- For CFG-based problems, draw nodes as labeled boxes (B1, B2, ...) and directed edges for control flow. Inside each box list statements in order. For available expressions, annotate each edge/box with IN and OUT sets. For loop-invariant motion, draw the loop header, loop body block, back edge, and preheader block placed before the header.
Formulas
OUT[B] = f_B(IN[B]) — OUT of basic block B is result of transfer function f_B applied to IN[B]. Symbols: B = basic block, f_B = transfer function, IN/OUT sets are sets of facts. Applies in iterative data-flow solves.
IN[B] = meet_{p in preds(B)} OUT[p] — IN is the confluence over OUT of predecessors. preds(B) = predecessor blocks. With subset order, use intersection for must-analyses and union for may-analyses (equivalently, pick a superset order so that this confluence is the meet).
Available(B)_OUT = (Available(B)_IN − Kill(B)) ∪ Gen(B) — standard gen/kill transfer for available expressions. Kill(B) = expressions that mention any variable redefined in B; Gen(B) = expressions computed in B that are not subsequently killed within B (i.e., their operands are not redefined later in B).
Reaching(B)_OUT = Gen(B) ∪ (Reaching(B)_IN − Kill(B)) — reaching definitions transfer.
Live(B)_IN = Use(B) ∪ (Live(B)_OUT − Def(B)); Live(B)_OUT = ⋃_{s in succ(B)} Live(s)_IN — liveness equations. Symbols: Use(B) = variables used before defined in B; Def(B) = variables defined in B; succ(B) = successors.
Syntax to remember for IR (three-address code examples):
t1 = a + b (binary operation)
t2 = t1 * 4
if t2 < c goto L (conditional jump)
x = y (copy)
call f, n (call with n args) — treat calls as possible side effects unless interprocedural analysis proves otherwise.
Worked examples
Example 1 — Constant folding and propagation (three-address code)
Given code: 1: a = 3 2: b = 4 3: c = a + b 4: d = c * 2 5: e = d + b 6: print(e)
Step-by-step:
- At 1 and 2 we know a=3, b=4 (constants).
- At 3: c = a + b ⇒ c = 3 + 4 ⇒ c = 7 (constant folding). Replace line 3 with
c = 7. - At 4: d = c * 2 ⇒ d = 7 * 2 ⇒ d = 14. Replace line 4 with
d = 14. - At 5: e = d + b ⇒ e = 14 + 4 ⇒ e = 18. Replace line 5 with
e = 18. - Final code: 1: a = 3 2: b = 4 3: c = 7 4: d = 14 5: e = 18 6: print(18)
Result: final print argument is constant; compiler may further simplify by removing unused variables. This example assumes no overflow and pure arithmetic.
Example 2 — Available expressions analysis (small CFG)
CFG nodes and statements: B1: t1 = a + b goto B2 B2: if c goto B3 else B4 B3: t2 = a + b goto B5 B4: a = 5 goto B5 B5: x = a + b
We want to know whether expression a + b is available at start of B5.
- Compute Gen and Kill per block: Gen(B1) = {a+b}, Kill(B1) = {}. Gen(B3) = {a+b}, Kill(B3) = {}. Gen(B4) = {}, Kill(B4) = {a+b} because B4 assigns to a.
- IN[B1] = ∅ (entry). OUT[B1] = {a+b}.
- IN[B2] = OUT[B1] = {a+b}. OUT[B2] = IN[B2] (no computations) = {a+b}.
- IN[B3] = OUT[B2] = {a+b}; OUT[B3] = {a+b}.
- IN[B4] = OUT[B2] = {a+b}; OUT[B4] = (IN − Kill) ∪ Gen = ({a+b} − {a+b}) ∪ {} = ∅.
- IN[B5] = OUT[B3] ∩ OUT[B4] = {a+b} ∩ ∅ = ∅. So
a+bis NOT available at B5 start because along one path (through B4) it was killed.
This trace demonstrates use of intersection (must-analysis) and the need to consider all paths.
Example 3 — Loop-invariant code motion
Loop body (pseudocode): for i = 0 to n-1: t = a + b x[i] = t * i
Assume a and b are not changed in the loop and i changes.
t = a + bis loop-invariant because it depends only on a and b which are not modified in the loop.- Create a preheader block before the loop header and move
t = a + binto the preheader. - Inside loop replace
t = a + bby use oftcomputed once.
Transformed code: preheader: t = a + b loop: x[i] = t * i
This reduces repeated addition and is safe because moving does not change values and there are no side effects.
Common mistakes
- Assuming optimisations always improve runtime; sometimes code size or cache behaviour may worsen performance.
- Ignoring language-defined undefined behaviour (e.g., signed integer overflow): some optimisations are only valid if UB is allowed to be exploited.
- Applying CSE across assignments that could alias (pointer writes) without alias analysis.
- Not creating a loop preheader when performing loop-invariant motion; forgetting to handle exceptional control flow.
For your exam
Types of questions you will get:
- Definitions and short notes: define available expressions, reaching definitions, liveness, SSA.
- Derivations: derive IN/OUT equations for a given analysis and explain why meet is union/intersection.
- Algorithm trace: given a CFG and statements, perform reaching definitions, available expressions or liveness analysis to fixed point and show IN/OUT sets.
- Program-transform questions: show safe transformations (e.g., hoist invariant code), or explain why transformation is unsafe.
- Small implementation-style: give pseudocode of worklist algorithm for data-flow analysis.
What a full-marks answer includes:
- Clear statement of the kind of analysis (may/must, forward/backward).
- Lattice, direction, meet operator, Gen/Kill definitions for each block.
- Iterative equations IN/OUT and clear initial conditions.
- Correct iterative trace or final solution and justification for correctness and termination (mention monotonicity and finite-height lattice).
- For transformations: pre- and post- code, proof of safety (why behaviour preserved), and notes on side-effects/aliases.
Quick check
- Is available expressions analysis a may-analysis or a must-analysis?
- Which meet operator (union or intersection) is used for liveness analysis?
- Why must you be careful moving code out of a loop if it includes a function call?
Answers: 1) Must-analysis (intersection). 2) Union (liveness is a may-analysis). 3) Function calls may have side effects or throw exceptions; moving them could change program behaviour unless proven pure.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?