Techniqueintro
Loop-invariant code motion
Also called LICM, hoisting.
Moves computations whose operands do not change inside a loop to a preheader before the loop, when this is safe.
Loop-invariant code motion takes an instruction inside a loop whose operands have the same values on every iteration, and computes it once before the loop. The new home is the preheader: a block that runs once each time the loop is entered, just before the loop header. The rewrite needs four facts. The operands are not written inside the loop. The destination is written only by this instruction in the loop. The destination is not read in the loop, or after it, before this instruction writes it. And the instruction cannot trap, or it runs on every path where the moved copy runs. The last fact is the one that is easy to forget: moving a division out of a loop that may run zero times adds a trap.
In plain words
If a loop computes the same thing on every turn, the compiler can compute it once before the loop starts and keep the answer. This saves work each time around the loop. But the move must not change what the program does. The computed value must really be the same on every turn, and nobody may need the old value of the variable it goes into. Also, the loop might not run at all, or the line might sit behind a test inside the loop. Then the program did not compute it before, and computing it now can crash the program, for example by dividing by zero.
When it applies
Take a natural loop with header . Its blocks are and the blocks that reach a back edge into without passing .
The preheader. A preheader of is a block outside whose only successor is , and which is the only predecessor of outside . Every entry into the loop passes through , and runs exactly once per entry. If has no such block, create one: a new block p: jump h, and redirect every edge into from outside to . This changes only the number of jumps executed.
Fix an instruction : x = e in a block of , where is a constant, a copy, or an operation a op b. Loads, calls, alloc and stores are not candidates here; see the variations for loads. is loop invariant if each operand is a constant or a name with no definition in , or, by the same test applied again, a name whose only reaching definition is an invariant instruction of that is moved first. may be moved to the end of when these conditions hold in the current program:
- (C1) Invariant operands. Each operand of is a constant, or a name that no instruction of defines and that is not address-taken. An address-taken name can change through a store or a call without being named.
- (C2) One definition. is the only instruction of that defines , and is not address-taken.
- (C3) No earlier read. is not live at the start of , in the sense of live variable analysis: no path from reads before it writes . This rules out a read of in the loop that sees the value from before the loop or from the previous iteration, and a read after the loop on a path that skipped .
- (C4) No new trap. cannot trap: it is not
/or%by a divisor that may be zero, and not a shift by a count that may be outside 0 to 63.
(C1) is what the reaching definitions test of the textbooks checks: all definitions of the operand that reach are outside . The textbook form of (C3) is two conditions: every use of in is reached only by , and dominates every exit of after which is live. Together these say that is not live at .
The template
The rewrite. Find the loops, from the innermost out, and give each a preheader. For one loop, mark the invariant instructions until no new one is found, in the order they are found. Then, in that order, move each marked instruction that meets (C1) to (C4) from its block to the end of the preheader, before its jump. An instruction moved out of an inner loop lands in the inner preheader, which is a block of the outer loop, so it is a candidate again when the outer loop is processed.
Legality. (C1) to (C4) are checked on the program as it is after the earlier moves. (C1) uses reaching definitions or a scan of the loop for definitions, (C3) uses liveness, a may property with union at joins, and (C4) is a fact about the operation and its operands.
Profit. The cost model is the number of instructions executed. A moved instruction runs once per entry of the loop instead of once per execution of . This pays when runs at least once per entry, the usual case. It costs one extra instruction per entry when the loop runs zero times or when is skipped, for example behind a test in the loop. A second cost is register pressure: the moved value stays live through the whole loop. In a loop that already uses all registers, this can cause spills that cost more than the instruction saved.
Proof that behavior stays the same. Let be the program with the preheader , and let be with moved from to the end of . Fix an input. The two programs have the same blocks, with the same instructions except , and the same terminators. Run them side by side, block by block, and keep this invariant at each matched point : the memory is the same, every name other than has the same value, and either has the same value or is not live at in .
- Outside the loop and , both programs run the same instructions. An instruction that reads needs live before it, so agrees there. All other operands agree. So the instruction writes the same value or traps in both, a call gets the same arguments and memory and returns the same result, and a definition of makes agree. A terminator reads a live name, so both take the same branch or return the same value.
- At , also sets to , the value of at that moment, and does not trap by (C4). Afterward all names other than still agree, and is not live at by (C3). So the invariant holds at .
- Inside one visit of the loop, from until the run leaves : no instruction of writes an operand of , by (C1), so every execution of in computes again. In no instruction of writes , by (C2), and no store or call can write it, since it is not address-taken, so stays all through the visit. Now take a point in the visit. If has run in this visit, is in both. If not, the run of went from to with no write to , and if were live at , that path followed by a path to a read would show that is live at , against (C3). So the invariant holds at every point in the visit. Every instruction other than behaves the same in both programs by the argument of case 1, and in cannot trap and leaves equal to in both.
- When the run leaves , the invariant holds at that point, and case 1 takes over. Each new entry of the loop passes through again.
So the two runs take the same branches, trap at the same instruction, return the same value, or both run forever. The only difference is the instruction count: runs once per arrival at , and once per execution of . When several instructions move, apply the argument once per move, in the order of the rewrite. Each move is checked against the program left by the moves before it.
Classic examples
An invariant product. The parameters are a, b and n. The block entry is the only way into the loop and ends with jump h, so it is already a preheader.
entry:
i = 0
s = 0
jump h
h:
c = i < n
br c body done
body:
t = a * b
u = t + i
s = s + u
i = i + 1
jump h
done:
ret s
a and b are parameters with no definition in the loop, t has one definition in the loop, t is read only after it, and a product cannot trap. So t = a * b moves to entry, before jump h. u = t + i reads i, which the loop changes, so it stays. For , , both programs return 21, in 27 steps before and 25 after. For the loop body never runs, and the new program takes 7 steps instead of 6.
A division that adds a trap. Replace the body by q = a / b; s = s + q; i = i + 1; jump h. The division is invariant, but it may trap. For and the old program returns 0: the body never runs. With q = a / b in the preheader, the new program traps. For and both trap. (C4) forbids the move. The usual fix is to rotate the loop first, see the variations: under a test that , the body runs at least once, and the division can move there.
A read before the write. In body: s = s + x; x = a * b; ..., the operands of x = a * b are invariant, but the first iteration reads x before the loop writes it, and sees the value from before the loop. So x is live at h, and (C3) forbids the move. If it moved, the first iteration would read instead.
Two definitions. If the loop holds x = a * b in one branch and x = a + b in the other, both are invariant in their operands, but neither may move: after the move, the loop would see one value of x where it saw two. (C2) catches this.
Variations
- On SSA form. In static single assignment form, every name has one definition, which dominates all its uses. Then (C2) and (C3) always hold, and an instruction is invariant when each operand is defined outside the loop or by an invariant instruction. Only (C1) and (C4) are left to check.
- Loop rotation. A loop
while c do bodybecomesif c then (do body while c). The new guarded block before the loop is a preheader that runs only if the body runs at least once. An instruction at the start of the body, before any store, call or other trap, can then move to this preheader even if it may trap: it would have run right after the preheader anyway, with the same operands. - Invariant loads. A load
x = *ris invariant ifris invariant and no store or call in the loop may write the cell thatrpoints to. Proving this needs alias analysis and mod-ref analysis of the calls. A load may also fault on a real machine, so the same care as for (C4) applies. - Scalar promotion. If a loop reads and writes one memory cell through an invariant pointer and nothing else touches it, the compiler loads the cell into a name in the preheader, uses the name in the loop, and stores it back at each exit.
- Partial redundancy elimination. Partial redundancy elimination treats an invariant expression as redundant on the back edge and inserts it at the preheader. Lazy code motion does this only where the expression is very busy, that is, computed on every path from that point, so it never adds a computation, and never a trap, to a path that lacked one. This subsumes most loop-invariant code motion, but it does not move a computation out of a loop that may run zero times unless the loop is rotated first.
- Sinking. The opposite move takes an instruction whose result is used only after the loop and puts it at the loop exits, so it runs once instead of on each iteration.
Pitfalls
- Adding a trap. A division, a remainder, a shift, or a load in a loop that may run zero times, or behind a test in the loop, did not run on every path. Moving it to the preheader can trap where the old program did not.
- Loops that run zero times. Even without traps, a moved instruction runs once on entry to a loop whose body never runs. This is one wasted instruction, not a wrong result, but it can matter in an outer loop that runs many times.
- Register pressure. Each moved value stays live through the whole loop. Many moved values can force spills inside the loop, which costs more than the work saved.
- Memory changed by the loop. A load is not invariant just because its pointer is: a store in the loop through another pointer, or a call, may change the cell. A load from memory that another thread writes, such as
while (!flag), must not move out of the loop, or the loop waits forever. Such accesses must be atomic or volatile, which the compiler never moves. - Calls. A call with invariant arguments is not invariant unless the function is known to be pure, to end, and to never trap.
- Values live into the loop. A name defined in the loop but read at the top of the loop before that definition holds the previous value on each iteration. Moving its definition changes the first read.
Exercises
- In the first example, why may
u = t + inot move, even aftert = a * bhas moved? Answer. It readsi, whichi = i + 1defines in the loop, so (C1) fails. - A loop body holds
t = a * band thenw = t * 2. Aftert = a * bmoves, mayw = t * 2move too? Answer. Yes.tno longer has a definition in the loop,whas one definition, a product cannot trap, and ifwis read only after it is written, (C3) holds. It moves to the preheader aftert = a * b. - Give a loop in which
q = a / 4may move butq = a / bmay not. Answer. Any loop that may run zero times, withaandbnot defined in it. Division by the constant 4 cannot trap, so (C4) holds for it. Division bybcan trap whenb = 0, so the move would add a trap on the run where the loop body never runs. - Why is it not enough, for (C3), that dominates every loop exit? Answer. A read of in the loop before , on the first iteration, still sees the value from before the loop. (C3) rules out this read and the reads after exits that skip in one condition.
- On SSA form, why do (C2) and (C3) hold? Answer. Each name has one definition, so (C2) holds. That definition dominates every use. A path from to a use that misses the definition, preceded by a path from the entry to that does not enter before , would be a path from the entry to the use that misses it, against dominance.
References
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.1.7 (Code Motion), Section 9.5 (Partial-Redundancy Elimination) and Section 9.6 (Loops in Flow Graphs)
- Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Section 13.2 (Loop-Invariant Code Motion), the marking of invariant instructions and the conditions for moving them to the preheader
- Etienne Morel and Claude Renvoise, Global optimization by suppression of partial redundancies, Communications of the ACM 22(2), 1979, 96-103, the treatment of loop-invariant computations as partial redundancies, moved to the entrance of the outermost loop in which they are invariant
- Frances E. Allen, Control flow analysis, ACM SIGPLAN Notices 5(7), 1970, 1-19, loops as strongly connected regions found with dominators, and the use of this structure to place code outside loops
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag T991RF Edit this page History Report an error Markdown