1.. _loop-terminology: 2 3=========================================== 4LLVM Loop Terminology (and Canonical Forms) 5=========================================== 6 7.. contents:: 8 :local: 9 10Loop Definition 11=============== 12 13Loops are an important concept for a code optimizer. In LLVM, detection 14of loops in a control-flow graph is done by :ref:`loopinfo`. It is based 15on the following definition. 16 17A loop is a subset of nodes from the control-flow graph (CFG; where 18nodes represent basic blocks) with the following properties: 19 201. 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). 23 242. 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). 28 293. 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 32 remain the same. 33 34In computer science literature, this is often called a *natural loop*. 35In LLVM, this is the only definition of a loop. 36 37 38Terminology 39----------- 40 41The definition of a loop comes with some additional terminology: 42 43* An **entering block** (or **loop predecessor**) is a non-loop node 44 that has an edge into the loop (necessarily the header). If there is 45 only one entering block entering block, and its only edge is to the 46 header, it is also called the loop's **preheader**. The preheader 47 dominates the loop without itself being part of the loop. 48 49* A **latch** is a loop node that has an edge to the header. 50 51* A **backedge** is an edge from a latch to the header. 52 53* An **exiting edge** is an edge from inside the loop to a node outside 54 of the loop. The source of such an edge is called an **exiting block**, its 55 target is an **exit block**. 56 57.. image:: ./loop-terminology.svg 58 :width: 400 px 59 60 61Important Notes 62--------------- 63 64This loop definition has some noteworthy consequences: 65 66* A node can be the header of at most one loop. As such, a loop can be 67 identified by its header. Due to the header being the only entry into 68 a loop, it can be called a Single-Entry-Multiple-Exits (SEME) region. 69 70 71* For basic blocks that are not reachable from the function's entry, the 72 concept of loops is undefined. This follows from the concept of 73 dominance being undefined as well. 74 75 76* The smallest loop consists of a single basic block that branches to 77 itself. In this case that block is the header, latch (and exiting 78 block if it has another edge to a different block) at the same time. 79 A single block that has no branch to itself is not considered a loop, 80 even though it is trivially strongly connected. 81 82.. image:: ./loop-single.svg 83 :width: 300 px 84 85In this case, the role of header, exiting block and latch fall to the 86same node. :ref:`loopinfo` reports this as: 87 88.. code-block:: console 89 90 $ opt input.ll -loops -analyze 91 Loop at depth 1 containing: %for.body<header><latch><exiting> 92 93 94* Loops can be nested inside each other. That is, a loop's node set can 95 be a subset of another loop with a different loop header. The loop 96 hierarchy in a function forms a forest: Each top-level loop is the 97 root of the tree of the loops nested inside it. 98 99.. image:: ./loop-nested.svg 100 :width: 350 px 101 102 103* It is not possible that two loops share only a few of their nodes. 104 Two loops are either disjoint or one is nested inside the other. In 105 the example below the left and right subsets both violate the 106 maximality condition. Only the merge of both sets is considered a loop. 107 108.. image:: ./loop-nonmaximal.svg 109 :width: 250 px 110 111 112* It is also possible that two logical loops share a header, but are 113 considered a single loop by LLVM: 114 115.. code-block:: C 116 117 for (int i = 0; i < 128; ++i) 118 for (int j = 0; j < 128; ++j) 119 body(i,j); 120 121which might be represented in LLVM-IR as follows. Note that there is 122only a single header and hence just a single loop. 123 124.. image:: ./loop-merge.svg 125 :width: 400 px 126 127The :ref:`LoopSimplify <loop-terminology-loop-simplify>` pass will 128detect the loop and ensure separate headers for the outer and inner loop. 129 130.. image:: ./loop-separate.svg 131 :width: 400 px 132 133* A cycle in the CFG does not imply there is a loop. The example below 134 shows such a CFG, where there is no header node that dominates all 135 other nodes in the cycle. This is called **irreducible control-flow**. 136 137.. image:: ./loop-irreducible.svg 138 :width: 150 px 139 140The term reducible results from the ability to collapse the CFG into a 141single node by successively replacing one of three base structures with 142a single node: A sequential execution of basic blocks, a conditional 143branching (or switch) with re-joining, and a basic block looping on itself. 144`Wikipedia <https://en.wikipedia.org/wiki/Control-flow_graph#Reducibility>`_ 145has a more formal definition, which basically says that every cycle has 146a dominating header. 147 148 149* Irreducible control-flow can occur at any level of the loop nesting. 150 That is, a loop that itself does not contain any loops can still have 151 cyclic control flow in its body; a loop that is not nested inside 152 another loop can still be part of an outer cycle; and there can be 153 additional cycles between any two loops where one is contained in the other. 154 155 156* Exiting edges are not the only way to break out of a loop. Other 157 possibilities are unreachable terminators, [[noreturn]] functions, 158 exceptions, signals, and your computer's power button. 159 160 161* A basic block "inside" the loop that does not have a path back to the 162 loop (i.e. to a latch or header) is not considered part of the loop. 163 This is illustrated by the following code. 164 165.. code-block:: C 166 167 for (unsigned i = 0; i <= n; ++i) { 168 if (c1) { 169 // When reaching this block, we will have exited the loop. 170 do_something(); 171 break; 172 } 173 if (c2) { 174 // abort(), never returns, so we have exited the loop. 175 abort(); 176 } 177 if (c3) { 178 // The unreachable allows the compiler to assume that this will not rejoin the loop. 179 do_something(); 180 __builtin_unreachable(); 181 } 182 if (c4) { 183 // This statically infinite loop is not nested because control-flow will not continue with the for-loop. 184 while(true) { 185 do_something(); 186 } 187 } 188 } 189 190 191* There is no requirement for the control flow to eventually leave the 192 loop, i.e. a loop can be infinite. A **statically infinite loop** is a 193 loop that has no exiting edges. A **dynamically infinite loop** has 194 exiting edges, but it is possible to be never taken. This may happen 195 only under some circumstances, such as when n == UINT_MAX in the code 196 below. 197 198.. code-block:: C 199 200 for (unsigned i = 0; i <= n; ++i) 201 body(i); 202 203It is possible for the optimizer to turn a dynamically infinite loop 204into a statically infinite loop, for instance when it can prove that the 205exiting condition is always false. Because the exiting edge is never 206taken, the optimizer can change the conditional branch into an 207unconditional one. 208 209Note that under some circumstances the compiler may assume that a loop will 210eventually terminate without proving it. For instance, it may remove a loop 211that does not do anything in its body. If the loop was infinite, this 212optimization resulted in an "infinite" performance speed-up. A call 213to the intrinsic :ref:`llvm.sideeffect<llvm_sideeffect>` can be added 214into the loop to ensure that the optimizer does not make this assumption 215without proof. 216 217 218* The number of executions of the loop header before leaving the loop is 219 the **loop trip count** (or **iteration count**). If the loop should 220 not be executed at all, a **loop guard** must skip the entire loop: 221 222.. image:: ./loop-guard.svg 223 :width: 500 px 224 225Since the first thing a loop header might do is to check whether there 226is another execution and if not, immediately exit without doing any work 227(also see :ref:`loop-terminology-loop-rotate`), loop trip count is not 228the best measure of a loop's number of iterations. For instance, the 229number of header executions of the code below for a non-positive n 230(before loop rotation) is 1, even though the loop body is not executed 231at all. 232 233.. code-block:: C 234 235 for (int i = 0; i < n; ++i) 236 body(i); 237 238A better measure is the **backedge-taken count**, which is the number of 239times any of the backedges is taken before the loop. It is one less than 240the trip count for executions that enter the header. 241 242 243.. _loopinfo: 244 245LoopInfo 246======== 247 248LoopInfo is the core analysis for obtaining information about loops. 249There are few key implications of the definitions given above which 250are important for working successfully with this interface. 251 252* LoopInfo does not contain information about non-loop cycles. As a 253 result, it is not suitable for any algorithm which requires complete 254 cycle detection for correctness. 255 256* LoopInfo provides an interface for enumerating all top level loops 257 (e.g. those not contained in any other loop). From there, you may 258 walk the tree of sub-loops rooted in that top level loop. 259 260* Loops which become statically unreachable during optimization *must* 261 be removed from LoopInfo. If this can not be done for some reason, 262 then the optimization is *required* to preserve the static 263 reachability of the loop. 264 265 266.. _loop-terminology-loop-simplify: 267 268Loop Simplify Form 269================== 270 271The Loop Simplify Form is a canonical form that makes 272several analyses and transformations simpler and more effective. 273It is ensured by the LoopSimplify 274(:ref:`-loop-simplify <passes-loop-simplify>`) pass and is automatically 275added by the pass managers when scheduling a LoopPass. 276This pass is implemented in 277`LoopSimplify.h <https://llvm.org/doxygen/LoopSimplify_8h_source.html>`_. 278When it is successful, the loop has: 279 280* A preheader. 281* A single backedge (which implies that there is a single latch). 282* Dedicated exits. That is, no exit block for the loop 283 has a predecessor that is outside the loop. This implies 284 that all exit blocks are dominated by the loop header. 285 286.. _loop-terminology-lcssa: 287 288Loop Closed SSA (LCSSA) 289======================= 290 291A program is in Loop Closed SSA Form if it is in SSA form 292and all values that are defined in a loop are used only inside 293this loop. 294Programs written in LLVM IR are always in SSA form but not necessarily 295in LCSSA. To achieve the latter, single entry PHI nodes are inserted 296at the end of the loops for all values that are live 297across the loop boundary [#lcssa-construction]_. 298In particular, consider the following loop: 299 300.. code-block:: C 301 302 c = ...; 303 for (...) { 304 if (c) 305 X1 = ... 306 else 307 X2 = ... 308 X3 = phi(X1, X2); // X3 defined 309 } 310 311 ... = X3 + 4; // X3 used, i.e. live 312 // outside the loop 313 314In the inner loop, the X3 is defined inside the loop, but used 315outside of it. In Loop Closed SSA form, this would be represented as follows: 316 317.. code-block:: C 318 319 c = ...; 320 for (...) { 321 if (c) 322 X1 = ... 323 else 324 X2 = ... 325 X3 = phi(X1, X2); 326 } 327 X4 = phi(X3); 328 329 ... = X4 + 4; 330 331This is still valid LLVM; the extra phi nodes are purely redundant, 332but all LoopPass'es are required to preserve them. 333This form is ensured by the LCSSA (:ref:`-lcssa <passes-lcssa>`) 334pass and is added automatically by the LoopPassManager when 335scheduling a LoopPass. 336After the loop optimizations are done, these extra phi nodes 337will be deleted by :ref:`-instcombine <passes-instcombine>`. 338 339The major benefit of this transformation is that it makes many other 340loop optimizations simpler. 341 342First of all, a simple observation is that if one needs to see all 343the outside users, they can just iterate over all the (loop closing) 344PHI nodes in the exit blocks (the alternative would be to 345scan the def-use chain [#def-use-chain]_ of all instructions in the loop). 346 347Then, consider for example 348:ref:`-loop-unswitch <passes-loop-unswitch>` ing the loop above. 349Because it is in LCSSA form, we know that any value defined inside of 350the loop will be used either only inside the loop or in a loop closing 351PHI node. In this case, the only loop closing PHI node is X4. 352This means that we can just copy the loop and change the X4 353accordingly, like so: 354 355.. code-block:: C 356 357 c = ...; 358 if (c) { 359 for (...) { 360 if (true) 361 X1 = ... 362 else 363 X2 = ... 364 X3 = phi(X1, X2); 365 } 366 } else { 367 for (...) { 368 if (false) 369 X1' = ... 370 else 371 X2' = ... 372 X3' = phi(X1', X2'); 373 } 374 } 375 X4 = phi(X3, X3') 376 377Now, all uses of X4 will get the updated value (in general, 378if a loop is in LCSSA form, in any loop transformation, 379we only need to update the loop closing PHI nodes for the changes 380to take effect). If we did not have Loop Closed SSA form, it means that X3 could 381possibly be used outside the loop. So, we would have to introduce the 382X4 (which is the new X3) and replace all uses of X3 with that. 383However, we should note that because LLVM keeps a def-use chain 384[#def-use-chain]_ for each Value, we wouldn't need 385to perform data-flow analysis to find and replace all the uses 386(there is even a utility function, replaceAllUsesWith(), 387that performs this transformation by iterating the def-use chain). 388 389Another important advantage is that the behavior of all uses 390of an induction variable is the same. Without this, you need to 391distinguish the case when the variable is used outside of 392the loop it is defined in, for example: 393 394.. code-block:: C 395 396 for (i = 0; i < 100; i++) { 397 for (j = 0; j < 100; j++) { 398 k = i + j; 399 use(k); // use 1 400 } 401 use(k); // use 2 402 } 403 404Looking from the outer loop with the normal SSA form, the first use of k 405is not well-behaved, while the second one is an induction variable with 406base 100 and step 1. Although, in practice, and in the LLVM context, 407such cases can be handled effectively by SCEV. Scalar Evolution 408(:ref:`scalar-evolution <passes-scalar-evolution>`) or SCEV, is a 409(analysis) pass that analyzes and categorizes the evolution of scalar 410expressions in loops. 411 412In general, it's easier to use SCEV in loops that are in LCSSA form. 413The evolution of a scalar (loop-variant) expression that 414SCEV can analyze is, by definition, relative to a loop. 415An expression is represented in LLVM by an 416`llvm::Instruction <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`_. 417If the expression is inside two (or more) loops (which can only 418happen if the loops are nested, like in the example above) and you want 419to get an analysis of its evolution (from SCEV), 420you have to also specify relative to what Loop you want it. 421Specifically, you have to use 422`getSCEVAtScope() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a21d6ee82eed29080d911dbb548a8bb68>`_. 423 424However, if all loops are in LCSSA form, each expression is actually 425represented by two different llvm::Instructions. One inside the loop 426and one outside, which is the loop-closing PHI node and represents 427the value of the expression after the last iteration (effectively, 428we break each loop-variant expression into two expressions and so, every 429expression is at most in one loop). You can now just use 430`getSCEV() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a30bd18ac905eacf3601bc6a553a9ff49>`_. 431and which of these two llvm::Instructions you pass to it disambiguates 432the context / scope / relative loop. 433 434.. rubric:: Footnotes 435 436.. [#lcssa-construction] To insert these loop-closing PHI nodes, one has to 437 (re-)compute dominance frontiers (if the loop has multiple exits). 438 439.. [#def-use-chain] A property of SSA is that there exists a def-use chain 440 for each definition, which is a list of all the uses of this definition. 441 LLVM implements this property by keeping a list of all the uses of a Value 442 in an internal data structure. 443 444"More Canonical" Loops 445====================== 446 447.. _loop-terminology-loop-rotate: 448 449Rotated Loops 450------------- 451 452Loops are rotated by the LoopRotate (:ref:`loop-rotate <passes-loop-rotate>`) 453pass, which converts loops into do/while style loops and is 454implemented in 455`LoopRotation.h <https://llvm.org/doxygen/LoopRotation_8h_source.html>`_. Example: 456 457.. code-block:: C 458 459 void test(int n) { 460 for (int i = 0; i < n; i += 1) 461 // Loop body 462 } 463 464is transformed to: 465 466.. code-block:: C 467 468 void test(int n) { 469 int i = 0; 470 do { 471 // Loop body 472 i += 1; 473 } while (i < n); 474 } 475 476**Warning**: This transformation is valid only if the compiler 477can prove that the loop body will be executed at least once. Otherwise, 478it has to insert a guard which will test it at runtime. In the example 479above, that would be: 480 481.. code-block:: C 482 483 void test(int n) { 484 int i = 0; 485 if (n > 0) { 486 do { 487 // Loop body 488 i += 1; 489 } while (i < n); 490 } 491 } 492 493It's important to understand the effect of loop rotation 494at the LLVM IR level. We follow with the previous examples 495in LLVM IR while also providing a graphical representation 496of the control-flow graphs (CFG). You can get the same graphical 497results by utilizing the :ref:`view-cfg <passes-view-cfg>` pass. 498 499The initial **for** loop could be translated to: 500 501.. code-block:: none 502 503 define void @test(i32 %n) { 504 entry: 505 br label %for.header 506 507 for.header: 508 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ] 509 %cond = icmp slt i32 %i, %n 510 br i1 %cond, label %body, label %exit 511 512 body: 513 ; Loop body 514 br label %latch 515 516 latch: 517 %i.next = add nsw i32 %i, 1 518 br label %for.header 519 520 exit: 521 ret void 522 } 523 524.. image:: ./loop-terminology-initial-loop.png 525 :width: 400 px 526 527Before we explain how LoopRotate will actually 528transform this loop, here's how we could convert 529it (by hand) to a do-while style loop. 530 531.. code-block:: none 532 533 define void @test(i32 %n) { 534 entry: 535 br label %body 536 537 body: 538 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ] 539 ; Loop body 540 br label %latch 541 542 latch: 543 %i.next = add nsw i32 %i, 1 544 %cond = icmp slt i32 %i.next, %n 545 br i1 %cond, label %body, label %exit 546 547 exit: 548 ret void 549 } 550 551.. image:: ./loop-terminology-rotated-loop.png 552 :width: 400 px 553 554Note two things: 555 556* The condition check was moved to the "bottom" of the loop, i.e. 557 the latch. This is something that LoopRotate does by copying the header 558 of the loop to the latch. 559* The compiler in this case can't deduce that the loop will 560 definitely execute at least once so the above transformation 561 is not valid. As mentioned above, a guard has to be inserted, 562 which is something that LoopRotate will do. 563 564This is how LoopRotate transforms this loop: 565 566.. code-block:: none 567 568 define void @test(i32 %n) { 569 entry: 570 %guard_cond = icmp slt i32 0, %n 571 br i1 %guard_cond, label %loop.preheader, label %exit 572 573 loop.preheader: 574 br label %body 575 576 body: 577 %i2 = phi i32 [ 0, %loop.preheader ], [ %i.next, %latch ] 578 br label %latch 579 580 latch: 581 %i.next = add nsw i32 %i2, 1 582 %cond = icmp slt i32 %i.next, %n 583 br i1 %cond, label %body, label %loop.exit 584 585 loop.exit: 586 br label %exit 587 588 exit: 589 ret void 590 } 591 592.. image:: ./loop-terminology-guarded-loop.png 593 :width: 500 px 594 595The result is a little bit more complicated than we may expect 596because LoopRotate ensures that the loop is in 597:ref:`Loop Simplify Form <loop-terminology-loop-simplify>` 598after rotation. 599In this case, it inserted the %loop.preheader basic block so 600that the loop has a preheader and it introduced the %loop.exit 601basic block so that the loop has dedicated exits 602(otherwise, %exit would be jumped from both %latch and %entry, 603but %entry is not contained in the loop). 604Note that a loop has to be in Loop Simplify Form beforehand 605too for LoopRotate to be applied successfully. 606 607The main advantage of this form is that it allows hoisting 608invariant instructions, especially loads, into the preheader. 609That could be done in non-rotated loops as well but with 610some disadvantages. Let's illustrate them with an example: 611 612.. code-block:: C 613 614 for (int i = 0; i < n; ++i) { 615 auto v = *p; 616 use(v); 617 } 618 619We assume that loading from p is invariant and use(v) is some 620statement that uses v. 621If we wanted to execute the load only once we could move it 622"out" of the loop body, resulting in this: 623 624.. code-block:: C 625 626 auto v = *p; 627 for (int i = 0; i < n; ++i) { 628 use(v); 629 } 630 631However, now, in the case that n <= 0, in the initial form, 632the loop body would never execute, and so, the load would 633never execute. This is a problem mainly for semantic reasons. 634Consider the case in which n <= 0 and loading from p is invalid. 635In the initial program there would be no error. However, with this 636transformation we would introduce one, effectively breaking 637the initial semantics. 638 639To avoid both of these problems, we can insert a guard: 640 641.. code-block:: C 642 643 if (n > 0) { // loop guard 644 auto v = *p; 645 for (int i = 0; i < n; ++i) { 646 use(v); 647 } 648 } 649 650This is certainly better but it could be improved slightly. Notice 651that the check for whether n is bigger than 0 is executed twice (and 652n does not change in between). Once when we check the guard condition 653and once in the first execution of the loop. To avoid that, we could 654do an unconditional first execution and insert the loop condition 655in the end. This effectively means transforming the loop into a do-while loop: 656 657.. code-block:: C 658 659 if (0 < n) { 660 auto v = *p; 661 do { 662 use(v); 663 ++i; 664 } while (i < n); 665 } 666 667Note that LoopRotate does not generally do such 668hoisting. Rather, it is an enabling transformation for other 669passes like Loop-Invariant Code Motion (:ref:`-licm <passes-licm>`). 670