LLVM 24.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/// Assume, due to our position in the remainder loop or its guard, anywhere
199/// from 0 to \p N more iterations can possibly execute. Among such cases in
200/// the original loop (with loop probability \p OriginalLoopProb), what is the
201/// probability of executing at least one more iteration?
203probOfNextInRemainder(BranchProbability OriginalLoopProb, unsigned N) {
204 // OriginalLoopProb == 1 would produce a division by zero in the calculation
205 // below. The problem is that case indicates an always infinite loop, but a
206 // remainder loop cannot be calculated at run time if the original loop is
207 // infinite as infinity % UnrollCount is undefined. We then choose
208 // probabilities indicating that all remainder loop iterations will always
209 // execute.
210 //
211 // Currently, the remainder loop here is an epilogue, which cannot be reached
212 // if the original loop is infinite, so the aforementioned choice is
213 // arbitrary.
214 //
215 // FIXME: Branch weights still need to be fixed in the case of prologues
216 // (issue #135812). In that case, the aforementioned choice seems reasonable
217 // for the goal of maintaining the original loop's block frequencies. That
218 // is, an infinite loop's initial iterations are not skipped, and the prologue
219 // loop body might have unique blocks that execute a finite number of times
220 // if, for example, the original loop body contains conditionals like i <
221 // UnrollCount.
222 if (OriginalLoopProb.isOne())
223 return OriginalLoopProb;
224
225 // Each of these variables holds the original loop's probability that the
226 // number of iterations it will execute is some m in the specified range.
227 BranchProbability ProbOne = OriginalLoopProb; // 1 <= m
228 BranchProbability ProbTooMany = ProbOne.pow(N + 1); // N + 1 <= m
229 BranchProbability ProbNotTooMany = ProbTooMany.getCompl(); // 0 <= m <= N
230 BranchProbability ProbOneNotTooMany = ProbOne - ProbTooMany; // 1 <= m <= N
231 return ProbOneNotTooMany / ProbNotTooMany;
232}
233
234/// Connect the unrolling epilog code to the original loop.
235/// The unrolling epilog code contains code to execute the
236/// 'extra' iterations if the run-time trip count modulo the
237/// unroll count is non-zero.
238///
239/// This function performs the following:
240/// - Update PHI nodes at the epilog loop exit
241/// - Create PHI nodes at the unrolling loop exit and epilog preheader to
242/// combine values that exit the unrolling loop code and jump around it.
243/// - Update PHI operands in the epilog loop by the new PHI nodes
244/// - At the unrolling loop exit, branch around the epilog loop if extra iters
245// (ModVal) is zero.
246/// - At the epilog preheader, add an llvm.assume call that extra iters is
247/// non-zero. If the unrolling loop exit is the predecessor, the above new
248/// branch guarantees that assumption. If the unrolling loop preheader is the
249/// predecessor, then the required first iteration from the original loop has
250/// yet to be executed, so it must be executed in the epilog loop. If we
251/// later unroll the epilog loop, that llvm.assume call somehow enables
252/// ScalarEvolution to compute a epilog loop maximum trip count, which enables
253/// eliminating the branch at the end of the final unrolled epilog iteration.
254///
255static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
256 BasicBlock *Exit, BasicBlock *PreHeader,
257 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
259 LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE,
260 unsigned Count, AssumptionCache &AC,
261 BranchProbability OriginalLoopProb) {
262 BasicBlock *Latch = L->getLoopLatch();
263 assert(Latch && "Loop must have a latch");
264 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
265
266 // Loop structure should be the following:
267 //
268 // PreHeader
269 // NewPreHeader
270 // Header
271 // ...
272 // Latch
273 // NewExit (PN)
274 // EpilogPreHeader
275 // EpilogHeader
276 // ...
277 // EpilogLatch
278 // Exit (EpilogPN)
279
280 // Update PHI nodes at Exit.
281 for (PHINode &PN : NewExit->phis()) {
282 // PN should be used in another PHI located in Exit block as
283 // Exit was split by SplitBlockPredecessors into Exit and NewExit
284 // Basically it should look like:
285 // NewExit:
286 // PN = PHI [I, Latch]
287 // ...
288 // Exit:
289 // EpilogPN = PHI [PN, EpilogPreHeader], [X, Exit2], [Y, Exit2.epil]
290 //
291 // Exits from non-latch blocks point to the original exit block and the
292 // epilogue edges have already been added.
293 //
294 // There is EpilogPreHeader incoming block instead of NewExit as
295 // NewExit was split 1 more time to get EpilogPreHeader.
296 assert(PN.hasOneUse() && "The phi should have 1 use");
297 PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
298 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
299
300 Value *V = PN.getIncomingValueForBlock(Latch);
302 if (I && L->contains(I))
303 // If value comes from an instruction in the loop add VMap value.
304 V = VMap.lookup(I);
305 // For the instruction out of the loop, constant or undefined value
306 // insert value itself.
307 EpilogPN->addIncoming(V, EpilogLatch);
308
309 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
310 "EpilogPN should have EpilogPreHeader incoming block");
311 // Change EpilogPreHeader incoming block to NewExit.
312 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
313 NewExit);
314 // Now PHIs should look like:
315 // NewExit:
316 // PN = PHI [I, Latch]
317 // ...
318 // Exit:
319 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
320 }
321
322 // Create PHI nodes at NewExit (from the unrolling loop Latch) and at
323 // EpilogPreHeader (from PreHeader and NewExit). Update corresponding PHI
324 // nodes in epilog loop.
325 for (BasicBlock *Succ : successors(Latch)) {
326 // Skip this as we already updated phis in exit blocks.
327 if (!L->contains(Succ))
328 continue;
329
330 // Succ here appears to always be just L->getHeader(). Otherwise, how do we
331 // know its corresponding epilog block (from VMap) is EpilogHeader and thus
332 // EpilogPreHeader is the right incoming block for VPN, as set below?
333 // TODO: Can we thus avoid the enclosing loop over successors?
334 assert(Succ == L->getHeader() &&
335 "Expect the only in-loop successor of latch to be the loop header");
336
337 for (PHINode &PN : Succ->phis()) {
338 // Add new PHI nodes to the loop exit block.
339 PHINode *NewPN0 = PHINode::Create(PN.getType(), /*NumReservedValues=*/1,
340 PN.getName() + ".unr");
341 NewPN0->insertBefore(NewExit->getFirstNonPHIIt());
342 // Add value to the new PHI node from the unrolling loop latch.
343 NewPN0->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
344
345 // Add new PHI nodes to EpilogPreHeader.
346 PHINode *NewPN1 = PHINode::Create(PN.getType(), /*NumReservedValues=*/2,
347 PN.getName() + ".epil.init");
348 NewPN1->insertBefore(EpilogPreHeader->getFirstNonPHIIt());
349 // Add value to the new PHI node from the unrolling loop preheader.
350 NewPN1->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
351 // Add value to the new PHI node from the epilog loop guard.
352 NewPN1->addIncoming(NewPN0, NewExit);
353
354 // Update the existing PHI node operand with the value from the new PHI
355 // node. Corresponding instruction in epilog loop should be PHI.
356 PHINode *VPN = cast<PHINode>(VMap[&PN]);
357 VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN1);
358 }
359 }
360
361 // In NewExit, branch around the epilog loop if no extra iters.
362 Instruction *InsertPt = NewExit->getTerminator();
363 IRBuilder<> B(InsertPt);
364 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
365 assert(Exit && "Loop must have a single exit block only");
366 // Split the epilogue exit to maintain loop canonicalization guarantees
368 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
369 PreserveLCSSA);
370 // Add the branch to the exit block (around the epilog loop)
371 MDNode *BranchWeights = nullptr;
372 if (OriginalLoopProb.isUnknown() &&
373 hasBranchWeightMD(*Latch->getTerminator())) {
374 // Assume equal distribution in interval [0, Count).
375 MDBuilder MDB(B.getContext());
376 BranchWeights = MDB.createBranchWeights(1, Count - 1);
377 }
378 CondBrInst *RemainderLoopGuard =
379 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit, BranchWeights);
380 if (!OriginalLoopProb.isUnknown()) {
381 setBranchProbability(RemainderLoopGuard,
382 probOfNextInRemainder(OriginalLoopProb, Count - 1),
383 /*ForFirstTarget=*/true);
384 }
385 InsertPt->eraseFromParent();
386 if (DT) {
387 auto *NewDom = DT->findNearestCommonDominator(Exit, NewExit);
388 DT->changeImmediateDominator(Exit, NewDom);
389 }
390
391 // In EpilogPreHeader, assume extra iters is non-zero.
392 IRBuilder<> B2(EpilogPreHeader, EpilogPreHeader->getFirstNonPHIIt());
393 Value *ModIsNotNull = B2.CreateIsNotNull(ModVal, "lcmp.mod");
394 AssumeInst *AI = cast<AssumeInst>(B2.CreateAssumption(ModIsNotNull));
395 AC.registerAssumption(AI);
396}
397
398/// Create a clone of the blocks in a loop and connect them together. A new
399/// loop will be created including all cloned blocks, and the iterator of the
400/// new loop switched to count NewIter down to 0.
401/// The cloned blocks should be inserted between InsertTop and InsertBot.
402/// InsertTop should be new preheader, InsertBot new loop exit.
403/// Returns the new cloned loop that is created.
404static Loop *CloneLoopBlocks(Loop *L, Value *NewIter,
405 const bool UseEpilogRemainder,
406 const bool UnrollRemainder, BasicBlock *InsertTop,
407 BasicBlock *InsertBot, BasicBlock *Preheader,
408 std::vector<BasicBlock *> &NewBlocks,
409 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
410 DominatorTree *DT, LoopInfo *LI, unsigned Count,
411 std::optional<unsigned> OriginalTripCount,
412 BranchProbability OriginalLoopProb) {
413 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
414 BasicBlock *Header = L->getHeader();
415 BasicBlock *Latch = L->getLoopLatch();
416 Function *F = Header->getParent();
417 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
418 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
419 Loop *ParentLoop = L->getParentLoop();
420 NewLoopsMap NewLoops;
421 NewLoops[ParentLoop] = ParentLoop;
422
423 // For each block in the original loop, create a new copy,
424 // and update the value map with the newly created values.
425 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
426 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
427 NewBlocks.push_back(NewBB);
428
429 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
430
431 VMap[*BB] = NewBB;
432 if (Header == *BB) {
433 // For the first block, add a CFG connection to this newly
434 // created block.
435 InsertTop->getTerminator()->setSuccessor(0, NewBB);
436 }
437
438 if (DT) {
439 if (Header == *BB) {
440 // The header is dominated by the preheader.
441 DT->addNewBlock(NewBB, InsertTop);
442 } else {
443 // Copy information from original loop to unrolled loop.
444 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
445 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
446 }
447 }
448
449 if (Latch == *BB) {
450 // For the last block, create a loop back to cloned head.
451 VMap.erase((*BB)->getTerminator());
452 // Use an incrementing IV. Pre-incr/post-incr is backedge/trip count.
453 // Subtle: NewIter can be 0 if we wrapped when computing the trip count,
454 // thus we must compare the post-increment (wrapping) value.
455 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
456 CondBrInst *LatchBR = cast<CondBrInst>(NewBB->getTerminator());
457 IRBuilder<> Builder(LatchBR);
458 PHINode *NewIdx =
459 PHINode::Create(NewIter->getType(), 2, suffix + ".iter");
460 NewIdx->insertBefore(FirstLoopBB->getFirstNonPHIIt());
461 auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
462 auto *One = ConstantInt::get(NewIdx->getType(), 1);
463 Value *IdxNext =
464 Builder.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
465 Value *IdxCmp = Builder.CreateICmpNE(IdxNext, NewIter, NewIdx->getName() + ".cmp");
466 MDNode *BranchWeights = nullptr;
467 if ((OriginalLoopProb.isUnknown() || !UseEpilogRemainder) &&
468 hasBranchWeightMD(*LatchBR)) {
469 uint32_t ExitWeight;
470 uint32_t BackEdgeWeight;
471 if (Count >= 3) {
472 // Note: We do not enter this loop for zero-remainders. The check
473 // is at the end of the loop. We assume equal distribution between
474 // possible remainders in [1, Count).
475 ExitWeight = 1;
476 BackEdgeWeight = (Count - 2) / 2;
477 } else {
478 // Unnecessary backedge, should never be taken. The conditional
479 // jump should be optimized away later.
480 ExitWeight = 1;
481 BackEdgeWeight = 0;
482 }
483 MDBuilder MDB(Builder.getContext());
484 BranchWeights = MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
485 }
486 CondBrInst *RemainderLoopLatch =
487 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot, BranchWeights);
488 if (!OriginalLoopProb.isUnknown() && UseEpilogRemainder) {
489 // Compute the total frequency of the original loop body from the
490 // remainder iterations. Once we've reached them, the first of them
491 // always executes, so its frequency and probability are 1.
492 double FreqRemIters = 1;
493 if (Count > 2) {
495 for (unsigned N = Count - 2; N >= 1; --N) {
496 ProbReaching *= probOfNextInRemainder(OriginalLoopProb, N);
497 FreqRemIters += ProbReaching.toDouble();
498 }
499 }
500 // Solve for the loop probability that would produce that frequency.
501 // Sum(i=0..inf)(Prob^i) = 1/(1-Prob) = FreqRemIters.
502 BranchProbability Prob =
503 BranchProbability::getBranchProbability(1 - 1 / FreqRemIters);
504 setBranchProbability(RemainderLoopLatch, Prob, /*ForFirstTarget=*/true);
505 }
506 NewIdx->addIncoming(Zero, InsertTop);
507 NewIdx->addIncoming(IdxNext, NewBB);
508 LatchBR->eraseFromParent();
509 }
510 }
511
512 // Change the incoming values to the ones defined in the preheader or
513 // cloned loop.
514 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
515 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
516 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
517 NewPHI->setIncomingBlock(idx, InsertTop);
518 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
519 idx = NewPHI->getBasicBlockIndex(Latch);
520 Value *InVal = NewPHI->getIncomingValue(idx);
521 NewPHI->setIncomingBlock(idx, NewLatch);
522 if (Value *V = VMap.lookup(InVal))
523 NewPHI->setIncomingValue(idx, V);
524 }
525
526 Loop *NewLoop = NewLoops[L];
527 assert(NewLoop && "L should have been cloned");
528
529 if (OriginalTripCount && UseEpilogRemainder)
530 setLoopEstimatedTripCount(NewLoop, *OriginalTripCount % Count);
531
532 // Add unroll disable metadata to disable future unrolling for this loop.
533 if (!UnrollRemainder)
534 NewLoop->setLoopAlreadyUnrolled();
535 return NewLoop;
536}
537
538/// Returns true if we can profitably unroll the multi-exit loop L.
540 Loop *L, const TargetTransformInfo *TTI,
541 SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
542 bool UseEpilogRemainder) {
543
544 // The main pain point with multi-exit loop unrolling is that once unrolled,
545 // we will not be able to merge all blocks into a straight line code.
546 // There are branches within the unrolled loop that go to the OtherExits.
547 // The second point is the increase in code size, but this is true
548 // irrespective of multiple exits.
549
550 // Note: Both the heuristics below are coarse grained. We are essentially
551 // enabling unrolling of loops that have a single side exit other than the
552 // normal LatchExit (i.e. exiting into a deoptimize block).
553 // The heuristics considered are:
554 // 1. low number of branches in the unrolled version.
555 // 2. high predictability of these extra branches.
556 // We avoid unrolling loops that have more than two exiting blocks. This
557 // limits the total number of branches in the unrolled loop to be atmost
558 // the unroll factor (since one of the exiting blocks is the latch block).
559 SmallVector<BasicBlock*, 4> ExitingBlocks;
560 L->getExitingBlocks(ExitingBlocks);
561 if (ExitingBlocks.size() > 2)
562 return false;
563
564 // Allow unrolling of loops with no non latch exit blocks.
565 if (OtherExits.size() == 0)
566 return true;
567
568 if (OtherExits.size() != 1)
569 return false;
570
571 // When UnrollRuntimeOtherExitPredictable is specified, we assume the other
572 // exit branch is predictable even if it has no deoptimize call.
574 return true;
575
576 // The second heuristic is that L has one exit other than the latchexit and
577 // that exit is highly unlikely.
578 if (TTI) {
579 BasicBlock *LatchBB = L->getLoopLatch();
580 assert(LatchBB && "Expected loop to have a latch");
581 BasicBlock *NonLatchExitingBlock =
582 (ExitingBlocks[0] == LatchBB) ? ExitingBlocks[1] : ExitingBlocks[0];
583 auto BranchProb =
584 llvm::getBranchProbability(NonLatchExitingBlock, OtherExits[0]);
585 // If BranchProbability could not be extracted (returns unknown), then
586 // don't return and do the check for deopt block.
587 if (!BranchProb.isUnknown()) {
588 auto Threshold = TTI->getPredictableBranchThreshold().getCompl();
589 return BranchProb < Threshold;
590 }
591 }
592
593 // We know that deoptimize blocks are rarely taken, which also implies the
594 // branch leading to the deoptimize block is highly unlikely.
595 return OtherExits[0]->getPostdominatingDeoptimizeCall();
596 // TODO: These can be fine-tuned further to consider code size or deopt states
597 // that are captured by the deoptimize exit block.
598 // Also, we can extend this to support more cases, if we actually
599 // know of kinds of multiexit loops that would benefit from unrolling.
600}
601
602/// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
603/// accounting for the possibility of unsigned overflow in the 2s complement
604/// domain. Preconditions:
605/// 1) TripCount = BECount + 1 (allowing overflow)
606/// 2) Log2(Count) <= BitWidth(BECount)
608 Value *TripCount, unsigned Count) {
609 // Note that TripCount is BECount + 1.
610 if (isPowerOf2_32(Count))
611 // If the expression is zero, then either:
612 // 1. There are no iterations to be run in the prolog/epilog loop.
613 // OR
614 // 2. The addition computing TripCount overflowed.
615 //
616 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
617 // the number of iterations that remain to be run in the original loop is a
618 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
619 // precondition of this method).
620 return B.CreateAnd(TripCount, Count - 1, "xtraiter");
621
622 // As (BECount + 1) can potentially unsigned overflow we count
623 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
624 Constant *CountC = ConstantInt::get(BECount->getType(), Count);
625 Value *ModValTmp = B.CreateURem(BECount, CountC);
626 Value *ModValAdd = B.CreateAdd(ModValTmp,
627 ConstantInt::get(ModValTmp->getType(), 1));
628 // At that point (BECount % Count) + 1 could be equal to Count.
629 // To handle this case we need to take mod by Count one more time.
630 return B.CreateURem(ModValAdd, CountC, "xtraiter");
631}
632
633
634/// Insert code in the prolog/epilog code when unrolling a loop with a
635/// run-time trip-count.
636///
637/// This method assumes that the loop unroll factor is total number
638/// of loop bodies in the loop after unrolling. (Some folks refer
639/// to the unroll factor as the number of *extra* copies added).
640/// We assume also that the loop unroll factor is a power-of-two. So, after
641/// unrolling the loop, the number of loop bodies executed is 2,
642/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
643/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
644/// the switch instruction is generated.
645///
646/// ***Prolog case***
647/// extraiters = tripcount % loopfactor
648/// if (extraiters == 0) jump Loop:
649/// else jump Prol:
650/// Prol: LoopBody;
651/// extraiters -= 1 // Omitted if unroll factor is 2.
652/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
653/// if (tripcount < loopfactor) jump End:
654/// Loop:
655/// ...
656/// End:
657///
658/// ***Epilog case***
659/// extraiters = tripcount % loopfactor
660/// if (tripcount < loopfactor) jump LoopExit:
661/// unroll_iters = tripcount - extraiters
662/// Loop: LoopBody; (executes unroll_iter times);
663/// unroll_iter -= 1
664/// if (unroll_iter != 0) jump Loop:
665/// LoopExit:
666/// if (extraiters == 0) jump EpilExit:
667/// Epil: LoopBody; (executes extraiters times)
668/// extraiters -= 1 // Omitted if unroll factor is 2.
669/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
670/// EpilExit:
671
673 Loop *L, unsigned Count, bool AllowExpensiveTripCount,
674 bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV,
676 const TargetTransformInfo *TTI, bool PreserveLCSSA,
677 unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit,
678 Loop **ResultLoop, std::optional<unsigned> OriginalTripCount,
679 BranchProbability OriginalLoopProb) {
680 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
681 LLVM_DEBUG(L->dump());
682 LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
683 : dbgs() << "Using prolog remainder.\n");
684
685 // Make sure the loop is in canonical form.
686 if (!L->isLoopSimplifyForm()) {
687 LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
688 return false;
689 }
690
691 // Guaranteed by LoopSimplifyForm.
692 BasicBlock *Latch = L->getLoopLatch();
693 BasicBlock *Header = L->getHeader();
694
695 CondBrInst *LatchBR = dyn_cast<CondBrInst>(Latch->getTerminator());
696
697 if (!LatchBR) {
698 // The loop-rotate pass can be helpful to avoid this in many cases.
700 dbgs()
701 << "Loop latch not terminated by a conditional branch.\n");
702 return false;
703 }
704
705 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
706 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
707
708 if (L->contains(LatchExit)) {
709 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
710 // targets of the Latch be an exit block out of the loop.
712 dbgs()
713 << "One of the loop latch successors must be the exit block.\n");
714 return false;
715 }
716
717 // These are exit blocks other than the target of the latch exiting block.
719 L->getUniqueNonLatchExitBlocks(OtherExits);
720 // Support only single exit and exiting block unless multi-exit loop
721 // unrolling is enabled.
722 if (!L->getExitingBlock() || OtherExits.size()) {
723 // We rely on LCSSA form being preserved when the exit blocks are transformed.
724 // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
725 if (!PreserveLCSSA)
726 return false;
727
728 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
729 if (UnrollRuntimeMultiExit.getNumOccurrences()) {
731 return false;
732 } else {
733 // Otherwise perform multi-exit unrolling, if either the target indicates
734 // it is profitable or the general profitability heuristics apply.
735 if (!RuntimeUnrollMultiExit &&
737 L, TTI, OtherExits, LatchExit, UseEpilogRemainder)) {
738 LLVM_DEBUG(dbgs() << "Multiple exit/exiting blocks in loop and "
739 "multi-exit unrolling not enabled!\n");
740 return false;
741 }
742 }
743 }
744 // Use Scalar Evolution to compute the trip count. This allows more loops to
745 // be unrolled than relying on induction var simplification.
746 if (!SE)
747 return false;
748
749 // Only unroll loops with a computable trip count.
750 // We calculate the backedge count by using getExitCount on the Latch block,
751 // which is proven to be the only exiting block in this loop. This is same as
752 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
753 // exiting blocks).
754 const SCEV *BECountSC = SE->getExitCount(L, Latch);
755 if (isa<SCEVCouldNotCompute>(BECountSC)) {
756 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
757 return false;
758 }
759
760 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
761
762 // Add 1 since the backedge count doesn't include the first loop iteration.
763 // (Note that overflow can occur, this is handled explicitly below)
764 const SCEV *TripCountSC =
765 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
766 if (isa<SCEVCouldNotCompute>(TripCountSC)) {
767 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
768 return false;
769 }
770
771 BasicBlock *PreHeader = L->getLoopPreheader();
772 Instruction *PreHeaderBR = PreHeader->getTerminator();
773 SCEVExpander Expander(*SE, "loop-unroll");
774 if (!AllowExpensiveTripCount &&
775 Expander.isHighCostExpansion(TripCountSC, L, SCEVExpansionBudget, TTI,
776 PreHeaderBR)) {
777 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
778 return false;
779 }
780
781 // This constraint lets us deal with an overflowing trip count easily; see the
782 // comment on ModVal below.
783 if (Log2_32(Count) > BEWidth) {
785 dbgs()
786 << "Count failed constraint on overflow trip count calculation.\n");
787 return false;
788 }
789
790 // Loop structure is the following:
791 //
792 // PreHeader
793 // Header
794 // ...
795 // Latch
796 // LatchExit
797
798 BasicBlock *NewPreHeader;
799 BasicBlock *NewExit = nullptr;
800 BasicBlock *PrologExit = nullptr;
801 BasicBlock *EpilogPreHeader = nullptr;
802 BasicBlock *PrologPreHeader = nullptr;
803
804 if (UseEpilogRemainder) {
805 // If epilog remainder
806 // Split PreHeader to insert a branch around loop for unrolling.
807 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
808 NewPreHeader->setName(PreHeader->getName() + ".new");
809 // Split LatchExit to create phi nodes from branch above.
810 NewExit = SplitBlockPredecessors(LatchExit, {Latch}, ".unr-lcssa", DT, LI,
811 nullptr, PreserveLCSSA);
812 // NewExit gets its DebugLoc from LatchExit, which is not part of the
813 // original Loop.
814 // Fix this by setting Loop's DebugLoc to NewExit.
815 auto *NewExitTerminator = NewExit->getTerminator();
816 NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
817 // Split NewExit to insert epilog remainder loop.
818 EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
819 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
820
821 // If the latch exits from multiple level of nested loops, then
822 // by assumption there must be another loop exit which branches to the
823 // outer loop and we must adjust the loop for the newly inserted blocks
824 // to account for the fact that our epilogue is still in the same outer
825 // loop. Note that this leaves loopinfo temporarily out of sync with the
826 // CFG until the actual epilogue loop is inserted.
827 if (auto *ParentL = L->getParentLoop())
828 if (LI->getLoopFor(LatchExit) != ParentL) {
829 LI->removeBlock(NewExit);
830 ParentL->addBasicBlockToLoop(NewExit, *LI);
831 LI->removeBlock(EpilogPreHeader);
832 ParentL->addBasicBlockToLoop(EpilogPreHeader, *LI);
833 }
834
835 } else {
836 // If prolog remainder
837 // Split the original preheader twice to insert prolog remainder loop
838 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
839 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
840 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
841 DT, LI);
842 PrologExit->setName(Header->getName() + ".prol.loopexit");
843 // Split PrologExit to get NewPreHeader.
844 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
845 NewPreHeader->setName(PreHeader->getName() + ".new");
846 }
847 // Loop structure should be the following:
848 // Epilog Prolog
849 //
850 // PreHeader PreHeader
851 // *NewPreHeader *PrologPreHeader
852 // Header *PrologExit
853 // ... *NewPreHeader
854 // Latch Header
855 // *NewExit ...
856 // *EpilogPreHeader Latch
857 // LatchExit LatchExit
858
859 // Calculate conditions for branch around loop for unrolling
860 // in epilog case and around prolog remainder loop in prolog case.
861 // Compute the number of extra iterations required, which is:
862 // extra iterations = run-time trip count % loop unroll factor
863 PreHeaderBR = PreHeader->getTerminator();
864 IRBuilder<> B(PreHeaderBR);
865 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
866 PreHeaderBR);
867 Value *BECount;
868 // If there are other exits before the latch, that may cause the latch exit
869 // branch to never be executed, and the latch exit count may be poison.
870 // In this case, freeze the TripCount and base BECount on the frozen
871 // TripCount. We will introduce two branches using these values, and it's
872 // important that they see a consistent value (which would not be guaranteed
873 // if were frozen independently.)
874 if ((!OtherExits.empty() || !SE->loopHasNoAbnormalExits(L)) &&
875 !isGuaranteedNotToBeUndefOrPoison(TripCount, AC, PreHeaderBR, DT)) {
876 TripCount = B.CreateFreeze(TripCount);
877 BECount =
878 B.CreateAdd(TripCount, Constant::getAllOnesValue(TripCount->getType()));
879 } else {
880 // If we don't need to freeze, use SCEVExpander for BECount as well, to
881 // allow slightly better value reuse.
882 BECount =
883 Expander.expandCodeFor(BECountSC, BECountSC->getType(), PreHeaderBR);
884 }
885
886 Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count);
887
888 Value *BranchVal =
889 UseEpilogRemainder ? B.CreateICmpULT(BECount,
890 ConstantInt::get(BECount->getType(),
891 Count - 1)) :
892 B.CreateIsNotNull(ModVal, "lcmp.mod");
893 BasicBlock *RemainderLoop =
894 UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
895 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
896 // Branch to either remainder (extra iterations) loop or unrolling loop.
897 MDNode *BranchWeights = nullptr;
898 if ((OriginalLoopProb.isUnknown() || !UseEpilogRemainder) &&
899 hasBranchWeightMD(*Latch->getTerminator())) {
900 // Assume loop is nearly always entered.
901 MDBuilder MDB(B.getContext());
902 BranchWeights = MDB.createBranchWeights(EpilogHeaderWeights);
903 }
904 CondBrInst *UnrollingLoopGuard =
905 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop, BranchWeights);
906 if (!OriginalLoopProb.isUnknown() && UseEpilogRemainder) {
907 // The original loop's first iteration always happens. Compute the
908 // probability of the original loop executing Count-1 iterations after that
909 // to complete the first iteration of the unrolled loop.
910 BranchProbability ProbOne = OriginalLoopProb;
911 BranchProbability ProbRest = ProbOne.pow(Count - 1);
912 setBranchProbability(UnrollingLoopGuard, ProbRest,
913 /*ForFirstTarget=*/false);
914 }
915 PreHeaderBR->eraseFromParent();
916 if (DT) {
917 if (UseEpilogRemainder)
918 DT->changeImmediateDominator(EpilogPreHeader, PreHeader);
919 else
920 DT->changeImmediateDominator(PrologExit, PreHeader);
921 }
922 Function *F = Header->getParent();
923 // Get an ordered list of blocks in the loop to help with the ordering of the
924 // cloned blocks in the prolog/epilog code
925 LoopBlocksDFS LoopBlocks(L);
926 LoopBlocks.perform(LI);
927
928 //
929 // For each extra loop iteration, create a copy of the loop's basic blocks
930 // and generate a condition that branches to the copy depending on the
931 // number of 'left over' iterations.
932 //
933 std::vector<BasicBlock *> NewBlocks;
935
936 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
937 // the loop, otherwise we create a cloned loop to execute the extra
938 // iterations. This function adds the appropriate CFG connections.
939 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
940 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
941 Loop *remainderLoop =
942 CloneLoopBlocks(L, ModVal, UseEpilogRemainder, UnrollRemainder, InsertTop,
943 InsertBot, NewPreHeader, NewBlocks, LoopBlocks, VMap, DT,
944 LI, Count, OriginalTripCount, OriginalLoopProb);
945
946 // Insert the cloned blocks into the function.
947 F->splice(InsertBot->getIterator(), F, NewBlocks[0]->getIterator(), F->end());
948
949 // Now the loop blocks are cloned and the other exiting blocks from the
950 // remainder are connected to the original Loop's exit blocks. The remaining
951 // work is to update the phi nodes in the original loop, and take in the
952 // values from the cloned region.
953 for (auto *BB : OtherExits) {
954 // Given we preserve LCSSA form, we know that the values used outside the
955 // loop will be used through these phi nodes at the exit blocks that are
956 // transformed below.
957 for (PHINode &PN : BB->phis()) {
958 unsigned oldNumOperands = PN.getNumIncomingValues();
959 // Add the incoming values from the remainder code to the end of the phi
960 // node.
961 for (unsigned i = 0; i < oldNumOperands; i++){
962 auto *PredBB =PN.getIncomingBlock(i);
963 if (PredBB == Latch)
964 // The latch exit is handled separately, see connectX
965 continue;
966 if (!L->contains(PredBB))
967 // Even if we had dedicated exits, the code above inserted an
968 // extra branch which can reach the latch exit.
969 continue;
970
971 auto *V = PN.getIncomingValue(i);
973 if (L->contains(I))
974 V = VMap.lookup(I);
975 PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB]));
976 }
977 }
978#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
979 for (BasicBlock *SuccBB : successors(BB)) {
980 assert(!(llvm::is_contained(OtherExits, SuccBB) || SuccBB == LatchExit) &&
981 "Breaks the definition of dedicated exits!");
982 }
983#endif
984 }
985
986 // Update the immediate dominator of the exit blocks and blocks that are
987 // reachable from the exit blocks. This is needed because we now have paths
988 // from both the original loop and the remainder code reaching the exit
989 // blocks. While the IDom of these exit blocks were from the original loop,
990 // now the IDom is the preheader (which decides whether the original loop or
991 // remainder code should run) unless the block still has just the original
992 // predecessor (such as NewExit in the case of an epilog remainder).
993 if (DT && !L->getExitingBlock()) {
994 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
995 // NB! We have to examine the dom children of all loop blocks, not just
996 // those which are the IDom of the exit blocks. This is because blocks
997 // reachable from the exit blocks can have their IDom as the nearest common
998 // dominator of the exit blocks.
999 for (auto *BB : L->blocks()) {
1000 auto *DomNodeBB = DT->getNode(BB);
1001 for (auto *DomChild : DomNodeBB->children()) {
1002 auto *DomChildBB = DomChild->getBlock();
1003 if (!L->contains(LI->getLoopFor(DomChildBB)) &&
1004 DomChildBB->getUniquePredecessor() != BB)
1005 ChildrenToUpdate.push_back(DomChildBB);
1006 }
1007 }
1008 for (auto *BB : ChildrenToUpdate)
1009 DT->changeImmediateDominator(BB, PreHeader);
1010 }
1011
1012 // Loop structure should be the following:
1013 // Epilog Prolog
1014 //
1015 // PreHeader PreHeader
1016 // NewPreHeader PrologPreHeader
1017 // Header PrologHeader
1018 // ... ...
1019 // Latch PrologLatch
1020 // NewExit PrologExit
1021 // EpilogPreHeader NewPreHeader
1022 // EpilogHeader Header
1023 // ... ...
1024 // EpilogLatch Latch
1025 // LatchExit LatchExit
1026
1027 // Rewrite the cloned instruction operands to use the values created when the
1028 // clone is created.
1029 for (BasicBlock *BB : NewBlocks) {
1030 Module *M = BB->getModule();
1031 for (Instruction &I : *BB) {
1032 RemapInstruction(&I, VMap,
1034 RemapDbgRecordRange(M, I.getDbgRecordRange(), VMap,
1036 }
1037 }
1038
1039 if (UseEpilogRemainder) {
1040 // Connect the epilog code to the original loop and update the
1041 // PHI functions.
1042 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, EpilogPreHeader,
1043 NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE, Count, *AC,
1044 OriginalLoopProb);
1045
1046 // Update counter in loop for unrolling.
1047 // Use an incrementing IV. Pre-incr/post-incr is backedge/trip count.
1048 // Subtle: TestVal can be 0 if we wrapped when computing the trip count,
1049 // thus we must compare the post-increment (wrapping) value.
1050 IRBuilder<> B2(NewPreHeader->getTerminator());
1051 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
1052 CondBrInst *LatchBR = cast<CondBrInst>(Latch->getTerminator());
1053 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter");
1054 NewIdx->insertBefore(Header->getFirstNonPHIIt());
1055 B2.SetInsertPoint(LatchBR);
1056 auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
1057 auto *One = ConstantInt::get(NewIdx->getType(), 1);
1058 Value *IdxNext = B2.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
1059 auto Pred = LatchBR->getSuccessor(0) == Header ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
1060 Value *IdxCmp = B2.CreateICmp(Pred, IdxNext, TestVal, NewIdx->getName() + ".ncmp");
1061 NewIdx->addIncoming(Zero, NewPreHeader);
1062 NewIdx->addIncoming(IdxNext, Latch);
1063 LatchBR->setCondition(IdxCmp);
1064 } else {
1065 // Connect the prolog code to the original loop and update the
1066 // PHI functions.
1067 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
1068 NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE);
1069 }
1070
1071 // If this loop is nested, then the loop unroller changes the code in the any
1072 // of its parent loops, so the Scalar Evolution pass needs to be run again.
1073 SE->forgetTopmostLoop(L);
1074
1075 // Verify that the Dom Tree and Loop Info are correct.
1076#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
1077 if (DT) {
1078 assert(DT->verify(DominatorTree::VerificationLevel::Full));
1079 LI->verify();
1080 }
1081#endif
1082
1083 // For unroll factor 2 remainder loop will have 1 iteration.
1084 if (Count == 2 && DT && LI && SE) {
1085 // TODO: This code could probably be pulled out into a helper function
1086 // (e.g. breakLoopBackedgeAndSimplify) and reused in loop-deletion.
1087 BasicBlock *RemainderLatch = remainderLoop->getLoopLatch();
1088 assert(RemainderLatch);
1089 SmallVector<BasicBlock *> RemainderBlocks(remainderLoop->getBlocks());
1090 breakLoopBackedge(remainderLoop, *DT, *SE, *LI, nullptr);
1091 remainderLoop = nullptr;
1092
1093 // Simplify loop values after breaking the backedge
1094 const DataLayout &DL = L->getHeader()->getDataLayout();
1096 for (BasicBlock *BB : RemainderBlocks) {
1097 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
1098 if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
1099 if (LI->replacementPreservesLCSSAForm(&Inst, V))
1100 Inst.replaceAllUsesWith(V);
1101 if (isInstructionTriviallyDead(&Inst))
1102 DeadInsts.emplace_back(&Inst);
1103 }
1104 // We can't do recursive deletion until we're done iterating, as we might
1105 // have a phi which (potentially indirectly) uses instructions later in
1106 // the block we're iterating through.
1108 }
1109
1110 // Merge latch into exit block.
1111 auto *ExitBB = RemainderLatch->getSingleSuccessor();
1112 assert(ExitBB && "required after breaking cond br backedge");
1113 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1114 MergeBlockIntoPredecessor(ExitBB, &DTU, LI);
1115 }
1116
1117 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
1118 // cannot rely on the LoopUnrollPass to do this because it only does
1119 // canonicalization for parent/subloops and not the sibling loops.
1120 if (OtherExits.size() > 0) {
1121 // Generate dedicated exit blocks for the original loop, to preserve
1122 // LoopSimplifyForm.
1123 formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
1124 // Generate dedicated exit blocks for the remainder loop if one exists, to
1125 // preserve LoopSimplifyForm.
1126 if (remainderLoop)
1127 formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
1128 }
1129
1130 auto UnrollResult = LoopUnrollResult::Unmodified;
1131 if (remainderLoop && UnrollRemainder) {
1132 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
1134 ULO.Count = Count - 1;
1135 ULO.Force = false;
1136 ULO.Runtime = false;
1137 ULO.AllowExpensiveTripCount = false;
1138 ULO.UnrollRemainder = false;
1139 ULO.ForgetAllSCEV = ForgetAllSCEV;
1141 "A loop with a convergence heart does not allow runtime unrolling.");
1142 UnrollResult = UnrollLoop(remainderLoop, ULO, LI, SE, DT, AC, TTI,
1143 /*ORE*/ nullptr, PreserveLCSSA);
1144 }
1145
1146 if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
1147 *ResultLoop = remainderLoop;
1148 NumRuntimeUnrolled++;
1149 return true;
1150}
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 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, BranchProbability OriginalLoopProb)
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 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, std::optional< unsigned > OriginalTripCount, BranchProbability OriginalLoopProb)
Create a clone of the blocks in a loop and connect them together.
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, const TargetTransformInfo *TTI, 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 BranchProbability probOfNextInRemainder(BranchProbability OriginalLoopProb, unsigned N)
Assume, due to our position in the remainder loop or its guard, anywhere from 0 to N more iterations ...
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:54
#define I(x, y, z)
Definition MD5.cpp:57
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:119
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:515
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; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static constexpr BranchProbability getOne()
LLVM_ABI BranchProbability pow(unsigned N) const
Compute pow(Probability, N).
BranchProbability getCompl() const
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Conditional Branch instruction.
void setCondition(Value *V)
BasicBlock * getSuccessor(unsigned i) const
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:64
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:122
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...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
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 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.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
LLVM_ABI void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() 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:466
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
Definition LoopInfo.cpp:595
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:1069
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(SCEVUse 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.
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< SCEVUse > &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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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:189
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
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 BranchProbability getBranchProbability(CondBrInst *B, bool ForFirstTarget)
Based on branch weight metadata, return either:
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:522
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:643
auto successors(const MachineBasicBlock *BB)
SmallDenseMap< const Loop *, Loop *, 4 > NewLoopsMap
Definition UnrollLoop.h:41
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:633
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:326
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:280
LLVM_ABI void setBranchProbability(CondBrInst *B, BranchProbability P, bool ForFirstTarget)
Set branch weight metadata for B to indicate that P and 1 - P are the probabilities of control flowin...
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:209
@ 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:547
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...
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 BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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:61
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
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, std::optional< unsigned > EstimatedLoopInvocationWeight=std::nullopt)
Set llvm.loop.estimated_trip_count with the value EstimatedTripCount in the loop metadata of L.
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:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
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 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, std::optional< unsigned > OriginalTripCount=std::nullopt, BranchProbability OriginalLoopProb=BranchProbability::getUnknown())
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
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.
#define N