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 more→→Loop 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 Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Boolean Algebra and Fundamental Laws → Logic Gates Fundamentals → Implementing Boolean Functions with Gates → Karnaugh Map Simplification → Combinational Circuit Design → Flip-Flops and Latches → Finite State Machines (FSMs) → Deterministic Finite Automata (DFA) → Nondeterministic Finite Automata (NFA) → Two-Way Finite Automata → NFA to DFA Conversion (Subset Construction) → DFA Properties and Minimization Algorithms → Regular Languages: Definition and Characterization → Context-Free Grammars (CFGs) → Context-Free Grammar Properties and Ambiguity → Parse Trees, Derivations, and Ambiguity in CFGs → Context-Free Grammars in Compiler Design → Abstract Syntax Trees (ASTs) → Symbol Tables and Scope Resolution → Semantic Analysis Phase → Intermediate Code Representation → Control Flow Graphs → Fixpoint Computation and Iteration → Dataflow Analysis → Reaching Definitions Analysis → Common Subexpression Elimination (CSE) → Dead Code Elimination → Code Optimization Fundamentals → Vectorization and SIMD Code Generation → Loop Invariant Code Motion (LICM)

Longest path: 102 steps · 537 total prerequisite topics

Prerequisites (3)

Leads To (2)