A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Common Subexpression Elimination (CSE)

Graduate Depth 97 in the knowledge graph I know this Set as goal
12topics build on this
509prerequisites beneath it
See this on the map →
Dataflow AnalysisReaching Definitions AnalysisDead Code EliminationValue Numbering and Redundancy Elimination
optimization cse expression-reuse

Core Idea

Common subexpression elimination detects and removes redundant computations. If the same expression is computed multiple times with unchanged operands, compute it once and reuse the result. CSE requires tracking when expressions are available (all operands have definitions reaching the current point) and when they are not killed (operands not reassigned).

Explainer

Consider this fragment of intermediate code: `t1 = a + b; t2 = a + b;`. If neither `a` nor `b` is modified between the two statements, then `t2` will always equal `t1`. Computing `a + b` a second time is pure waste — the compiler can replace the second computation with `t2 = t1`. This is the essence of common subexpression elimination (CSE): find expressions that have already been computed with unchanged operands, and reuse the earlier result instead of recomputing.

The challenge is determining *when* an expression is safe to reuse. From your study of dataflow analysis and reaching definitions, you have the machinery to answer this. An expression `a + b` is available at a program point if every path from the start of the program to that point computes `a + b`, and neither `a` nor `b` is redefined after the most recent computation. If any path redefines an operand without recomputing the expression, the earlier value may be stale and cannot be reused. The compiler solves this with available expressions analysis, a forward dataflow problem: the gen set at each statement includes expressions it computes, the kill set includes all expressions containing variables it redefines, and the meet operation at join points takes the intersection (an expression is only available if it is available on *all* incoming paths).

There are two scopes of CSE. Local CSE operates within a single basic block — a straight-line sequence of instructions with no branches. This is simple because there is only one path, so you just scan forward, maintaining a table of computed expressions and replacing duplicates. Global CSE operates across an entire function's control flow graph, handling branches and loops. Global CSE requires the full available expressions dataflow analysis, which propagates information across basic block boundaries. The result is more powerful: it can catch redundancies across branches, in loop bodies, and between distant parts of the function.

CSE interacts productively with other optimizations. Copy propagation can expose new common subexpressions by replacing variable copies with their originals, making previously different-looking expressions identical. Constant folding can simplify operands, again revealing matches. In loops, CSE often works hand-in-hand with loop-invariant code motion: an expression computed inside a loop whose operands never change across iterations is both a common subexpression and loop-invariant, and can be hoisted out of the loop entirely. The compiler's optimization pipeline typically runs these passes in sequence, with each pass creating opportunities for the next.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesComparison Operators and Boolean TestsLogical Operators and Boolean AlgebraBoolean Algebra and Fundamental LawsLogic Gates FundamentalsImplementing Boolean Functions with GatesKarnaugh Map SimplificationCombinational Circuit DesignFlip-Flops and LatchesFinite State Machines (FSMs)Deterministic Finite Automata (DFA)Nondeterministic Finite Automata (NFA)Two-Way Finite AutomataNFA to DFA Conversion (Subset Construction)DFA Properties and Minimization AlgorithmsRegular Languages: Definition and CharacterizationContext-Free Grammars (CFGs)Context-Free Grammar Properties and AmbiguityParse Trees, Derivations, and Ambiguity in CFGsContext-Free Grammars in Compiler DesignAbstract Syntax Trees (ASTs)Symbol Tables and Scope ResolutionSemantic Analysis PhaseIntermediate Code RepresentationControl Flow GraphsFixpoint Computation and IterationDataflow AnalysisReaching Definitions AnalysisCommon Subexpression Elimination (CSE)

Longest path: 98 steps · 509 total prerequisite topics

Prerequisites (2)

Leads To (2)