3 ===========================================
4 LLVM Loop Terminology (and Canonical Forms)
5 ===========================================
13 Loops are an important concept for a code optimizer. In LLVM, detection
14 of loops in a control-flow graph is done by :ref:`loopinfo`. It is based
15 on the following definition.
17 A loop is a subset of nodes from the control-flow graph (CFG; where
18 nodes represent basic blocks) with the following properties:
20 1. The induced subgraph (which is the subgraph that contains all the
21 edges from the CFG within the loop) is strongly connected
22 (every node is reachable from all others).
24 2. All edges from outside the subset into the subset point to the same
25 node, called the **header**. As a consequence, the header dominates
26 all nodes in the loop (i.e. every execution path to any of the loop's
27 node will have to pass through the header).
29 3. The loop is the maximum subset with these properties. That is, no
30 additional nodes from the CFG can be added such that the induced
31 subgraph would still be strongly connected and the header would
34 In computer science literature, this is often called a *natural loop*.
35 In LLVM, a more generalized definition is called a
36 :ref:`cycle <cycle-terminology>`.
42 The definition of a loop comes with some additional terminology:
44 * An **entering block** (or **loop predecessor**) is a non-loop node
45 that has an edge into the loop (necessarily the header). If there is
46 only one entering block, and its only edge is to the
47 header, it is also called the loop's **preheader**. The preheader
48 dominates the loop without itself being part of the loop.
50 * A **latch** is a loop node that has an edge to the header.
52 * A **backedge** is an edge from a latch to the header.
54 * An **exiting edge** is an edge from inside the loop to a node outside
55 of the loop. The source of such an edge is called an **exiting block**, its
56 target is an **exit block**.
58 .. image:: ./loop-terminology.svg
65 This loop definition has some noteworthy consequences:
67 * A node can be the header of at most one loop. As such, a loop can be
68 identified by its header. Due to the header being the only entry into
69 a loop, it can be called a Single-Entry-Multiple-Exits (SEME) region.
72 * For basic blocks that are not reachable from the function's entry, the
73 concept of loops is undefined. This follows from the concept of
74 dominance being undefined as well.
77 * The smallest loop consists of a single basic block that branches to
78 itself. In this case that block is the header, latch (and exiting
79 block if it has another edge to a different block) at the same time.
80 A single block that has no branch to itself is not considered a loop,
81 even though it is trivially strongly connected.
83 .. image:: ./loop-single.svg
86 In this case, the role of header, exiting block and latch fall to the
87 same node. :ref:`loopinfo` reports this as:
89 .. code-block:: console
91 $ opt input.ll -passes='print<loops>'
92 Loop at depth 1 containing: %for.body<header><latch><exiting>
95 * Loops can be nested inside each other. That is, a loop's node set can
96 be a subset of another loop with a different loop header. The loop
97 hierarchy in a function forms a forest: Each top-level loop is the
98 root of the tree of the loops nested inside it.
100 .. image:: ./loop-nested.svg
104 * It is not possible that two loops share only a few of their nodes.
105 Two loops are either disjoint or one is nested inside the other. In
106 the example below the left and right subsets both violate the
107 maximality condition. Only the merge of both sets is considered a loop.
109 .. image:: ./loop-nonmaximal.svg
113 * It is also possible that two logical loops share a header, but are
114 considered a single loop by LLVM:
118 for (int i = 0; i < 128; ++i)
119 for (int j = 0; j < 128; ++j)
122 which might be represented in LLVM-IR as follows. Note that there is
123 only a single header and hence just a single loop.
125 .. image:: ./loop-merge.svg
128 The :ref:`LoopSimplify <loop-terminology-loop-simplify>` pass will
129 detect the loop and ensure separate headers for the outer and inner loop.
131 .. image:: ./loop-separate.svg
134 * A cycle in the CFG does not imply there is a loop. The example below
135 shows such a CFG, where there is no header node that dominates all
136 other nodes in the cycle. This is called **irreducible control-flow**.
138 .. image:: ./loop-irreducible.svg
141 The term reducible results from the ability to collapse the CFG into a
142 single node by successively replacing one of three base structures with
143 a single node: A sequential execution of basic blocks, acyclic conditional
144 branches (or switches), and a basic block looping on itself.
145 `Wikipedia <https://en.wikipedia.org/wiki/Control-flow_graph#Reducibility>`_
146 has a more formal definition, which basically says that every cycle has
150 * Irreducible control-flow can occur at any level of the loop nesting.
151 That is, a loop that itself does not contain any loops can still have
152 cyclic control flow in its body; a loop that is not nested inside
153 another loop can still be part of an outer cycle; and there can be
154 additional cycles between any two loops where one is contained in the other.
155 However, an LLVM :ref:`cycle<cycle-terminology>` covers both, loops and
156 irreducible control flow.
159 * The `FixIrreducible <https://llvm.org/doxygen/FixIrreducible_8h.html>`_
160 pass can transform irreducible control flow into loops by inserting
161 new loop headers. It is not included in any default optimization pass
162 pipeline, but is required for some back-end targets.
165 * Exiting edges are not the only way to break out of a loop. Other
166 possibilities are unreachable terminators, [[noreturn]] functions,
167 exceptions, signals, and your computer's power button.
170 * A basic block "inside" the loop that does not have a path back to the
171 loop (i.e. to a latch or header) is not considered part of the loop.
172 This is illustrated by the following code.
176 for (unsigned i = 0; i <= n; ++i) {
178 // When reaching this block, we will have exited the loop.
183 // abort(), never returns, so we have exited the loop.
187 // The unreachable allows the compiler to assume that this will not rejoin the loop.
189 __builtin_unreachable();
192 // This statically infinite loop is not nested because control-flow will not continue with the for-loop.
200 * There is no requirement for the control flow to eventually leave the
201 loop, i.e. a loop can be infinite. A **statically infinite loop** is a
202 loop that has no exiting edges. A **dynamically infinite loop** has
203 exiting edges, but it is possible to be never taken. This may happen
204 only under some circumstances, such as when n == UINT_MAX in the code
209 for (unsigned i = 0; i <= n; ++i)
212 It is possible for the optimizer to turn a dynamically infinite loop
213 into a statically infinite loop, for instance when it can prove that the
214 exiting condition is always false. Because the exiting edge is never
215 taken, the optimizer can change the conditional branch into an
218 If a is loop is annotated with
219 :ref:`llvm.loop.mustprogress <langref_llvm_loop_mustprogress>` metadata,
220 the compiler is allowed to assume that it will eventually terminate, even
221 if it cannot prove it. For instance, it may remove a mustprogress-loop
222 that does not have any side-effect in its body even though the program
223 could be stuck in that loop forever. Languages such as C and
224 `C++ <https://eel.is/c++draft/intro.progress#1>`_ have such
225 forward-progress guarantees for some loops. Also see the
226 :ref:`mustprogress <langref_mustprogress>` and
227 :ref:`willreturn <langref_willreturn>` function attributes, as well as
228 the older :ref:`llvm.sideeffect <llvm_sideeffect>` intrinsic.
230 * The number of executions of the loop header before leaving the loop is
231 the **loop trip count** (or **iteration count**). If the loop should
232 not be executed at all, a **loop guard** must skip the entire loop:
234 .. image:: ./loop-guard.svg
237 Since the first thing a loop header might do is to check whether there
238 is another execution and if not, immediately exit without doing any work
239 (also see :ref:`loop-terminology-loop-rotate`), loop trip count is not
240 the best measure of a loop's number of iterations. For instance, the
241 number of header executions of the code below for a non-positive n
242 (before loop rotation) is 1, even though the loop body is not executed
247 for (int i = 0; i < n; ++i)
250 A better measure is the **backedge-taken count**, which is the number of
251 times any of the backedges is taken before the loop. It is one less than
252 the trip count for executions that enter the header.
260 LoopInfo is the core analysis for obtaining information about loops.
261 There are few key implications of the definitions given above which
262 are important for working successfully with this interface.
264 * LoopInfo does not contain information about non-loop cycles. As a
265 result, it is not suitable for any algorithm which requires complete
266 cycle detection for correctness.
268 * LoopInfo provides an interface for enumerating all top level loops
269 (e.g. those not contained in any other loop). From there, you may
270 walk the tree of sub-loops rooted in that top level loop.
272 * Loops which become statically unreachable during optimization *must*
273 be removed from LoopInfo. If this can not be done for some reason,
274 then the optimization is *required* to preserve the static
275 reachability of the loop.
278 .. _loop-terminology-loop-simplify:
283 The Loop Simplify Form is a canonical form that makes
284 several analyses and transformations simpler and more effective.
285 It is ensured by the LoopSimplify
286 (:ref:`-loop-simplify <passes-loop-simplify>`) pass and is automatically
287 added by the pass managers when scheduling a LoopPass.
288 This pass is implemented in
289 `LoopSimplify.h <https://llvm.org/doxygen/LoopSimplify_8h_source.html>`_.
290 When it is successful, the loop has:
293 * A single backedge (which implies that there is a single latch).
294 * Dedicated exits. That is, no exit block for the loop
295 has a predecessor that is outside the loop. This implies
296 that all exit blocks are dominated by the loop header.
298 .. _loop-terminology-lcssa:
300 Loop Closed SSA (LCSSA)
301 =======================
303 A program is in Loop Closed SSA Form if it is in SSA form
304 and all values that are defined in a loop are used only inside
307 Programs written in LLVM IR are always in SSA form but not necessarily
308 in LCSSA. To achieve the latter, for each value that is live across the
309 loop boundary, single entry PHI nodes are inserted to each of the exit blocks
310 [#lcssa-construction]_ in order to "close" these values inside the loop.
311 In particular, consider the following loop:
321 X3 = phi(X1, X2); // X3 defined
324 ... = X3 + 4; // X3 used, i.e. live
327 In the inner loop, the X3 is defined inside the loop, but used
328 outside of it. In Loop Closed SSA form, this would be represented as follows:
344 This is still valid LLVM; the extra phi nodes are purely redundant,
345 but all LoopPass'es are required to preserve them.
346 This form is ensured by the LCSSA (:ref:`-lcssa <passes-lcssa>`)
347 pass and is added automatically by the LoopPassManager when
348 scheduling a LoopPass.
349 After the loop optimizations are done, these extra phi nodes
350 will be deleted by :ref:`-instcombine <passes-instcombine>`.
352 Note that an exit block is outside of a loop, so how can such a phi "close"
353 the value inside the loop since it uses it outside of it ? First of all,
355 `mentioned in the LangRef <https://llvm.org/docs/LangRef.html#id311>`_:
356 "the use of each incoming value is deemed to occur on the edge from the
357 corresponding predecessor block to the current block". Now, an
358 edge to an exit block is considered outside of the loop because
359 if we take that edge, it leads us clearly out of the loop.
361 However, an edge doesn't actually contain any IR, so in source code,
362 we have to choose a convention of whether the use happens in
363 the current block or in the respective predecessor. For LCSSA's purpose,
364 we consider the use happens in the latter (so as to consider the
365 use inside) [#point-of-use-phis]_.
367 The major benefit of LCSSA is that it makes many other loop optimizations
370 First of all, a simple observation is that if one needs to see all
371 the outside users, they can just iterate over all the (loop closing)
372 PHI nodes in the exit blocks (the alternative would be to
373 scan the def-use chain [#def-use-chain]_ of all instructions in the loop).
375 Then, consider for example
376 :ref:`simple-loop-unswitch <passes-simple-loop-unswitch>` ing the loop above.
377 Because it is in LCSSA form, we know that any value defined inside of
378 the loop will be used either only inside the loop or in a loop closing
379 PHI node. In this case, the only loop closing PHI node is X4.
380 This means that we can just copy the loop and change the X4
381 accordingly, like so:
405 Now, all uses of X4 will get the updated value (in general,
406 if a loop is in LCSSA form, in any loop transformation,
407 we only need to update the loop closing PHI nodes for the changes
408 to take effect). If we did not have Loop Closed SSA form, it means that X3 could
409 possibly be used outside the loop. So, we would have to introduce the
410 X4 (which is the new X3) and replace all uses of X3 with that.
411 However, we should note that because LLVM keeps a def-use chain
412 [#def-use-chain]_ for each Value, we wouldn't need
413 to perform data-flow analysis to find and replace all the uses
414 (there is even a utility function, replaceAllUsesWith(),
415 that performs this transformation by iterating the def-use chain).
417 Another important advantage is that the behavior of all uses
418 of an induction variable is the same. Without this, you need to
419 distinguish the case when the variable is used outside of
420 the loop it is defined in, for example:
424 for (i = 0; i < 100; i++) {
425 for (j = 0; j < 100; j++) {
432 Looking from the outer loop with the normal SSA form, the first use of k
433 is not well-behaved, while the second one is an induction variable with
434 base 100 and step 1. Although, in practice, and in the LLVM context,
435 such cases can be handled effectively by SCEV. Scalar Evolution
436 (:ref:`scalar-evolution <passes-scalar-evolution>`) or SCEV, is a
437 (analysis) pass that analyzes and categorizes the evolution of scalar
438 expressions in loops.
440 In general, it's easier to use SCEV in loops that are in LCSSA form.
441 The evolution of a scalar (loop-variant) expression that
442 SCEV can analyze is, by definition, relative to a loop.
443 An expression is represented in LLVM by an
444 `llvm::Instruction <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`_.
445 If the expression is inside two (or more) loops (which can only
446 happen if the loops are nested, like in the example above) and you want
447 to get an analysis of its evolution (from SCEV),
448 you have to also specify relative to what Loop you want it.
449 Specifically, you have to use
450 `getSCEVAtScope() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a21d6ee82eed29080d911dbb548a8bb68>`_.
452 However, if all loops are in LCSSA form, each expression is actually
453 represented by two different llvm::Instructions. One inside the loop
454 and one outside, which is the loop-closing PHI node and represents
455 the value of the expression after the last iteration (effectively,
456 we break each loop-variant expression into two expressions and so, every
457 expression is at most in one loop). You can now just use
458 `getSCEV() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a30bd18ac905eacf3601bc6a553a9ff49>`_.
459 and which of these two llvm::Instructions you pass to it disambiguates
460 the context / scope / relative loop.
462 .. rubric:: Footnotes
464 .. [#lcssa-construction] To insert these loop-closing PHI nodes, one has to
465 (re-)compute dominance frontiers (if the loop has multiple exits).
467 .. [#point-of-use-phis] Considering the point of use of a PHI entry value
468 to be in the respective predecessor is a convention across the whole LLVM.
469 The reason is mostly practical; for example it preserves the dominance
470 property of SSA. It is also just an overapproximation of the actual
471 number of uses; the incoming block could branch to another block in which
472 case the value is not actually used but there are no side-effects (it might
473 increase its live range which is not relevant in LCSSA though).
474 Furthermore, we can gain some intuition if we consider liveness:
475 A PHI is *usually* inserted in the current block because the value can't
476 be used from this point and onwards (i.e. the current block is a dominance
477 frontier). It doesn't make sense to consider that the value is used in
478 the current block (because of the PHI) since the value stops being live
479 before the PHI. In some sense the PHI definition just "replaces" the original
480 value definition and doesn't actually use it. It should be stressed that
481 this analogy is only used as an example and does not pose any strict
482 requirements. For example, the value might dominate the current block
483 but we can still insert a PHI (as we do with LCSSA PHI nodes) *and*
484 use the original value afterwards (in which case the two live ranges overlap,
485 although in LCSSA (the whole point is that) we never do that).
488 .. [#def-use-chain] A property of SSA is that there exists a def-use chain
489 for each definition, which is a list of all the uses of this definition.
490 LLVM implements this property by keeping a list of all the uses of a Value
491 in an internal data structure.
493 "More Canonical" Loops
494 ======================
496 .. _loop-terminology-loop-rotate:
501 Loops are rotated by the LoopRotate (:ref:`loop-rotate <passes-loop-rotate>`)
502 pass, which converts loops into do/while style loops and is
504 `LoopRotation.h <https://llvm.org/doxygen/LoopRotation_8h_source.html>`_. Example:
509 for (int i = 0; i < n; i += 1)
525 **Warning**: This transformation is valid only if the compiler
526 can prove that the loop body will be executed at least once. Otherwise,
527 it has to insert a guard which will test it at runtime. In the example
528 above, that would be:
542 It's important to understand the effect of loop rotation
543 at the LLVM IR level. We follow with the previous examples
544 in LLVM IR while also providing a graphical representation
545 of the control-flow graphs (CFG). You can get the same graphical
546 results by utilizing the :ref:`view-cfg <passes-view-cfg>` pass.
548 The initial **for** loop could be translated to:
552 define void @test(i32 %n) {
557 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
558 %cond = icmp slt i32 %i, %n
559 br i1 %cond, label %body, label %exit
566 %i.next = add nsw i32 %i, 1
573 .. image:: ./loop-terminology-initial-loop.png
576 Before we explain how LoopRotate will actually
577 transform this loop, here's how we could convert
578 it (by hand) to a do-while style loop.
582 define void @test(i32 %n) {
587 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
592 %i.next = add nsw i32 %i, 1
593 %cond = icmp slt i32 %i.next, %n
594 br i1 %cond, label %body, label %exit
600 .. image:: ./loop-terminology-rotated-loop.png
605 * The condition check was moved to the "bottom" of the loop, i.e.
606 the latch. This is something that LoopRotate does by copying the header
607 of the loop to the latch.
608 * The compiler in this case can't deduce that the loop will
609 definitely execute at least once so the above transformation
610 is not valid. As mentioned above, a guard has to be inserted,
611 which is something that LoopRotate will do.
613 This is how LoopRotate transforms this loop:
617 define void @test(i32 %n) {
619 %guard_cond = icmp slt i32 0, %n
620 br i1 %guard_cond, label %loop.preheader, label %exit
626 %i2 = phi i32 [ 0, %loop.preheader ], [ %i.next, %latch ]
630 %i.next = add nsw i32 %i2, 1
631 %cond = icmp slt i32 %i.next, %n
632 br i1 %cond, label %body, label %loop.exit
641 .. image:: ./loop-terminology-guarded-loop.png
644 The result is a little bit more complicated than we may expect
645 because LoopRotate ensures that the loop is in
646 :ref:`Loop Simplify Form <loop-terminology-loop-simplify>`
648 In this case, it inserted the %loop.preheader basic block so
649 that the loop has a preheader and it introduced the %loop.exit
650 basic block so that the loop has dedicated exits
651 (otherwise, %exit would be jumped from both %latch and %entry,
652 but %entry is not contained in the loop).
653 Note that a loop has to be in Loop Simplify Form beforehand
654 too for LoopRotate to be applied successfully.
656 The main advantage of this form is that it allows hoisting
657 invariant instructions, especially loads, into the preheader.
658 That could be done in non-rotated loops as well but with
659 some disadvantages. Let's illustrate them with an example:
663 for (int i = 0; i < n; ++i) {
668 We assume that loading from p is invariant and use(v) is some
669 statement that uses v.
670 If we wanted to execute the load only once we could move it
671 "out" of the loop body, resulting in this:
676 for (int i = 0; i < n; ++i) {
680 However, now, in the case that n <= 0, in the initial form,
681 the loop body would never execute, and so, the load would
682 never execute. This is a problem mainly for semantic reasons.
683 Consider the case in which n <= 0 and loading from p is invalid.
684 In the initial program there would be no error. However, with this
685 transformation we would introduce one, effectively breaking
686 the initial semantics.
688 To avoid both of these problems, we can insert a guard:
692 if (n > 0) { // loop guard
694 for (int i = 0; i < n; ++i) {
699 This is certainly better but it could be improved slightly. Notice
700 that the check for whether n is bigger than 0 is executed twice (and
701 n does not change in between). Once when we check the guard condition
702 and once in the first execution of the loop. To avoid that, we could
703 do an unconditional first execution and insert the loop condition
704 in the end. This effectively means transforming the loop into a do-while loop:
716 Note that LoopRotate does not generally do such
717 hoisting. Rather, it is an enabling transformation for other
718 passes like Loop-Invariant Code Motion (:ref:`-licm <passes-licm>`).