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

Loop Invariant Code Motion (LICM)

Graduate Depth 101 in the knowledge graph I know this Set as goal
4topics build on this
537prerequisites beneath it
See this on the map →
Code Optimization FundamentalsControl Flow Graphs+1 moreLoop Detection and AnalysisLoop Unrolling
optimization loop-optimization code-motion

Core Idea

Loop invariant code motion hoists expressions that do not depend on loop iterations outside the loop. If an expression's operands are not modified in the loop, it computes the same value in each iteration and can be moved before the loop. This reduces redundant computation. Safety requires ensuring the expression is always executed before the loop's first iteration.

Explainer

From your work on code optimization, you know that compilers look for redundant or unnecessary computation and try to eliminate it. Loops are the highest-priority target because any wasted work inside a loop is multiplied by the iteration count. Loop invariant code motion (LICM) identifies computations inside a loop whose results never change across iterations and moves them to a point just before the loop begins, so they execute exactly once instead of thousands or millions of times.

An expression is loop invariant if all of its operands are either constants or are defined outside the loop. For example, in a loop that computes `a[i] = x * y + i`, the subexpression `x * y` is invariant if neither `x` nor `y` is modified inside the loop. The compiler can hoist `t = x * y` to the loop's preheader — a block that executes exactly once before the loop entry — and replace the original expression with `a[i] = t + i`. The control flow graph you studied makes this analysis precise: the compiler inspects definitions within the loop's strongly connected component and checks whether any definition of an operand reaches the expression from inside the loop.

The subtlety lies in safety. Hoisting is only safe if the expression would have executed on every iteration anyway. If the expression sits inside a conditional branch within the loop (`if (condition) { t = x * y; }`), moving it to the preheader means it now executes even when the condition is false. This can cause problems if the expression has side effects or can fault — for instance, a division that might divide by zero. The compiler must prove that the expression dominates all loop exits (meaning every path through the loop passes through it) or that the expression is free of observable side effects before performing the hoist.

LICM often works in concert with other optimizations. Strength reduction might turn a loop-variant multiplication into an addition, and then LICM can hoist the initialization of that addition's base value. Conversely, LICM can expose new opportunities for common subexpression elimination outside the loop. This cascading effect is why compilers run optimization passes in carefully ordered sequences — each pass creates 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)Dead Code EliminationCode Optimization FundamentalsVectorization and SIMD Code GenerationLoop Invariant Code Motion (LICM)

Longest path: 102 steps · 537 total prerequisite topics

Prerequisites (3)

Leads To (2)