1.. _loop-terminology: 2 3=========================================== 4LLVM Loop Terminology (and Canonical Forms) 5=========================================== 6 7.. contents:: 8 :local: 9 10Introduction 11============ 12 13Loops are a core concept in any optimizer. This page spells out some 14of the common terminology used within LLVM code to describe loop 15structures. 16 17First, let's start with the basics. In LLVM, a Loop is a maximal set of basic 18blocks that form a strongly connected component (SCC) in the Control 19Flow Graph (CFG) where there exists a dedicated entry/header block that 20dominates all other blocks within the loop. Thus, without leaving the 21loop, one can reach every block in the loop from the header block and 22the header block from every block in the loop. 23 24Note that there are some important implications of this definition: 25 26* Not all SCCs are loops. There exist SCCs that do not meet the 27 dominance requirement and such are not considered loops. 28 29* Loops can contain non-loop SCCs and non-loop SCCs may contain 30 loops. Loops may also contain sub-loops. 31 32* A header block is uniquely associated with one loop. There can be 33 multiple SCC within that loop, but the strongly connected component 34 (SCC) formed from their union must always be unique. 35 36* Given the use of dominance in the definition, all loops are 37 statically reachable from the entry of the function. 38 39* Every loop must have a header block, and some set of predecessors 40 outside the loop. A loop is allowed to be statically infinite, so 41 there need not be any exiting edges. 42 43* Any two loops are either fully disjoint (no intersecting blocks), or 44 one must be a sub-loop of the other. 45 46* Loops in a function form a forest. One implication of this fact 47 is that a loop either has no parent or a single parent. 48 49A loop may have an arbitrary number of exits, both explicit (via 50control flow) and implicit (via throwing calls which transfer control 51out of the containing function). There is no special requirement on 52the form or structure of exit blocks (the block outside the loop which 53is branched to). They may have multiple predecessors, phis, etc... 54 55Key Terminology 56=============== 57 58Header Block - The basic block which dominates all other blocks 59contained within the loop. As such, it is the first one executed if 60the loop executes at all. Note that a block can be the header of 61two separate loops at the same time, but only if one is a sub-loop 62of the other. 63 64Exiting Block - A basic block contained within a given loop which has 65at least one successor outside of the loop and one successor inside the 66loop. (The latter is a consequence of the block being contained within 67an SCC which is part of the loop.) That is, it has a successor which 68is an Exit Block. 69 70Exit Block - A basic block outside of the associated loop which has a 71predecessor inside the loop. That is, it has a predecessor which is 72an Exiting Block. 73 74Latch Block - A basic block within the loop whose successors include 75the header block of the loop. Thus, a latch is a source of backedge. 76A loop may have multiple latch blocks. A latch block may be either 77conditional or unconditional. 78 79Backedge(s) - The edge(s) in the CFG from latch blocks to the header 80block. Note that there can be multiple such edges, and even multiple 81such edges leaving a single latch block. 82 83Loop Predecessor - The predecessor blocks of the loop header which 84are not contained by the loop itself. These are the only blocks 85through which execution can enter the loop. When used in the 86singular form implies that there is only one such unique block. 87 88Preheader Block - A preheader is a (singular) loop predecessor which 89ends in an unconditional transfer of control to the loop header. Note 90that not all loops have such blocks. 91 92Backedge Taken Count - The number of times the backedge will execute 93before some interesting event happens. Commonly used without 94qualification of the event as a shorthand for when some exiting block 95branches to some exit block. May be zero, or not statically computable. 96 97Iteration Count - The number of times the header will execute before 98some interesting event happens. Commonly used without qualification to 99refer to the iteration count at which the loop exits. Will always be 100one greater than the backedge taken count. *Warning*: Preceding 101statement is true in the *integer domain*; if you're dealing with fixed 102width integers (such as LLVM Values or SCEVs), you need to be cautious 103of overflow when converting one to the other. 104 105It's important to note that the same basic block can play multiple 106roles in the same loop, or in different loops at once. For example, a 107single block can be the header for two nested loops at once, while 108also being an exiting block for the inner one only, and an exit block 109for a sibling loop. Example: 110 111.. code-block:: C 112 113 while (..) { 114 for (..) {} 115 do { 116 do { 117 // <-- block of interest 118 if (exit) break; 119 } while (..); 120 } while (..) 121 } 122 123LoopInfo 124======== 125 126LoopInfo is the core analysis for obtaining information about loops. 127There are few key implications of the definitions given above which 128are important for working successfully with this interface. 129 130* LoopInfo does not contain information about non-loop cycles. As a 131 result, it is not suitable for any algorithm which requires complete 132 cycle detection for correctness. 133 134* LoopInfo provides an interface for enumerating all top level loops 135 (e.g. those not contained in any other loop). From there, you may 136 walk the tree of sub-loops rooted in that top level loop. 137 138* Loops which become statically unreachable during optimization *must* 139 be removed from LoopInfo. If this can not be done for some reason, 140 then the optimization is *required* to preserve the static 141 reachability of the loop. 142 143 144.. _loop-terminology-loop-simplify: 145 146Loop Simplify Form 147================== 148 149The Loop Simplify Form is a canonical form that makes 150several analyses and transformations simpler and more effective. 151It is ensured by the LoopSimplify 152(:ref:`-loop-simplify <passes-loop-simplify>`) pass and is automatically 153added by the pass managers when scheduling a LoopPass. 154This pass is implemented in 155`LoopSimplify.h <https://llvm.org/doxygen/LoopSimplify_8h_source.html>`_. 156When it is successful, the loop has: 157 158* A preheader. 159* A single backedge (which implies that there is a single latch). 160* Dedicated exits. That is, no exit block for the loop 161 has a predecessor that is outside the loop. This implies 162 that all exit blocks are dominated by the loop header. 163 164 165Loop Closed SSA (LCSSA) 166======================= 167 168TBD 169 170"More Canonical" Loops 171====================== 172 173.. _loop-terminology-loop-rotate: 174 175Rotated Loops 176------------- 177 178Loops are rotated by the LoopRotate (:ref:`loop-rotate <passes-loop-rotate>`) 179pass, which converts loops into do/while style loops and is 180implemented in 181`LoopRotation.h <https://llvm.org/doxygen/LoopRotation_8h_source.html>`_. Example: 182 183.. code-block:: C 184 185 void test(int n) { 186 for (int i = 0; i < n; i += 1) 187 // Loop body 188 } 189 190is transformed to: 191 192.. code-block:: C 193 194 void test(int n) { 195 int i = 0; 196 do { 197 // Loop body 198 i += 1; 199 } while (i < n); 200 } 201 202**Warning**: This transformation is valid only if the compiler 203can prove that the loop body will be executed at least once. Otherwise, 204it has to insert a guard which will test it at runtime. In the example 205above, that would be: 206 207.. code-block:: C 208 209 void test(int n) { 210 int i = 0; 211 if (n > 0) { 212 do { 213 // Loop body 214 i += 1; 215 } while (i < n); 216 } 217 } 218 219It's important to understand the effect of loop rotation 220at the LLVM IR level. We follow with the previous examples 221in LLVM IR while also providing a graphical representation 222of the control-flow graphs (CFG). You can get the same graphical 223results by utilizing the :ref:`view-cfg <passes-view-cfg>` pass. 224 225The initial **for** loop could be translated to: 226 227.. code-block:: none 228 229 define void @test(i32 %n) { 230 entry: 231 br label %for.header 232 233 for.header: 234 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ] 235 %cond = icmp slt i32 %i, %n 236 br i1 %cond, label %body, label %exit 237 238 body: 239 ; Loop body 240 br label %latch 241 242 latch: 243 %i.next = add nsw i32 %i, 1 244 br label %for.header 245 246 exit: 247 ret void 248 } 249 250.. image:: ./loop-terminology-initial-loop.png 251 :width: 400 px 252 253Before we explain how LoopRotate will actually 254transform this loop, here's how we could convert 255it (by hand) to a do-while style loop. 256 257.. code-block:: none 258 259 define void @test(i32 %n) { 260 entry: 261 br label %body 262 263 body: 264 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ] 265 ; Loop body 266 br label %latch 267 268 latch: 269 %i.next = add nsw i32 %i, 1 270 %cond = icmp slt i32 %i.next, %n 271 br i1 %cond, label %body, label %exit 272 273 exit: 274 ret void 275 } 276 277.. image:: ./loop-terminology-rotated-loop.png 278 :width: 400 px 279 280Note two things: 281 282* The condition check was moved to the "bottom" of the loop, i.e. 283 the latch. This is something that LoopRotate does by copying the header 284 of the loop to the latch. 285* The compiler in this case can't deduce that the loop will 286 definitely execute at least once so the above transformation 287 is not valid. As mentioned above, a guard has to be inserted, 288 which is something that LoopRotate will do. 289 290This is how LoopRotate transforms this loop: 291 292.. code-block:: none 293 294 define void @test(i32 %n) { 295 entry: 296 %guard_cond = icmp slt i32 0, %n 297 br i1 %guard_cond, label %loop.preheader, label %exit 298 299 loop.preheader: 300 br label %body 301 302 body: 303 %i2 = phi i32 [ 0, %loop.preheader ], [ %i.next, %latch ] 304 br label %latch 305 306 latch: 307 %i.next = add nsw i32 %i2, 1 308 %cond = icmp slt i32 %i.next, %n 309 br i1 %cond, label %body, label %loop.exit 310 311 loop.exit: 312 br label %exit 313 314 exit: 315 ret void 316 } 317 318.. image:: ./loop-terminology-guarded-loop.png 319 :width: 500 px 320 321The result is a little bit more complicated than we may expect 322because LoopRotate ensures that the loop is in 323:ref:`Loop Simplify Form <loop-terminology-loop-simplify>` 324after rotation. 325In this case, it inserted the %loop.preheader basic block so 326that the loop has a preheader and it introduced the %loop.exit 327basic block so that the loop has dedicated exits 328(otherwise, %exit would be jumped from both %latch and %entry, 329but %entry is not contained in the loop). 330Note that a loop has to be in Loop Simplify Form beforehand 331too for LoopRotate to be applied successfully. 332 333The main advantage of this form is that it allows hoisting 334invariant instructions, especially loads, into the preheader. 335That could be done in non-rotated loops as well but with 336some disadvantages. Let's illustrate them with an example: 337 338.. code-block:: C 339 340 for (int i = 0; i < n; ++i) { 341 auto v = *p; 342 use(v); 343 } 344 345We assume that loading from p is invariant and use(v) is some 346statement that uses v. 347If we wanted to execute the load only once we could move it 348"out" of the loop body, resulting in this: 349 350.. code-block:: C 351 352 auto v = *p; 353 for (int i = 0; i < n; ++i) { 354 use(v); 355 } 356 357However, now, in the case that n <= 0, in the initial form, 358the loop body would never execute, and so, the load would 359never execute. This is a problem mainly for semantic reasons. 360Consider the case in which n <= 0 and loading from p is invalid. 361In the initial program there would be no error. However, with this 362transformation we would introduce one, effectively breaking 363the initial semantics. 364 365To avoid both of these problems, we can insert a guard: 366 367.. code-block:: C 368 369 if (n > 0) { // loop guard 370 auto v = *p; 371 for (int i = 0; i < n; ++i) { 372 use(v); 373 } 374 } 375 376This is certainly better but it could be improved slightly. Notice 377that the check for whether n is bigger than 0 is executed twice (and 378n does not change in between). Once when we check the guard condition 379and once in the first execution of the loop. To avoid that, we could 380do an unconditional first execution and insert the loop condition 381in the end. This effectively means transforming the loop into a do-while loop: 382 383.. code-block:: C 384 385 if (0 < n) { 386 auto v = *p; 387 do { 388 use(v); 389 ++i; 390 } while (i < n); 391 } 392 393Note that LoopRotate does not generally do such 394hoisting. Rather, it is an enabling transformation for other 395passes like Loop-Invariant Code Motion (:ref:`-licm <passes-licm>`). 396