Every time you write a loop, you implicitly ask: how many times must this work be done? Sometimes the answer is obvious — counting array elements clearly requires visiting each one. But sometimes a computation inside the loop does not change from one iteration to the next. Its inputs are the same, so its output is the same, every single time.
Loop-Invariant Code Motion (LICM) is the compiler technique that spots those computations and hoists them above the loop — so they run exactly once, before the first iteration, instead of once per iteration.
A computation is loop-invariant if every variable it reads is either a constant or is defined outside the loop and never modified inside it. The value of such an expression is identical on every trip around the loop. Executing it repeatedly is pure waste.
The idea sounds obvious, yet the details matter enormously. The compiler must guarantee that moving the computation is safe: it must not change program behavior, must not introduce a division by zero that would have been avoided, and must not run code on a path where it never would have reached. Those correctness conditions — combined with the performance pay-off — make LICM one of the most studied transformations in compiler theory.
Comments
Loading comments...