LLVM 22.0.0git
LoopUnrollRuntime.cpp
Go to the documentation of this file.
1//===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements some loop unrolling utilities for loops with run-time
10// trip counts. See LoopUnroll.cpp for unrolling loops with compile-time
11// trip counts.
12//
13// The functions in this file are used to generate extra code when the
14// run-time trip count modulo the unroll factor is not 0. When this is the
15// case, we need to generate code to execute these 'left over' iterations.
16//
17// The current strategy generates an if-then-else sequence prior to the
18// unrolled loop to execute the 'left over' iterations before or after the
19// unrolled loop.
20//
21//===----------------------------------------------------------------------===//
22
23#include "llvm/ADT/Statistic.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
35#include "llvm/Support/Debug.h"
43
44using namespace llvm;
45
46#define DEBUG_TYPE "loop-unroll"
47
48STATISTIC(NumRuntimeUnrolled,
49 "Number of loops unrolled with run-time trip counts");
51 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
52 cl::desc("Allow runtime unrolling for loops with multiple exits, when "
53 "epilog is generated"));
55 "unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden,
56 cl::desc("Assume the non latch exit block to be predictable"));
57
58// Probability that the loop trip count is so small that after the prolog
59// we do not enter the unrolled loop at all.
60// It is unlikely that the loop trip count is smaller than the unroll factor;
61// other than that, the choice of constant is not tuned yet.
62static const uint32_t UnrolledLoopHeaderWeights[] = {1, 127};
63// Probability that the loop trip count is so small that we skip the unrolled
64// loop completely and immediately enter the epilogue loop.
65// It is unlikely that the loop trip count is smaller than the unroll factor;
66// other than that, the choice of constant is not tuned yet.
67static const uint32_t EpilogHeaderWeights[] = {1, 127};
68
69/// Connect the unrolling prolog code to the original loop.
70/// The unrolling prolog code contains code to execute the
71/// 'extra' iterations if the run-time trip count modulo the
72/// unroll count is non-zero.
73///
74/// This function performs the following:
75/// - Create PHI nodes at prolog end block to combine values
76/// that exit the prolog code and jump around the prolog.
77/// - Add a PHI operand to a PHI node at the loop exit block
78/// for values that exit the prolog and go around the loop.
79/// - Branch around the original loop if the trip count is less
80/// than the unroll factor.
81///
82static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
83 BasicBlock *PrologExit,
84 BasicBlock *OriginalLoopLatchExit,
85 BasicBlock *PreHeader, BasicBlock *NewPreHeader,
87 LoopInfo *LI, bool PreserveLCSSA,
88 ScalarEvolution &SE) {
89 // Loop structure should be the following:
90 // Preheader
91 // PrologHeader
92 // ...
93 // PrologLatch
94 // PrologExit
95 // NewPreheader
96 // Header
97 // ...
98 // Latch
99 // LatchExit
100 BasicBlock *Latch = L->getLoopLatch();
101 assert(Latch && "Loop must have a latch");
102 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
103
104 // Create a PHI node for each outgoing value from the original loop
105 // (which means it is an outgoing value from the prolog code too).
106 // The new PHI node is inserted in the prolog end basic block.
107 // The new PHI node value is added as an operand of a PHI node in either
108 // the loop header or the loop exit block.
109 for (BasicBlock *Succ : successors(Latch)) {
110 for (PHINode &PN : Succ->phis()) {
111 // Add a new PHI node to the prolog end block and add the
112 // appropriate incoming values.
113 // TODO: This code assumes that the PrologExit (or the LatchExit block for
114 // prolog loop) contains only one predecessor from the loop, i.e. the
115 // PrologLatch. When supporting multiple-exiting block loops, we can have
116 // two or more blocks that have the LatchExit as the target in the
117 // original loop.
118 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr");
119 NewPN->insertBefore(PrologExit->getFirstNonPHIIt());
120 // Adding a value to the new PHI node from the original loop preheader.
121 // This is the value that skips all the prolog code.
122 if (L->contains(&PN)) {
123 // Succ is loop header.
124 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
125 PreHeader);
126 } else {
127 // Succ is LatchExit.
128 NewPN->addIncoming(PoisonValue::get(PN.getType()), PreHeader);
129 }
130
131 Value *V = PN.getIncomingValueForBlock(Latch);
133 if (L->contains(I)) {
134 V = VMap.lookup(I);
135 }
136 }
137 // Adding a value to the new PHI node from the last prolog block
138 // that was created.
139 NewPN->addIncoming(V, PrologLatch);
140
141 // Update the existing PHI node operand with the value from the
142 // new PHI node. How this is done depends on if the existing
143 // PHI node is in the original loop block, or the exit block.
144 if (L->contains(&PN))
145 PN.setIncomingValueForBlock(NewPreHeader, NewPN);
146 else
147 PN.addIncoming(NewPN, PrologExit);
149 }
150 }
151
152 // Make sure that created prolog loop is in simplified form
153 SmallVector<BasicBlock *, 4> PrologExitPreds;
154 Loop *PrologLoop = LI->getLoopFor(PrologLatch);
155 if (PrologLoop) {
156 for (BasicBlock *PredBB : predecessors(PrologExit))
157 if (PrologLoop->contains(PredBB))
158 PrologExitPreds.push_back(PredBB);
159
160 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
161 nullptr, PreserveLCSSA);
162 }
163
164 // Create a branch around the original loop, which is taken if there are no
165 // iterations remaining to be executed after running the prologue.
166 Instruction *InsertPt = PrologExit->getTerminator();
167 IRBuilder<> B(InsertPt);
168
169 assert(Count != 0 && "nonsensical Count!");
170
171 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
172 // This means %xtraiter is (BECount + 1) and all of the iterations of this
173 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
174 // then (BECount + 1) cannot unsigned-overflow.
175 Value *BrLoopExit =
176 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
177 // Split the exit to maintain loop canonicalization guarantees
178 SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
179 SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
180 nullptr, PreserveLCSSA);
181 // Add the branch to the exit block (around the unrolled loop)
182 MDNode *BranchWeights = nullptr;
183 if (hasBranchWeightMD(*Latch->getTerminator())) {
184 // Assume loop is nearly always entered.
185 MDBuilder MDB(B.getContext());
187 }
188 B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader,
189 BranchWeights);
190 InsertPt->eraseFromParent();
191 if (DT) {
192 auto *NewDom = DT->findNearestCommonDominator(OriginalLoopLatchExit,
193 PrologExit);
194 DT->changeImmediateDominator(OriginalLoopLatchExit, NewDom);
195 }
196}
197
198/// Connect the unrolling epilog code to the original loop.
199/// The unrolling epilog code contains code to execute the
200/// 'extra' iterations if the run-time trip count modulo the
201/// unroll count is non-zero.
202///
203/// This function performs the following:
204/// - Update PHI nodes at the epilog loop exit
205/// - Create PHI nodes at the unrolling loop exit and epilog preheader to
206/// combine values that exit the unrolling loop code and jump around it.
207/// - Update PHI operands in the epilog loop by the new PHI nodes
208/// - At the unrolling loop exit, branch around the epilog loop if extra iters
209// (ModVal) is zero.
210/// - At the epilog preheader, add an llvm.assume call that extra iters is
211/// non-zero. If the unrolling loop exit is the predecessor, the above new
212/// branch guarantees that assumption. If the unrolling loop preheader is the
213/// predecessor, then the required first iteration from the original loop has
214/// yet to be executed, so it must be executed in the epilog loop. If we
215/// later unroll the epilog loop, that llvm.assume call somehow enables
216/// ScalarEvolution to compute a epilog loop maximum trip count, which enables
217/// eliminating the branch at the end of the final unrolled epilog iteration.
218///
219static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
220 BasicBlock *Exit, BasicBlock *PreHeader,
221 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
223 LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE,
224 unsigned Count, AssumptionCache &AC) {
225 BasicBlock *Latch = L->getLoopLatch();
226 assert(Latch && "Loop must have a latch");
227 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
228
229 // Loop structure should be the following:
230 //
231 // PreHeader
232 // NewPreHeader
233 // Header
234 // ...
235 // Latch
236 // NewExit (PN)
237 // EpilogPreHeader
238 // EpilogHeader
239 // ...
240 // EpilogLatch
241 // Exit (EpilogPN)
242
243 // Update PHI nodes at Exit.
244 for (PHINode &PN : NewExit->phis()) {
245 // PN should be used in another PHI located in Exit block as
246 // Exit was split by SplitBlockPredecessors into Exit and NewExit
247 // Basically it should look like:
248 // NewExit:
249 // PN = PHI [I, Latch]
250 // ...
251 // Exit:
252 // EpilogPN = PHI [PN, EpilogPreHeader], [X, Exit2], [Y, Exit2.epil]
253 //
254 // Exits from non-latch blocks point to the original exit block and the
255 // epilogue edges have already been added.
256 //
257 // There is EpilogPreHeader incoming block instead of NewExit as
258 // NewExit was split 1 more time to get EpilogPreHeader.
259 assert(PN.hasOneUse() && "The phi should have 1 use");
260 PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
261 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
262
263 Value *V = PN.getIncomingValueForBlock(Latch);
265 if (I && L->contains(I))
266 // If value comes from an instruction in the loop add VMap value.
267 V = VMap.lookup(I);
268 // For the instruction out of the loop, constant or undefined value
269 // insert value itself.
270 EpilogPN->addIncoming(V, EpilogLatch);
271
272 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
273 "EpilogPN should have EpilogPreHeader incoming block");
274 // Change EpilogPreHeader incoming block to NewExit.
275 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
276 NewExit);
277 // Now PHIs should look like:
278 // NewExit:
279 // PN = PHI [I, Latch]
280 // ...
281 // Exit:
282 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
283 }
284
285 // Create PHI nodes at NewExit (from the unrolling loop Latch) and at
286 // EpilogPreHeader (from PreHeader and NewExit). Update corresponding PHI
287 // nodes in epilog loop.
288 for (BasicBlock *Succ : successors(Latch)) {
289 // Skip this as we already updated phis in exit blocks.
290 if (!L->contains(Succ))
291 continue;
292
293 // Succ here appears to always be just L->getHeader(). Otherwise, how do we
294 // know its corresponding epilog block (from VMap) is EpilogHeader and thus
295 // EpilogPreHeader is the right incoming block for VPN, as set below?
296 // TODO: Can we thus avoid the enclosing loop over successors?
297 assert(Succ == L->getHeader() &&
298 "Expect the only in-loop successor of latch to be the loop header");
299
300 for (PHINode &PN : Succ->phis()) {
301 // Add new PHI nodes to the loop exit block.
302 PHINode *NewPN0 = PHINode::Create(PN.getType(), /*NumReservedValues=*/1,
303 PN.getName() + ".unr");
304 NewPN0->insertBefore(NewExit->getFirstNonPHIIt());
305 // Add value to the new PHI node from the unrolling loop latch.
306 NewPN0->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
307
308 // Add new PHI nodes to EpilogPreHeader.
309 PHINode *NewPN1 = PHINode::Create(PN.getType(), /*NumReservedValues=*/2,
310 PN.getName() + ".epil.init");
311 NewPN1->insertBefore(EpilogPreHeader->getFirstNonPHIIt());
312 // Add value to the new PHI node from the unrolling loop preheader.
313 NewPN1->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
314 // Add value to the new PHI node from the epilog loop guard.
315 NewPN1->addIncoming(NewPN0, NewExit);
316
317 // Update the existing PHI node operand with the value from the new PHI
318 // node. Corresponding instruction in epilog loop should be PHI.
319 PHINode *VPN = cast<PHINode>(VMap[&PN]);
320 VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN1);
321 }
322 }
323
324 // In NewExit, branch around the epilog loop if no extra iters.
325 Instruction *InsertPt = NewExit->getTerminator();
326 IRBuilder<> B(InsertPt);
327 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
328 assert(Exit && "Loop must have a single exit block only");
329 // Split the epilogue exit to maintain loop canonicalization guarantees
331 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
332 PreserveLCSSA);
333 // Add the branch to the exit block (around the epilog loop)
334 MDNode *BranchWeights = nullptr;
335 if (hasBranchWeightMD(*Latch->getTerminator())) {
336 // Assume equal distribution in interval [0, Count).
337 MDBuilder MDB(B.getContext());
338 BranchWeights = MDB.createBranchWeights(1, Count - 1);
339 }
340 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit, BranchWeights);
341 InsertPt->eraseFromParent();
342 if (DT) {
343 auto *NewDom = DT->findNearestCommonDominator(Exit, NewExit);
344 DT->changeImmediateDominator(Exit, NewDom);
345 }
346
347 // In EpilogPreHeader, assume extra iters is non-zero.
348 IRBuilder<> B2(EpilogPreHeader, EpilogPreHeader->getFirstNonPHIIt());
349 Value *ModIsNotNull = B2.CreateIsNotNull(ModVal, "lcmp.mod");
350 AssumeInst *AI = cast<AssumeInst>(B2.CreateAssumption(ModIsNotNull));
351 AC.registerAssumption(AI);
352}
353
354/// Create a clone of the blocks in a loop and connect them together. A new
355/// loop will be created including all cloned blocks, and the iterator of the
356/// new loop switched to count NewIter down to 0.
357/// The cloned blocks should be inserted between InsertTop and InsertBot.
358/// InsertTop should be new preheader, InsertBot new loop exit.
359/// Returns the new cloned loop that is created.
360static Loop *
361CloneLoopBlocks(Loop *L, Value *NewIter, const bool UseEpilogRemainder,
362 const bool UnrollRemainder,
363 BasicBlock *InsertTop,
364 BasicBlock *InsertBot, BasicBlock *Preheader,
365 std::vector<BasicBlock *> &NewBlocks,
366 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
367 DominatorTree *DT, LoopInfo *LI, unsigned Count) {
368 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
369 BasicBlock *Header = L->getHeader();
370 BasicBlock *Latch = L->getLoopLatch();
371 Function *F = Header->getParent();
372 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
373 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
374 Loop *ParentLoop = L->getParentLoop();
375 NewLoopsMap NewLoops;
376 NewLoops[ParentLoop] = ParentLoop;
377
378 // For each block in the original loop, create a new copy,
379 // and update the value map with the newly created values.
380 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
381 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
382 NewBlocks.push_back(NewBB);
383
384 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
385
386 VMap[*BB] = NewBB;
387 if (Header == *BB) {
388 // For the first block, add a CFG connection to this newly
389 // created block.
390 InsertTop->getTerminator()->setSuccessor(0, NewBB);
391 }
392
393 if (DT) {
394 if (Header == *BB) {
395 // The header is dominated by the preheader.
396 DT->addNewBlock(NewBB, InsertTop);
397 } else {
398 // Copy information from original loop to unrolled loop.
399 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
400 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
401 }
402 }
403
404 if (Latch == *BB) {
405 // For the last block, create a loop back to cloned head.
406 VMap.erase((*BB)->getTerminator());
407 // Use an incrementing IV. Pre-incr/post-incr is backedge/trip count.
408 // Subtle: NewIter can be 0 if we wrapped when computing the trip count,
409 // thus we must compare the post-increment (wrapping) value.
410 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
411 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
412 IRBuilder<> Builder(LatchBR);
413 PHINode *NewIdx =
414 PHINode::Create(NewIter->getType(), 2, suffix + ".iter");
415 NewIdx->insertBefore(FirstLoopBB->getFirstNonPHIIt());
416 auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
417 auto *One = ConstantInt::get(NewIdx->getType(), 1);
418 Value *IdxNext =
419 Builder.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
420 Value *IdxCmp = Builder.CreateICmpNE(IdxNext, NewIter, NewIdx->getName() + ".cmp");
421 MDNode *BranchWeights = nullptr;
422 if (hasBranchWeightMD(*LatchBR)) {
423 uint32_t ExitWeight;
424 uint32_t BackEdgeWeight;
425 if (Count >= 3) {
426 // Note: We do not enter this loop for zero-remainders. The check
427 // is at the end of the loop. We assume equal distribution between
428 // possible remainders in [1, Count).
429 ExitWeight = 1;
430 BackEdgeWeight = (Count - 2) / 2;
431 } else {
432 // Unnecessary backedge, should never be taken. The conditional
433 // jump should be optimized away later.
434 ExitWeight = 1;
435 BackEdgeWeight = 0;
436 }
437 MDBuilder MDB(Builder.getContext());
438 BranchWeights = MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
439 }
440 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot, BranchWeights);
441 NewIdx->addIncoming(Zero, InsertTop);
442 NewIdx->addIncoming(IdxNext, NewBB);
443 LatchBR->eraseFromParent();
444 }
445 }
446
447 // Change the incoming values to the ones defined in the preheader or
448 // cloned loop.
449 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
450 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
451 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
452 NewPHI->setIncomingBlock(idx, InsertTop);
453 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
454 idx = NewPHI->getBasicBlockIndex(Latch);
455 Value *InVal = NewPHI->getIncomingValue(idx);
456 NewPHI->setIncomingBlock(idx, NewLatch);
457 if (Value *V = VMap.lookup(InVal))
458 NewPHI->setIncomingValue(idx, V);
459 }
460
461 Loop *NewLoop = NewLoops[L];
462 assert(NewLoop && "L should have been cloned");
463 MDNode *LoopID = NewLoop->getLoopID();
464
465 // Only add loop metadata if the loop is not going to be completely
466 // unrolled.
467 if (UnrollRemainder)
468 return NewLoop;
469
470 std::optional<MDNode *> NewLoopID = makeFollowupLoopID(
472 if (NewLoopID) {
473 NewLoop->setLoopID(*NewLoopID);
474
475 // Do not setLoopAlreadyUnrolled if loop attributes have been defined
476 // explicitly.
477 return NewLoop;
478 }
479
480 // Add unroll disable metadata to disable future unrolling for this loop.
481 NewLoop->setLoopAlreadyUnrolled();
482 return NewLoop;
483}
484
485/// Returns true if we can profitably unroll the multi-exit loop L. Currently,
486/// we return true only if UnrollRuntimeMultiExit is set to true.
488 Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
489 bool UseEpilogRemainder) {
490
491 // The main pain point with multi-exit loop unrolling is that once unrolled,
492 // we will not be able to merge all blocks into a straight line code.
493 // There are branches within the unrolled loop that go to the OtherExits.
494 // The second point is the increase in code size, but this is true
495 // irrespective of multiple exits.
496
497 // Note: Both the heuristics below are coarse grained. We are essentially
498 // enabling unrolling of loops that have a single side exit other than the
499 // normal LatchExit (i.e. exiting into a deoptimize block).
500 // The heuristics considered are:
501 // 1. low number of branches in the unrolled version.
502 // 2. high predictability of these extra branches.
503 // We avoid unrolling loops that have more than two exiting blocks. This
504 // limits the total number of branches in the unrolled loop to be atmost
505 // the unroll factor (since one of the exiting blocks is the latch block).
506 SmallVector<BasicBlock*, 4> ExitingBlocks;
507 L->getExitingBlocks(ExitingBlocks);
508 if (ExitingBlocks.size() > 2)
509 return false;
510
511 // Allow unrolling of loops with no non latch exit blocks.
512 if (OtherExits.size() == 0)
513 return true;
514
515 // The second heuristic is that L has one exit other than the latchexit and
516 // that exit is a deoptimize block. We know that deoptimize blocks are rarely
517 // taken, which also implies the branch leading to the deoptimize block is
518 // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we
519 // assume the other exit branch is predictable even if it has no deoptimize
520 // call.
521 return (OtherExits.size() == 1 &&
523 OtherExits[0]->getPostdominatingDeoptimizeCall()));
524 // TODO: These can be fine-tuned further to consider code size or deopt states
525 // that are captured by the deoptimize exit block.
526 // Also, we can extend this to support more cases, if we actually
527 // know of kinds of multiexit loops that would benefit from unrolling.
528}
529
530/// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
531/// accounting for the possibility of unsigned overflow in the 2s complement
532/// domain. Preconditions:
533/// 1) TripCount = BECount + 1 (allowing overflow)
534/// 2) Log2(Count) <= BitWidth(BECount)
536 Value *TripCount, unsigned Count) {
537 // Note that TripCount is BECount + 1.
538 if (isPowerOf2_32(Count))
539 // If the expression is zero, then either:
540 // 1. There are no iterations to be run in the prolog/epilog loop.
541 // OR
542 // 2. The addition computing TripCount overflowed.
543 //
544 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
545 // the number of iterations that remain to be run in the original loop is a
546 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
547 // precondition of this method).
548 return B.CreateAnd(TripCount, Count - 1, "xtraiter");
549
550 // As (BECount + 1) can potentially unsigned overflow we count
551 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
552 Constant *CountC = ConstantInt::get(BECount->getType(), Count);
553 Value *ModValTmp = B.CreateURem(BECount, CountC);
554 Value *ModValAdd = B.CreateAdd(ModValTmp,
555 ConstantInt::get(ModValTmp->getType(), 1));
556 // At that point (BECount % Count) + 1 could be equal to Count.
557 // To handle this case we need to take mod by Count one more time.
558 return B.CreateURem(ModValAdd, CountC, "xtraiter");
559}
560
561
562/// Insert code in the prolog/epilog code when unrolling a loop with a
563/// run-time trip-count.
564///
565/// This method assumes that the loop unroll factor is total number
566/// of loop bodies in the loop after unrolling. (Some folks refer
567/// to the unroll factor as the number of *extra* copies added).
568/// We assume also that the loop unroll factor is a power-of-two. So, after
569/// unrolling the loop, the number of loop bodies executed is 2,
570/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
571/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
572/// the switch instruction is generated.
573///
574/// ***Prolog case***
575/// extraiters = tripcount % loopfactor
576/// if (extraiters == 0) jump Loop:
577/// else jump Prol:
578/// Prol: LoopBody;
579/// extraiters -= 1 // Omitted if unroll factor is 2.
580/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
581/// if (tripcount < loopfactor) jump End:
582/// Loop:
583/// ...
584/// End:
585///
586/// ***Epilog case***
587/// extraiters = tripcount % loopfactor
588/// if (tripcount < loopfactor) jump LoopExit:
589/// unroll_iters = tripcount - extraiters
590/// Loop: LoopBody; (executes unroll_iter times);
591/// unroll_iter -= 1
592/// if (unroll_iter != 0) jump Loop:
593/// LoopExit:
594/// if (extraiters == 0) jump EpilExit:
595/// Epil: LoopBody; (executes extraiters times)
596/// extraiters -= 1 // Omitted if unroll factor is 2.
597/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
598/// EpilExit:
599
601 Loop *L, unsigned Count, bool AllowExpensiveTripCount,
602 bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV,
604 const TargetTransformInfo *TTI, bool PreserveLCSSA,
605 unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit,
606 Loop **ResultLoop) {
607 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
608 LLVM_DEBUG(L->dump());
609 LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
610 : dbgs() << "Using prolog remainder.\n");
611
612 // Make sure the loop is in canonical form.
613 if (!L->isLoopSimplifyForm()) {
614 LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
615 return false;
616 }
617
618 // Guaranteed by LoopSimplifyForm.
619 BasicBlock *Latch = L->getLoopLatch();
620 BasicBlock *Header = L->getHeader();
621
622 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
623
624 if (!LatchBR || LatchBR->isUnconditional()) {
625 // The loop-rotate pass can be helpful to avoid this in many cases.
627 dbgs()
628 << "Loop latch not terminated by a conditional branch.\n");
629 return false;
630 }
631
632 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
633 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
634
635 if (L->contains(LatchExit)) {
636 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
637 // targets of the Latch be an exit block out of the loop.
639 dbgs()
640 << "One of the loop latch successors must be the exit block.\n");
641 return false;
642 }
643
644 // These are exit blocks other than the target of the latch exiting block.
646 L->getUniqueNonLatchExitBlocks(OtherExits);
647 // Support only single exit and exiting block unless multi-exit loop
648 // unrolling is enabled.
649 if (!L->getExitingBlock() || OtherExits.size()) {
650 // We rely on LCSSA form being preserved when the exit blocks are transformed.
651 // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
652 if (!PreserveLCSSA)
653 return false;
654
655 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
656 if (UnrollRuntimeMultiExit.getNumOccurrences()) {
658 return false;
659 } else {
660 // Otherwise perform multi-exit unrolling, if either the target indicates
661 // it is profitable or the general profitability heuristics apply.
662 if (!RuntimeUnrollMultiExit &&
663 !canProfitablyRuntimeUnrollMultiExitLoop(L, OtherExits, LatchExit,
664 UseEpilogRemainder)) {
665 LLVM_DEBUG(dbgs() << "Multiple exit/exiting blocks in loop and "
666 "multi-exit unrolling not enabled!\n");
667 return false;
668 }
669 }
670 }
671 // Use Scalar Evolution to compute the trip count. This allows more loops to
672 // be unrolled than relying on induction var simplification.
673 if (!SE)
674 return false;
675
676 // Only unroll loops with a computable trip count.
677 // We calculate the backedge count by using getExitCount on the Latch block,
678 // which is proven to be the only exiting block in this loop. This is same as
679 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
680 // exiting blocks).
681 const SCEV *BECountSC = SE->getExitCount(L, Latch);
682 if (isa<SCEVCouldNotCompute>(BECountSC)) {
683 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
684 return false;
685 }
686
687 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
688
689 // Add 1 since the backedge count doesn't include the first loop iteration.
690 // (Note that overflow can occur, this is handled explicitly below)
691 const SCEV *TripCountSC =
692 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
693 if (isa<SCEVCouldNotCompute>(TripCountSC)) {
694 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
695 return false;
696 }
697
698 BasicBlock *PreHeader = L->getLoopPreheader();
699 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
700 const DataLayout &DL = Header->getDataLayout();
701 SCEVExpander Expander(*SE, DL, "loop-unroll");
702 if (!AllowExpensiveTripCount &&
703 Expander.isHighCostExpansion(TripCountSC, L, SCEVExpansionBudget, TTI,
704 PreHeaderBR)) {
705 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
706 return false;
707 }
708
709 // This constraint lets us deal with an overflowing trip count easily; see the
710 // comment on ModVal below.
711 if (Log2_32(Count) > BEWidth) {
713 dbgs()
714 << "Count failed constraint on overflow trip count calculation.\n");
715 return false;
716 }
717
718 // Loop structure is the following:
719 //
720 // PreHeader
721 // Header
722 // ...
723 // Latch
724 // LatchExit
725
726 BasicBlock *NewPreHeader;
727 BasicBlock *NewExit = nullptr;
728 BasicBlock *PrologExit = nullptr;
729 BasicBlock *EpilogPreHeader = nullptr;
730 BasicBlock *PrologPreHeader = nullptr;
731
732 if (UseEpilogRemainder) {
733 // If epilog remainder
734 // Split PreHeader to insert a branch around loop for unrolling.
735 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
736 NewPreHeader->setName(PreHeader->getName() + ".new");
737 // Split LatchExit to create phi nodes from branch above.
738 NewExit = SplitBlockPredecessors(LatchExit, {Latch}, ".unr-lcssa", DT, LI,
739 nullptr, PreserveLCSSA);
740 // NewExit gets its DebugLoc from LatchExit, which is not part of the
741 // original Loop.
742 // Fix this by setting Loop's DebugLoc to NewExit.
743 auto *NewExitTerminator = NewExit->getTerminator();
744 NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
745 // Split NewExit to insert epilog remainder loop.
746 EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
747 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
748
749 // If the latch exits from multiple level of nested loops, then
750 // by assumption there must be another loop exit which branches to the
751 // outer loop and we must adjust the loop for the newly inserted blocks
752 // to account for the fact that our epilogue is still in the same outer
753 // loop. Note that this leaves loopinfo temporarily out of sync with the
754 // CFG until the actual epilogue loop is inserted.
755 if (auto *ParentL = L->getParentLoop())
756 if (LI->getLoopFor(LatchExit) != ParentL) {
757 LI->removeBlock(NewExit);
758 ParentL->addBasicBlockToLoop(NewExit, *LI);
759 LI->removeBlock(EpilogPreHeader);
760 ParentL->addBasicBlockToLoop(EpilogPreHeader, *LI);
761 }
762
763 } else {
764 // If prolog remainder
765 // Split the original preheader twice to insert prolog remainder loop
766 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
767 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
768 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
769 DT, LI);
770 PrologExit->setName(Header->getName() + ".prol.loopexit");
771 // Split PrologExit to get NewPreHeader.
772 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
773 NewPreHeader->setName(PreHeader->getName() + ".new");
774 }
775 // Loop structure should be the following:
776 // Epilog Prolog
777 //
778 // PreHeader PreHeader
779 // *NewPreHeader *PrologPreHeader
780 // Header *PrologExit
781 // ... *NewPreHeader
782 // Latch Header
783 // *NewExit ...
784 // *EpilogPreHeader Latch
785 // LatchExit LatchExit
786
787 // Calculate conditions for branch around loop for unrolling
788 // in epilog case and around prolog remainder loop in prolog case.
789 // Compute the number of extra iterations required, which is:
790 // extra iterations = run-time trip count % loop unroll factor
791 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
792 IRBuilder<> B(PreHeaderBR);
793 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
794 PreHeaderBR);
795 Value *BECount;
796 // If there are other exits before the latch, that may cause the latch exit
797 // branch to never be executed, and the latch exit count may be poison.
798 // In this case, freeze the TripCount and base BECount on the frozen
799 // TripCount. We will introduce two branches using these values, and it's
800 // important that they see a consistent value (which would not be guaranteed
801 // if were frozen independently.)
802 if ((!OtherExits.empty() || !SE->loopHasNoAbnormalExits(L)) &&
803 !isGuaranteedNotToBeUndefOrPoison(TripCount, AC, PreHeaderBR, DT)) {
804 TripCount = B.CreateFreeze(TripCount);
805 BECount =
806 B.CreateAdd(TripCount, Constant::getAllOnesValue(TripCount->getType()));
807 } else {
808 // If we don't need to freeze, use SCEVExpander for BECount as well, to
809 // allow slightly better value reuse.
810 BECount =
811 Expander.expandCodeFor(BECountSC, BECountSC->getType(), PreHeaderBR);
812 }
813
814 Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count);
815
816 Value *BranchVal =
817 UseEpilogRemainder ? B.CreateICmpULT(BECount,
818 ConstantInt::get(BECount->getType(),
819 Count - 1)) :
820 B.CreateIsNotNull(ModVal, "lcmp.mod");
821 BasicBlock *RemainderLoop =
822 UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
823 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
824 // Branch to either remainder (extra iterations) loop or unrolling loop.
825 MDNode *BranchWeights = nullptr;
826 if (hasBranchWeightMD(*Latch->getTerminator())) {
827 // Assume loop is nearly always entered.
828 MDBuilder MDB(B.getContext());
829 BranchWeights = MDB.createBranchWeights(EpilogHeaderWeights);
830 }
831 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop, BranchWeights);
832 PreHeaderBR->eraseFromParent();
833 if (DT) {
834 if (UseEpilogRemainder)
835 DT->changeImmediateDominator(EpilogPreHeader, PreHeader);
836 else
837 DT->changeImmediateDominator(PrologExit, PreHeader);
838 }
839 Function *F = Header->getParent();
840 // Get an ordered list of blocks in the loop to help with the ordering of the
841 // cloned blocks in the prolog/epilog code
842 LoopBlocksDFS LoopBlocks(L);
843 LoopBlocks.perform(LI);
844
845 //
846 // For each extra loop iteration, create a copy of the loop's basic blocks
847 // and generate a condition that branches to the copy depending on the
848 // number of 'left over' iterations.
849 //
850 std::vector<BasicBlock *> NewBlocks;
852
853 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
854 // the loop, otherwise we create a cloned loop to execute the extra
855 // iterations. This function adds the appropriate CFG connections.
856 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
857 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
858 Loop *remainderLoop = CloneLoopBlocks(
859 L, ModVal, UseEpilogRemainder, UnrollRemainder, InsertTop, InsertBot,
860 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI, Count);
861
862 // Insert the cloned blocks into the function.
863 F->splice(InsertBot->getIterator(), F, NewBlocks[0]->getIterator(), F->end());
864
865 // Now the loop blocks are cloned and the other exiting blocks from the
866 // remainder are connected to the original Loop's exit blocks. The remaining
867 // work is to update the phi nodes in the original loop, and take in the
868 // values from the cloned region.
869 for (auto *BB : OtherExits) {
870 // Given we preserve LCSSA form, we know that the values used outside the
871 // loop will be used through these phi nodes at the exit blocks that are
872 // transformed below.
873 for (PHINode &PN : BB->phis()) {
874 unsigned oldNumOperands = PN.getNumIncomingValues();
875 // Add the incoming values from the remainder code to the end of the phi
876 // node.
877 for (unsigned i = 0; i < oldNumOperands; i++){
878 auto *PredBB =PN.getIncomingBlock(i);
879 if (PredBB == Latch)
880 // The latch exit is handled separately, see connectX
881 continue;
882 if (!L->contains(PredBB))
883 // Even if we had dedicated exits, the code above inserted an
884 // extra branch which can reach the latch exit.
885 continue;
886
887 auto *V = PN.getIncomingValue(i);
889 if (L->contains(I))
890 V = VMap.lookup(I);
891 PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB]));
892 }
893 }
894#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
895 for (BasicBlock *SuccBB : successors(BB)) {
896 assert(!(llvm::is_contained(OtherExits, SuccBB) || SuccBB == LatchExit) &&
897 "Breaks the definition of dedicated exits!");
898 }
899#endif
900 }
901
902 // Update the immediate dominator of the exit blocks and blocks that are
903 // reachable from the exit blocks. This is needed because we now have paths
904 // from both the original loop and the remainder code reaching the exit
905 // blocks. While the IDom of these exit blocks were from the original loop,
906 // now the IDom is the preheader (which decides whether the original loop or
907 // remainder code should run) unless the block still has just the original
908 // predecessor (such as NewExit in the case of an epilog remainder).
909 if (DT && !L->getExitingBlock()) {
910 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
911 // NB! We have to examine the dom children of all loop blocks, not just
912 // those which are the IDom of the exit blocks. This is because blocks
913 // reachable from the exit blocks can have their IDom as the nearest common
914 // dominator of the exit blocks.
915 for (auto *BB : L->blocks()) {
916 auto *DomNodeBB = DT->getNode(BB);
917 for (auto *DomChild : DomNodeBB->children()) {
918 auto *DomChildBB = DomChild->getBlock();
919 if (!L->contains(LI->getLoopFor(DomChildBB)) &&
920 DomChildBB->getUniquePredecessor() != BB)
921 ChildrenToUpdate.push_back(DomChildBB);
922 }
923 }
924 for (auto *BB : ChildrenToUpdate)
925 DT->changeImmediateDominator(BB, PreHeader);
926 }
927
928 // Loop structure should be the following:
929 // Epilog Prolog
930 //
931 // PreHeader PreHeader
932 // NewPreHeader PrologPreHeader
933 // Header PrologHeader
934 // ... ...
935 // Latch PrologLatch
936 // NewExit PrologExit
937 // EpilogPreHeader NewPreHeader
938 // EpilogHeader Header
939 // ... ...
940 // EpilogLatch Latch
941 // LatchExit LatchExit
942
943 // Rewrite the cloned instruction operands to use the values created when the
944 // clone is created.
945 for (BasicBlock *BB : NewBlocks) {
946 Module *M = BB->getModule();
947 for (Instruction &I : *BB) {
948 RemapInstruction(&I, VMap,
950 RemapDbgRecordRange(M, I.getDbgRecordRange(), VMap,
952 }
953 }
954
955 if (UseEpilogRemainder) {
956 // Connect the epilog code to the original loop and update the
957 // PHI functions.
958 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, EpilogPreHeader,
959 NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE, Count, *AC);
960
961 // Update counter in loop for unrolling.
962 // Use an incrementing IV. Pre-incr/post-incr is backedge/trip count.
963 // Subtle: TestVal can be 0 if we wrapped when computing the trip count,
964 // thus we must compare the post-increment (wrapping) value.
965 IRBuilder<> B2(NewPreHeader->getTerminator());
966 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
967 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
968 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter");
969 NewIdx->insertBefore(Header->getFirstNonPHIIt());
970 B2.SetInsertPoint(LatchBR);
971 auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
972 auto *One = ConstantInt::get(NewIdx->getType(), 1);
973 Value *IdxNext = B2.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
974 auto Pred = LatchBR->getSuccessor(0) == Header ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
975 Value *IdxCmp = B2.CreateICmp(Pred, IdxNext, TestVal, NewIdx->getName() + ".ncmp");
976 NewIdx->addIncoming(Zero, NewPreHeader);
977 NewIdx->addIncoming(IdxNext, Latch);
978 LatchBR->setCondition(IdxCmp);
979 } else {
980 // Connect the prolog code to the original loop and update the
981 // PHI functions.
982 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
983 NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE);
984 }
985
986 // If this loop is nested, then the loop unroller changes the code in the any
987 // of its parent loops, so the Scalar Evolution pass needs to be run again.
988 SE->forgetTopmostLoop(L);
989
990 // Verify that the Dom Tree and Loop Info are correct.
991#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
992 if (DT) {
993 assert(DT->verify(DominatorTree::VerificationLevel::Full));
994 LI->verify(*DT);
995 }
996#endif
997
998 // For unroll factor 2 remainder loop will have 1 iteration.
999 if (Count == 2 && DT && LI && SE) {
1000 // TODO: This code could probably be pulled out into a helper function
1001 // (e.g. breakLoopBackedgeAndSimplify) and reused in loop-deletion.
1002 BasicBlock *RemainderLatch = remainderLoop->getLoopLatch();
1003 assert(RemainderLatch);
1004 SmallVector<BasicBlock *> RemainderBlocks(remainderLoop->getBlocks());
1005 breakLoopBackedge(remainderLoop, *DT, *SE, *LI, nullptr);
1006 remainderLoop = nullptr;
1007
1008 // Simplify loop values after breaking the backedge
1009 const DataLayout &DL = L->getHeader()->getDataLayout();
1011 for (BasicBlock *BB : RemainderBlocks) {
1012 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
1013 if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
1014 if (LI->replacementPreservesLCSSAForm(&Inst, V))
1015 Inst.replaceAllUsesWith(V);
1016 if (isInstructionTriviallyDead(&Inst))
1017 DeadInsts.emplace_back(&Inst);
1018 }
1019 // We can't do recursive deletion until we're done iterating, as we might
1020 // have a phi which (potentially indirectly) uses instructions later in
1021 // the block we're iterating through.
1023 }
1024
1025 // Merge latch into exit block.
1026 auto *ExitBB = RemainderLatch->getSingleSuccessor();
1027 assert(ExitBB && "required after breaking cond br backedge");
1028 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1029 MergeBlockIntoPredecessor(ExitBB, &DTU, LI);
1030 }
1031
1032 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
1033 // cannot rely on the LoopUnrollPass to do this because it only does
1034 // canonicalization for parent/subloops and not the sibling loops.
1035 if (OtherExits.size() > 0) {
1036 // Generate dedicated exit blocks for the original loop, to preserve
1037 // LoopSimplifyForm.
1038 formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
1039 // Generate dedicated exit blocks for the remainder loop if one exists, to
1040 // preserve LoopSimplifyForm.
1041 if (remainderLoop)
1042 formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
1043 }
1044
1045 auto UnrollResult = LoopUnrollResult::Unmodified;
1046 if (remainderLoop && UnrollRemainder) {
1047 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
1049 ULO.Count = Count - 1;
1050 ULO.Force = false;
1051 ULO.Runtime = false;
1052 ULO.AllowExpensiveTripCount = false;
1053 ULO.UnrollRemainder = false;
1054 ULO.ForgetAllSCEV = ForgetAllSCEV;
1056 "A loop with a convergence heart does not allow runtime unrolling.");
1057 UnrollResult = UnrollLoop(remainderLoop, ULO, LI, SE, DT, AC, TTI,
1058 /*ORE*/ nullptr, PreserveLCSSA);
1059 }
1060
1061 if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
1062 *ResultLoop = remainderLoop;
1063 NumRuntimeUnrolled++;
1064 return true;
1065}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Module.h This file contains the declarations for the Module class.
static Loop * CloneLoopBlocks(Loop *L, Value *NewIter, const bool UseEpilogRemainder, const bool UnrollRemainder, BasicBlock *InsertTop, BasicBlock *InsertBot, BasicBlock *Preheader, std::vector< BasicBlock * > &NewBlocks, LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI, unsigned Count)
Create a clone of the blocks in a loop and connect them together.
static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, BasicBlock *Exit, BasicBlock *PreHeader, BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE, unsigned Count, AssumptionCache &AC)
Connect the unrolling epilog code to the original loop.
static const uint32_t UnrolledLoopHeaderWeights[]
static Value * CreateTripRemainder(IRBuilder<> &B, Value *BECount, Value *TripCount, unsigned Count)
Calculate ModVal = (BECount + 1) % Count on the abstract integer domain accounting for the possibilit...
static cl::opt< bool > UnrollRuntimeOtherExitPredictable("unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden, cl::desc("Assume the non latch exit block to be predictable"))
static bool canProfitablyRuntimeUnrollMultiExitLoop(Loop *L, SmallVectorImpl< BasicBlock * > &OtherExits, BasicBlock *LatchExit, bool UseEpilogRemainder)
Returns true if we can profitably unroll the multi-exit loop L.
static const uint32_t EpilogHeaderWeights[]
static cl::opt< bool > UnrollRuntimeMultiExit("unroll-runtime-multi-exit", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolling for loops with multiple exits, when " "epilog is generated"))
static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, BasicBlock *PrologExit, BasicBlock *OriginalLoopLatchExit, BasicBlock *PreHeader, BasicBlock *NewPreHeader, ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE)
Connect the unrolling prolog code to the original loop.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
This file contains the declarations for profiling metadata utility functions.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:528
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
@ ICMP_NE
not equal
Definition InstrTypes.h:698
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI CallInst * CreateAssumption(Value *Cond, ArrayRef< OperandBundleDef > OpBundles={})
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1420
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1403
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2654
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2442
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2783
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Store the result of a depth first search within basic blocks contained by a single loop.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:441
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:526
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
Definition LoopInfo.cpp:538
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:502
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1078
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
void setIncomingBlock(unsigned i, BasicBlock *BB)
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class uses information about analyze scalars to rewrite expressions in canonical form.
bool isHighCostExpansion(ArrayRef< const SCEV * > Exprs, Loop *L, unsigned Budget, const TargetTransformInfo *TTI, const Instruction *At)
Return true for expressions that can't be evaluated at runtime within given Budget.
LLVM_ABI Value * expandCodeFor(const SCEV *SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
bool erase(const KeyT &Val)
Definition ValueMap.h:192
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:533
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:644
auto successors(const MachineBasicBlock *BB)
SmallDenseMap< const Loop *, Loop *, 4 > NewLoopsMap
Definition UnrollLoop.h:41
LLVM_ABI std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:402
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:342
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:288
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
@ Unmodified
The loop was not modified.
Definition UnrollLoop.h:60
@ FullyUnrolled
The loop was fully unrolled into straight-line code.
Definition UnrollLoop.h:69
LLVM_ABI void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA)
Remove the backedge of the specified loop.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
const char *const LLVMLoopUnrollFollowupAll
Definition UnrollLoop.h:45
TargetTransformInfo TTI
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
Definition LoopUtils.cpp:58
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
const char *const LLVMLoopUnrollFollowupRemainder
Definition UnrollLoop.h:48
LLVM_ABI const Loop * addClonedBlockToLoopInfo(BasicBlock *OriginalBB, BasicBlock *ClonedBB, LoopInfo *LI, NewLoopsMap &NewLoops)
Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary and adds a mapping from the o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:560
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1897
LLVM_ABI bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, bool PreserveLCSSA, unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit, Loop **ResultLoop=nullptr)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI LoopUnrollResult UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const llvm::TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop=nullptr, AAResults *AA=nullptr)
Unroll the given loop by Count.