xref: /llvm-project/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp (revision 9a35f19e3e851e5a62499416e276ff9ae13b7b07)
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"
24 #include "llvm/Analysis/DomTreeUpdater.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/LoopIterator.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Analysis/ValueTracking.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"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/LoopUtils.h"
40 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
41 #include "llvm/Transforms/Utils/UnrollLoop.h"
42 #include <algorithm>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "loop-unroll"
47 
48 STATISTIC(NumRuntimeUnrolled,
49           "Number of loops unrolled with run-time trip counts");
50 static cl::opt<bool> UnrollRuntimeMultiExit(
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"));
54 static cl::opt<bool> UnrollRuntimeOtherExitPredictable(
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 /// Connect the unrolling prolog code to the original loop.
59 /// The unrolling prolog code contains code to execute the
60 /// 'extra' iterations if the run-time trip count modulo the
61 /// unroll count is non-zero.
62 ///
63 /// This function performs the following:
64 /// - Create PHI nodes at prolog end block to combine values
65 ///   that exit the prolog code and jump around the prolog.
66 /// - Add a PHI operand to a PHI node at the loop exit block
67 ///   for values that exit the prolog and go around the loop.
68 /// - Branch around the original loop if the trip count is less
69 ///   than the unroll factor.
70 ///
71 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
72                           BasicBlock *PrologExit,
73                           BasicBlock *OriginalLoopLatchExit,
74                           BasicBlock *PreHeader, BasicBlock *NewPreHeader,
75                           ValueToValueMapTy &VMap, DominatorTree *DT,
76                           LoopInfo *LI, bool PreserveLCSSA) {
77   // Loop structure should be the following:
78   // Preheader
79   //  PrologHeader
80   //  ...
81   //  PrologLatch
82   //  PrologExit
83   //   NewPreheader
84   //    Header
85   //    ...
86   //    Latch
87   //      LatchExit
88   BasicBlock *Latch = L->getLoopLatch();
89   assert(Latch && "Loop must have a latch");
90   BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
91 
92   // Create a PHI node for each outgoing value from the original loop
93   // (which means it is an outgoing value from the prolog code too).
94   // The new PHI node is inserted in the prolog end basic block.
95   // The new PHI node value is added as an operand of a PHI node in either
96   // the loop header or the loop exit block.
97   for (BasicBlock *Succ : successors(Latch)) {
98     for (PHINode &PN : Succ->phis()) {
99       // Add a new PHI node to the prolog end block and add the
100       // appropriate incoming values.
101       // TODO: This code assumes that the PrologExit (or the LatchExit block for
102       // prolog loop) contains only one predecessor from the loop, i.e. the
103       // PrologLatch. When supporting multiple-exiting block loops, we can have
104       // two or more blocks that have the LatchExit as the target in the
105       // original loop.
106       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
107                                        PrologExit->getFirstNonPHI());
108       // Adding a value to the new PHI node from the original loop preheader.
109       // This is the value that skips all the prolog code.
110       if (L->contains(&PN)) {
111         // Succ is loop header.
112         NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
113                            PreHeader);
114       } else {
115         // Succ is LatchExit.
116         NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader);
117       }
118 
119       Value *V = PN.getIncomingValueForBlock(Latch);
120       if (Instruction *I = dyn_cast<Instruction>(V)) {
121         if (L->contains(I)) {
122           V = VMap.lookup(I);
123         }
124       }
125       // Adding a value to the new PHI node from the last prolog block
126       // that was created.
127       NewPN->addIncoming(V, PrologLatch);
128 
129       // Update the existing PHI node operand with the value from the
130       // new PHI node.  How this is done depends on if the existing
131       // PHI node is in the original loop block, or the exit block.
132       if (L->contains(&PN))
133         PN.setIncomingValueForBlock(NewPreHeader, NewPN);
134       else
135         PN.addIncoming(NewPN, PrologExit);
136     }
137   }
138 
139   // Make sure that created prolog loop is in simplified form
140   SmallVector<BasicBlock *, 4> PrologExitPreds;
141   Loop *PrologLoop = LI->getLoopFor(PrologLatch);
142   if (PrologLoop) {
143     for (BasicBlock *PredBB : predecessors(PrologExit))
144       if (PrologLoop->contains(PredBB))
145         PrologExitPreds.push_back(PredBB);
146 
147     SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
148                            nullptr, PreserveLCSSA);
149   }
150 
151   // Create a branch around the original loop, which is taken if there are no
152   // iterations remaining to be executed after running the prologue.
153   Instruction *InsertPt = PrologExit->getTerminator();
154   IRBuilder<> B(InsertPt);
155 
156   assert(Count != 0 && "nonsensical Count!");
157 
158   // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
159   // This means %xtraiter is (BECount + 1) and all of the iterations of this
160   // loop were executed by the prologue.  Note that if BECount <u (Count - 1)
161   // then (BECount + 1) cannot unsigned-overflow.
162   Value *BrLoopExit =
163       B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
164   // Split the exit to maintain loop canonicalization guarantees
165   SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
166   SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
167                          nullptr, PreserveLCSSA);
168   // Add the branch to the exit block (around the unrolled loop)
169   B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
170   InsertPt->eraseFromParent();
171   if (DT) {
172     auto *NewDom = DT->findNearestCommonDominator(OriginalLoopLatchExit,
173                                                   PrologExit);
174     DT->changeImmediateDominator(OriginalLoopLatchExit, NewDom);
175   }
176 }
177 
178 /// Connect the unrolling epilog code to the original loop.
179 /// The unrolling epilog code contains code to execute the
180 /// 'extra' iterations if the run-time trip count modulo the
181 /// unroll count is non-zero.
182 ///
183 /// This function performs the following:
184 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
185 /// - Create PHI nodes at the unrolling loop exit to combine
186 ///   values that exit the unrolling loop code and jump around it.
187 /// - Update PHI operands in the epilog loop by the new PHI nodes
188 /// - Branch around the epilog loop if extra iters (ModVal) is zero.
189 ///
190 static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
191                           BasicBlock *Exit, BasicBlock *PreHeader,
192                           BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
193                           ValueToValueMapTy &VMap, DominatorTree *DT,
194                           LoopInfo *LI, bool PreserveLCSSA,
195                           ScalarEvolution &SE) {
196   BasicBlock *Latch = L->getLoopLatch();
197   assert(Latch && "Loop must have a latch");
198   BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
199 
200   // Loop structure should be the following:
201   //
202   // PreHeader
203   // NewPreHeader
204   //   Header
205   //   ...
206   //   Latch
207   // NewExit (PN)
208   // EpilogPreHeader
209   //   EpilogHeader
210   //   ...
211   //   EpilogLatch
212   // Exit (EpilogPN)
213 
214   // Update PHI nodes at NewExit and Exit.
215   for (PHINode &PN : NewExit->phis()) {
216     // PN should be used in another PHI located in Exit block as
217     // Exit was split by SplitBlockPredecessors into Exit and NewExit
218     // Basicaly it should look like:
219     // NewExit:
220     //   PN = PHI [I, Latch]
221     // ...
222     // Exit:
223     //   EpilogPN = PHI [PN, EpilogPreHeader], [X, Exit2], [Y, Exit2.epil]
224     //
225     // Exits from non-latch blocks point to the original exit block and the
226     // epilogue edges have already been added.
227     //
228     // There is EpilogPreHeader incoming block instead of NewExit as
229     // NewExit was spilt 1 more time to get EpilogPreHeader.
230     assert(PN.hasOneUse() && "The phi should have 1 use");
231     PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
232     assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
233 
234     // Add incoming PreHeader from branch around the Loop
235     PN.addIncoming(UndefValue::get(PN.getType()), PreHeader);
236     SE.forgetValue(&PN);
237 
238     Value *V = PN.getIncomingValueForBlock(Latch);
239     Instruction *I = dyn_cast<Instruction>(V);
240     if (I && L->contains(I))
241       // If value comes from an instruction in the loop add VMap value.
242       V = VMap.lookup(I);
243     // For the instruction out of the loop, constant or undefined value
244     // insert value itself.
245     EpilogPN->addIncoming(V, EpilogLatch);
246 
247     assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
248           "EpilogPN should have EpilogPreHeader incoming block");
249     // Change EpilogPreHeader incoming block to NewExit.
250     EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
251                                NewExit);
252     // Now PHIs should look like:
253     // NewExit:
254     //   PN = PHI [I, Latch], [undef, PreHeader]
255     // ...
256     // Exit:
257     //   EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
258   }
259 
260   // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
261   // Update corresponding PHI nodes in epilog loop.
262   for (BasicBlock *Succ : successors(Latch)) {
263     // Skip this as we already updated phis in exit blocks.
264     if (!L->contains(Succ))
265       continue;
266     for (PHINode &PN : Succ->phis()) {
267       // Add new PHI nodes to the loop exit block and update epilog
268       // PHIs with the new PHI values.
269       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
270                                        NewExit->getFirstNonPHI());
271       // Adding a value to the new PHI node from the unrolling loop preheader.
272       NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
273       // Adding a value to the new PHI node from the unrolling loop latch.
274       NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
275 
276       // Update the existing PHI node operand with the value from the new PHI
277       // node.  Corresponding instruction in epilog loop should be PHI.
278       PHINode *VPN = cast<PHINode>(VMap[&PN]);
279       VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN);
280     }
281   }
282 
283   Instruction *InsertPt = NewExit->getTerminator();
284   IRBuilder<> B(InsertPt);
285   Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
286   assert(Exit && "Loop must have a single exit block only");
287   // Split the epilogue exit to maintain loop canonicalization guarantees
288   SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
289   SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
290                          PreserveLCSSA);
291   // Add the branch to the exit block (around the unrolling loop)
292   B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
293   InsertPt->eraseFromParent();
294   if (DT) {
295     auto *NewDom = DT->findNearestCommonDominator(Exit, NewExit);
296     DT->changeImmediateDominator(Exit, NewDom);
297   }
298 
299   // Split the main loop exit to maintain canonicalization guarantees.
300   SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
301   SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
302                          PreserveLCSSA);
303 }
304 
305 /// Create a clone of the blocks in a loop and connect them together. A new
306 /// loop will be created including all cloned blocks, and the iterator of the
307 /// new loop switched to count NewIter down to 0.
308 /// The cloned blocks should be inserted between InsertTop and InsertBot.
309 /// InsertTop should be new preheader, InsertBot new loop exit.
310 /// Returns the new cloned loop that is created.
311 static Loop *
312 CloneLoopBlocks(Loop *L, Value *NewIter, const bool UseEpilogRemainder,
313                 const bool UnrollRemainder,
314                 BasicBlock *InsertTop,
315                 BasicBlock *InsertBot, BasicBlock *Preheader,
316                 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
317                 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
318   StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
319   BasicBlock *Header = L->getHeader();
320   BasicBlock *Latch = L->getLoopLatch();
321   Function *F = Header->getParent();
322   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
323   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
324   Loop *ParentLoop = L->getParentLoop();
325   NewLoopsMap NewLoops;
326   NewLoops[ParentLoop] = ParentLoop;
327 
328   // For each block in the original loop, create a new copy,
329   // and update the value map with the newly created values.
330   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
331     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
332     NewBlocks.push_back(NewBB);
333 
334     addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
335 
336     VMap[*BB] = NewBB;
337     if (Header == *BB) {
338       // For the first block, add a CFG connection to this newly
339       // created block.
340       InsertTop->getTerminator()->setSuccessor(0, NewBB);
341     }
342 
343     if (DT) {
344       if (Header == *BB) {
345         // The header is dominated by the preheader.
346         DT->addNewBlock(NewBB, InsertTop);
347       } else {
348         // Copy information from original loop to unrolled loop.
349         BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
350         DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
351       }
352     }
353 
354     if (Latch == *BB) {
355       // For the last block, create a loop back to cloned head.
356       VMap.erase((*BB)->getTerminator());
357       // Use an incrementing IV.  Pre-incr/post-incr is backedge/trip count.
358       // Subtle: NewIter can be 0 if we wrapped when computing the trip count,
359       // thus we must compare the post-increment (wrapping) value.
360       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
361       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
362       IRBuilder<> Builder(LatchBR);
363       PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
364                                         suffix + ".iter",
365                                         FirstLoopBB->getFirstNonPHI());
366       auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
367       auto *One = ConstantInt::get(NewIdx->getType(), 1);
368       Value *IdxNext = Builder.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
369       Value *IdxCmp = Builder.CreateICmpNE(IdxNext, NewIter, NewIdx->getName() + ".cmp");
370       Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
371       NewIdx->addIncoming(Zero, InsertTop);
372       NewIdx->addIncoming(IdxNext, NewBB);
373       LatchBR->eraseFromParent();
374     }
375   }
376 
377   // Change the incoming values to the ones defined in the preheader or
378   // cloned loop.
379   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
380     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
381     unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
382     NewPHI->setIncomingBlock(idx, InsertTop);
383     BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
384     idx = NewPHI->getBasicBlockIndex(Latch);
385     Value *InVal = NewPHI->getIncomingValue(idx);
386     NewPHI->setIncomingBlock(idx, NewLatch);
387     if (Value *V = VMap.lookup(InVal))
388       NewPHI->setIncomingValue(idx, V);
389   }
390 
391   Loop *NewLoop = NewLoops[L];
392   assert(NewLoop && "L should have been cloned");
393   MDNode *LoopID = NewLoop->getLoopID();
394 
395   // Only add loop metadata if the loop is not going to be completely
396   // unrolled.
397   if (UnrollRemainder)
398     return NewLoop;
399 
400   Optional<MDNode *> NewLoopID = makeFollowupLoopID(
401       LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
402   if (NewLoopID) {
403     NewLoop->setLoopID(NewLoopID.getValue());
404 
405     // Do not setLoopAlreadyUnrolled if loop attributes have been defined
406     // explicitly.
407     return NewLoop;
408   }
409 
410   // Add unroll disable metadata to disable future unrolling for this loop.
411   NewLoop->setLoopAlreadyUnrolled();
412   return NewLoop;
413 }
414 
415 /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
416 /// we return true only if UnrollRuntimeMultiExit is set to true.
417 static bool canProfitablyUnrollMultiExitLoop(
418     Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
419     bool UseEpilogRemainder) {
420 
421   // Priority goes to UnrollRuntimeMultiExit if it's supplied.
422   if (UnrollRuntimeMultiExit.getNumOccurrences())
423     return UnrollRuntimeMultiExit;
424 
425   // The main pain point with multi-exit loop unrolling is that once unrolled,
426   // we will not be able to merge all blocks into a straight line code.
427   // There are branches within the unrolled loop that go to the OtherExits.
428   // The second point is the increase in code size, but this is true
429   // irrespective of multiple exits.
430 
431   // Note: Both the heuristics below are coarse grained. We are essentially
432   // enabling unrolling of loops that have a single side exit other than the
433   // normal LatchExit (i.e. exiting into a deoptimize block).
434   // The heuristics considered are:
435   // 1. low number of branches in the unrolled version.
436   // 2. high predictability of these extra branches.
437   // We avoid unrolling loops that have more than two exiting blocks. This
438   // limits the total number of branches in the unrolled loop to be atmost
439   // the unroll factor (since one of the exiting blocks is the latch block).
440   SmallVector<BasicBlock*, 4> ExitingBlocks;
441   L->getExitingBlocks(ExitingBlocks);
442   if (ExitingBlocks.size() > 2)
443     return false;
444 
445   // Allow unrolling of loops with no non latch exit blocks.
446   if (OtherExits.size() == 0)
447     return true;
448 
449   // The second heuristic is that L has one exit other than the latchexit and
450   // that exit is a deoptimize block. We know that deoptimize blocks are rarely
451   // taken, which also implies the branch leading to the deoptimize block is
452   // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we
453   // assume the other exit branch is predictable even if it has no deoptimize
454   // call.
455   return (OtherExits.size() == 1 &&
456           (UnrollRuntimeOtherExitPredictable ||
457            OtherExits[0]->getTerminatingDeoptimizeCall()));
458   // TODO: These can be fine-tuned further to consider code size or deopt states
459   // that are captured by the deoptimize exit block.
460   // Also, we can extend this to support more cases, if we actually
461   // know of kinds of multiexit loops that would benefit from unrolling.
462 }
463 
464 // Assign the maximum possible trip count as the back edge weight for the
465 // remainder loop if the original loop comes with a branch weight.
466 static void updateLatchBranchWeightsForRemainderLoop(Loop *OrigLoop,
467                                                      Loop *RemainderLoop,
468                                                      uint64_t UnrollFactor) {
469   uint64_t TrueWeight, FalseWeight;
470   BranchInst *LatchBR =
471       cast<BranchInst>(OrigLoop->getLoopLatch()->getTerminator());
472   if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight))
473     return;
474   uint64_t ExitWeight = LatchBR->getSuccessor(0) == OrigLoop->getHeader()
475                             ? FalseWeight
476                             : TrueWeight;
477   assert(UnrollFactor > 1);
478   uint64_t BackEdgeWeight = (UnrollFactor - 1) * ExitWeight;
479   BasicBlock *Header = RemainderLoop->getHeader();
480   BasicBlock *Latch = RemainderLoop->getLoopLatch();
481   auto *RemainderLatchBR = cast<BranchInst>(Latch->getTerminator());
482   unsigned HeaderIdx = (RemainderLatchBR->getSuccessor(0) == Header ? 0 : 1);
483   MDBuilder MDB(RemainderLatchBR->getContext());
484   MDNode *WeightNode =
485     HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
486                 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
487   RemainderLatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
488 }
489 
490 /// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
491 /// accounting for the possibility of unsigned overflow in the 2s complement
492 /// domain. Preconditions:
493 /// 1) TripCount = BECount + 1 (allowing overflow)
494 /// 2) Log2(Count) <= BitWidth(BECount)
495 static Value *CreateTripRemainder(IRBuilder<> &B, Value *BECount,
496                                   Value *TripCount, unsigned Count) {
497   // Note that TripCount is BECount + 1.
498   if (isPowerOf2_32(Count))
499     // If the expression is zero, then either:
500     //  1. There are no iterations to be run in the prolog/epilog loop.
501     // OR
502     //  2. The addition computing TripCount overflowed.
503     //
504     // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
505     // the number of iterations that remain to be run in the original loop is a
506     // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
507     // precondition of this method).
508     return B.CreateAnd(TripCount, Count - 1, "xtraiter");
509 
510   // As (BECount + 1) can potentially unsigned overflow we count
511   // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
512   Constant *CountC = ConstantInt::get(BECount->getType(), Count);
513   Value *ModValTmp = B.CreateURem(BECount, CountC);
514   Value *ModValAdd = B.CreateAdd(ModValTmp,
515                                  ConstantInt::get(ModValTmp->getType(), 1));
516   // At that point (BECount % Count) + 1 could be equal to Count.
517   // To handle this case we need to take mod by Count one more time.
518   return B.CreateURem(ModValAdd, CountC, "xtraiter");
519 }
520 
521 
522 /// Insert code in the prolog/epilog code when unrolling a loop with a
523 /// run-time trip-count.
524 ///
525 /// This method assumes that the loop unroll factor is total number
526 /// of loop bodies in the loop after unrolling. (Some folks refer
527 /// to the unroll factor as the number of *extra* copies added).
528 /// We assume also that the loop unroll factor is a power-of-two. So, after
529 /// unrolling the loop, the number of loop bodies executed is 2,
530 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
531 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
532 /// the switch instruction is generated.
533 ///
534 /// ***Prolog case***
535 ///        extraiters = tripcount % loopfactor
536 ///        if (extraiters == 0) jump Loop:
537 ///        else jump Prol:
538 /// Prol:  LoopBody;
539 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
540 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
541 ///        if (tripcount < loopfactor) jump End:
542 /// Loop:
543 /// ...
544 /// End:
545 ///
546 /// ***Epilog case***
547 ///        extraiters = tripcount % loopfactor
548 ///        if (tripcount < loopfactor) jump LoopExit:
549 ///        unroll_iters = tripcount - extraiters
550 /// Loop:  LoopBody; (executes unroll_iter times);
551 ///        unroll_iter -= 1
552 ///        if (unroll_iter != 0) jump Loop:
553 /// LoopExit:
554 ///        if (extraiters == 0) jump EpilExit:
555 /// Epil:  LoopBody; (executes extraiters times)
556 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
557 ///        if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
558 /// EpilExit:
559 
560 bool llvm::UnrollRuntimeLoopRemainder(
561     Loop *L, unsigned Count, bool AllowExpensiveTripCount,
562     bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV,
563     LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC,
564     const TargetTransformInfo *TTI, bool PreserveLCSSA, Loop **ResultLoop) {
565   LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
566   LLVM_DEBUG(L->dump());
567   LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
568                                 : dbgs() << "Using prolog remainder.\n");
569 
570   // Make sure the loop is in canonical form.
571   if (!L->isLoopSimplifyForm()) {
572     LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
573     return false;
574   }
575 
576   // Guaranteed by LoopSimplifyForm.
577   BasicBlock *Latch = L->getLoopLatch();
578   BasicBlock *Header = L->getHeader();
579 
580   BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
581 
582   if (!LatchBR || LatchBR->isUnconditional()) {
583     // The loop-rotate pass can be helpful to avoid this in many cases.
584     LLVM_DEBUG(
585         dbgs()
586         << "Loop latch not terminated by a conditional branch.\n");
587     return false;
588   }
589 
590   unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
591   BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
592 
593   if (L->contains(LatchExit)) {
594     // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
595     // targets of the Latch be an exit block out of the loop.
596     LLVM_DEBUG(
597         dbgs()
598         << "One of the loop latch successors must be the exit block.\n");
599     return false;
600   }
601 
602   // These are exit blocks other than the target of the latch exiting block.
603   SmallVector<BasicBlock *, 4> OtherExits;
604   L->getUniqueNonLatchExitBlocks(OtherExits);
605   // Support only single exit and exiting block unless multi-exit loop
606   // unrolling is enabled.
607   if (!L->getExitingBlock() || OtherExits.size()) {
608     // We rely on LCSSA form being preserved when the exit blocks are transformed.
609     // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
610     if (!PreserveLCSSA)
611       return false;
612 
613     if (!canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit,
614                                           UseEpilogRemainder)) {
615       LLVM_DEBUG(
616           dbgs()
617           << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
618              "enabled!\n");
619       return false;
620     }
621   }
622   // Use Scalar Evolution to compute the trip count. This allows more loops to
623   // be unrolled than relying on induction var simplification.
624   if (!SE)
625     return false;
626 
627   // Only unroll loops with a computable trip count.
628   // We calculate the backedge count by using getExitCount on the Latch block,
629   // which is proven to be the only exiting block in this loop. This is same as
630   // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
631   // exiting blocks).
632   const SCEV *BECountSC = SE->getExitCount(L, Latch);
633   if (isa<SCEVCouldNotCompute>(BECountSC)) {
634     LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
635     return false;
636   }
637 
638   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
639 
640   // Add 1 since the backedge count doesn't include the first loop iteration.
641   // (Note that overflow can occur, this is handled explicitly below)
642   const SCEV *TripCountSC =
643       SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
644   if (isa<SCEVCouldNotCompute>(TripCountSC)) {
645     LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
646     return false;
647   }
648 
649   BasicBlock *PreHeader = L->getLoopPreheader();
650   BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
651   const DataLayout &DL = Header->getModule()->getDataLayout();
652   SCEVExpander Expander(*SE, DL, "loop-unroll");
653   if (!AllowExpensiveTripCount &&
654       Expander.isHighCostExpansion(TripCountSC, L, SCEVCheapExpansionBudget,
655                                    TTI, PreHeaderBR)) {
656     LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
657     return false;
658   }
659 
660   // This constraint lets us deal with an overflowing trip count easily; see the
661   // comment on ModVal below.
662   if (Log2_32(Count) > BEWidth) {
663     LLVM_DEBUG(
664         dbgs()
665         << "Count failed constraint on overflow trip count calculation.\n");
666     return false;
667   }
668 
669   // Loop structure is the following:
670   //
671   // PreHeader
672   //   Header
673   //   ...
674   //   Latch
675   // LatchExit
676 
677   BasicBlock *NewPreHeader;
678   BasicBlock *NewExit = nullptr;
679   BasicBlock *PrologExit = nullptr;
680   BasicBlock *EpilogPreHeader = nullptr;
681   BasicBlock *PrologPreHeader = nullptr;
682 
683   if (UseEpilogRemainder) {
684     // If epilog remainder
685     // Split PreHeader to insert a branch around loop for unrolling.
686     NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
687     NewPreHeader->setName(PreHeader->getName() + ".new");
688     // Split LatchExit to create phi nodes from branch above.
689     NewExit = SplitBlockPredecessors(LatchExit, {Latch}, ".unr-lcssa", DT, LI,
690                                      nullptr, PreserveLCSSA);
691     // NewExit gets its DebugLoc from LatchExit, which is not part of the
692     // original Loop.
693     // Fix this by setting Loop's DebugLoc to NewExit.
694     auto *NewExitTerminator = NewExit->getTerminator();
695     NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
696     // Split NewExit to insert epilog remainder loop.
697     EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
698     EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
699 
700     // If the latch exits from multiple level of nested loops, then
701     // by assumption there must be another loop exit which branches to the
702     // outer loop and we must adjust the loop for the newly inserted blocks
703     // to account for the fact that our epilogue is still in the same outer
704     // loop. Note that this leaves loopinfo temporarily out of sync with the
705     // CFG until the actual epilogue loop is inserted.
706     if (auto *ParentL = L->getParentLoop())
707       if (LI->getLoopFor(LatchExit) != ParentL) {
708         LI->removeBlock(NewExit);
709         ParentL->addBasicBlockToLoop(NewExit, *LI);
710         LI->removeBlock(EpilogPreHeader);
711         ParentL->addBasicBlockToLoop(EpilogPreHeader, *LI);
712       }
713 
714   } else {
715     // If prolog remainder
716     // Split the original preheader twice to insert prolog remainder loop
717     PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
718     PrologPreHeader->setName(Header->getName() + ".prol.preheader");
719     PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
720                             DT, LI);
721     PrologExit->setName(Header->getName() + ".prol.loopexit");
722     // Split PrologExit to get NewPreHeader.
723     NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
724     NewPreHeader->setName(PreHeader->getName() + ".new");
725   }
726   // Loop structure should be the following:
727   //  Epilog             Prolog
728   //
729   // PreHeader         PreHeader
730   // *NewPreHeader     *PrologPreHeader
731   //   Header          *PrologExit
732   //   ...             *NewPreHeader
733   //   Latch             Header
734   // *NewExit            ...
735   // *EpilogPreHeader    Latch
736   // LatchExit              LatchExit
737 
738   // Calculate conditions for branch around loop for unrolling
739   // in epilog case and around prolog remainder loop in prolog case.
740   // Compute the number of extra iterations required, which is:
741   //  extra iterations = run-time trip count % loop unroll factor
742   PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
743   IRBuilder<> B(PreHeaderBR);
744   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
745                                             PreHeaderBR);
746   Value *BECount;
747   // If there are other exits before the latch, that may cause the latch exit
748   // branch to never be executed, and the latch exit count may be poison.
749   // In this case, freeze the TripCount and base BECount on the frozen
750   // TripCount. We will introduce two branches using these values, and it's
751   // important that they see a consistent value (which would not be guaranteed
752   // if were frozen independently.)
753   if ((!OtherExits.empty() || !SE->loopHasNoAbnormalExits(L)) &&
754       !isGuaranteedNotToBeUndefOrPoison(TripCount, AC, PreHeaderBR, DT)) {
755     TripCount = B.CreateFreeze(TripCount);
756     BECount =
757         B.CreateAdd(TripCount, ConstantInt::get(TripCount->getType(), -1));
758   } else {
759     // If we don't need to freeze, use SCEVExpander for BECount as well, to
760     // allow slightly better value reuse.
761     BECount =
762         Expander.expandCodeFor(BECountSC, BECountSC->getType(), PreHeaderBR);
763   }
764 
765   Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count);
766 
767   Value *BranchVal =
768       UseEpilogRemainder ? B.CreateICmpULT(BECount,
769                                            ConstantInt::get(BECount->getType(),
770                                                             Count - 1)) :
771                            B.CreateIsNotNull(ModVal, "lcmp.mod");
772   BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
773   BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
774   // Branch to either remainder (extra iterations) loop or unrolling loop.
775   B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
776   PreHeaderBR->eraseFromParent();
777   if (DT) {
778     if (UseEpilogRemainder)
779       DT->changeImmediateDominator(NewExit, PreHeader);
780     else
781       DT->changeImmediateDominator(PrologExit, PreHeader);
782   }
783   Function *F = Header->getParent();
784   // Get an ordered list of blocks in the loop to help with the ordering of the
785   // cloned blocks in the prolog/epilog code
786   LoopBlocksDFS LoopBlocks(L);
787   LoopBlocks.perform(LI);
788 
789   //
790   // For each extra loop iteration, create a copy of the loop's basic blocks
791   // and generate a condition that branches to the copy depending on the
792   // number of 'left over' iterations.
793   //
794   std::vector<BasicBlock *> NewBlocks;
795   ValueToValueMapTy VMap;
796 
797   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
798   // the loop, otherwise we create a cloned loop to execute the extra
799   // iterations. This function adds the appropriate CFG connections.
800   BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
801   BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
802   Loop *remainderLoop = CloneLoopBlocks(
803       L, ModVal, UseEpilogRemainder, UnrollRemainder, InsertTop, InsertBot,
804       NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
805 
806   // Assign the maximum possible trip count as the back edge weight for the
807   // remainder loop if the original loop comes with a branch weight.
808   if (remainderLoop && !UnrollRemainder)
809     updateLatchBranchWeightsForRemainderLoop(L, remainderLoop, Count);
810 
811   // Insert the cloned blocks into the function.
812   F->getBasicBlockList().splice(InsertBot->getIterator(),
813                                 F->getBasicBlockList(),
814                                 NewBlocks[0]->getIterator(),
815                                 F->end());
816 
817   // Now the loop blocks are cloned and the other exiting blocks from the
818   // remainder are connected to the original Loop's exit blocks. The remaining
819   // work is to update the phi nodes in the original loop, and take in the
820   // values from the cloned region.
821   for (auto *BB : OtherExits) {
822     // Given we preserve LCSSA form, we know that the values used outside the
823     // loop will be used through these phi nodes at the exit blocks that are
824     // transformed below.
825     for (PHINode &PN : BB->phis()) {
826      unsigned oldNumOperands = PN.getNumIncomingValues();
827      // Add the incoming values from the remainder code to the end of the phi
828      // node.
829      for (unsigned i = 0; i < oldNumOperands; i++){
830        auto *PredBB =PN.getIncomingBlock(i);
831        if (PredBB == Latch)
832          // The latch exit is handled seperately, see connectX
833          continue;
834        if (!L->contains(PredBB))
835          // Even if we had dedicated exits, the code above inserted an
836          // extra branch which can reach the latch exit.
837          continue;
838 
839        auto *V = PN.getIncomingValue(i);
840        if (Instruction *I = dyn_cast<Instruction>(V))
841          if (L->contains(I))
842            V = VMap.lookup(I);
843        PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB]));
844      }
845    }
846 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
847     for (BasicBlock *SuccBB : successors(BB)) {
848       assert(!(llvm::is_contained(OtherExits, SuccBB) || SuccBB == LatchExit) &&
849              "Breaks the definition of dedicated exits!");
850     }
851 #endif
852   }
853 
854   // Update the immediate dominator of the exit blocks and blocks that are
855   // reachable from the exit blocks. This is needed because we now have paths
856   // from both the original loop and the remainder code reaching the exit
857   // blocks. While the IDom of these exit blocks were from the original loop,
858   // now the IDom is the preheader (which decides whether the original loop or
859   // remainder code should run).
860   if (DT && !L->getExitingBlock()) {
861     SmallVector<BasicBlock *, 16> ChildrenToUpdate;
862     // NB! We have to examine the dom children of all loop blocks, not just
863     // those which are the IDom of the exit blocks. This is because blocks
864     // reachable from the exit blocks can have their IDom as the nearest common
865     // dominator of the exit blocks.
866     for (auto *BB : L->blocks()) {
867       auto *DomNodeBB = DT->getNode(BB);
868       for (auto *DomChild : DomNodeBB->children()) {
869         auto *DomChildBB = DomChild->getBlock();
870         if (!L->contains(LI->getLoopFor(DomChildBB)))
871           ChildrenToUpdate.push_back(DomChildBB);
872       }
873     }
874     for (auto *BB : ChildrenToUpdate)
875       DT->changeImmediateDominator(BB, PreHeader);
876   }
877 
878   // Loop structure should be the following:
879   //  Epilog             Prolog
880   //
881   // PreHeader         PreHeader
882   // NewPreHeader      PrologPreHeader
883   //   Header            PrologHeader
884   //   ...               ...
885   //   Latch             PrologLatch
886   // NewExit           PrologExit
887   // EpilogPreHeader   NewPreHeader
888   //   EpilogHeader      Header
889   //   ...               ...
890   //   EpilogLatch       Latch
891   // LatchExit              LatchExit
892 
893   // Rewrite the cloned instruction operands to use the values created when the
894   // clone is created.
895   for (BasicBlock *BB : NewBlocks) {
896     for (Instruction &I : *BB) {
897       RemapInstruction(&I, VMap,
898                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
899     }
900   }
901 
902   if (UseEpilogRemainder) {
903     // Connect the epilog code to the original loop and update the
904     // PHI functions.
905     ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, EpilogPreHeader,
906                   NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE);
907 
908     // Update counter in loop for unrolling.
909     // Use an incrementing IV.  Pre-incr/post-incr is backedge/trip count.
910     // Subtle: TestVal can be 0 if we wrapped when computing the trip count,
911     // thus we must compare the post-increment (wrapping) value.
912     IRBuilder<> B2(NewPreHeader->getTerminator());
913     Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
914     BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
915     PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
916                                       Header->getFirstNonPHI());
917     B2.SetInsertPoint(LatchBR);
918     auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
919     auto *One = ConstantInt::get(NewIdx->getType(), 1);
920     Value *IdxNext = B2.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
921     auto Pred = LatchBR->getSuccessor(0) == Header ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
922     Value *IdxCmp = B2.CreateICmp(Pred, IdxNext, TestVal, NewIdx->getName() + ".ncmp");
923     NewIdx->addIncoming(Zero, NewPreHeader);
924     NewIdx->addIncoming(IdxNext, Latch);
925     LatchBR->setCondition(IdxCmp);
926   } else {
927     // Connect the prolog code to the original loop and update the
928     // PHI functions.
929     ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
930                   NewPreHeader, VMap, DT, LI, PreserveLCSSA);
931   }
932 
933   // If this loop is nested, then the loop unroller changes the code in the any
934   // of its parent loops, so the Scalar Evolution pass needs to be run again.
935   SE->forgetTopmostLoop(L);
936 
937   // Verify that the Dom Tree and Loop Info are correct.
938 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
939   if (DT) {
940     assert(DT->verify(DominatorTree::VerificationLevel::Full));
941     LI->verify(*DT);
942   }
943 #endif
944 
945   // For unroll factor 2 remainder loop will have 1 iteration.
946   if (Count == 2 && DT && LI && SE) {
947     // TODO: This code could probably be pulled out into a helper function
948     // (e.g. breakLoopBackedgeAndSimplify) and reused in loop-deletion.
949     BasicBlock *RemainderLatch = remainderLoop->getLoopLatch();
950     assert(RemainderLatch);
951     SmallVector<BasicBlock*> RemainderBlocks(remainderLoop->getBlocks().begin(),
952                                              remainderLoop->getBlocks().end());
953     breakLoopBackedge(remainderLoop, *DT, *SE, *LI, nullptr);
954     remainderLoop = nullptr;
955 
956     // Simplify loop values after breaking the backedge
957     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
958     SmallVector<WeakTrackingVH, 16> DeadInsts;
959     for (BasicBlock *BB : RemainderBlocks) {
960       for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
961         if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
962           if (LI->replacementPreservesLCSSAForm(&Inst, V))
963             Inst.replaceAllUsesWith(V);
964         if (isInstructionTriviallyDead(&Inst))
965           DeadInsts.emplace_back(&Inst);
966       }
967       // We can't do recursive deletion until we're done iterating, as we might
968       // have a phi which (potentially indirectly) uses instructions later in
969       // the block we're iterating through.
970       RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
971     }
972 
973     // Merge latch into exit block.
974     auto *ExitBB = RemainderLatch->getSingleSuccessor();
975     assert(ExitBB && "required after breaking cond br backedge");
976     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
977     MergeBlockIntoPredecessor(ExitBB, &DTU, LI);
978   }
979 
980   // Canonicalize to LoopSimplifyForm both original and remainder loops. We
981   // cannot rely on the LoopUnrollPass to do this because it only does
982   // canonicalization for parent/subloops and not the sibling loops.
983   if (OtherExits.size() > 0) {
984     // Generate dedicated exit blocks for the original loop, to preserve
985     // LoopSimplifyForm.
986     formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
987     // Generate dedicated exit blocks for the remainder loop if one exists, to
988     // preserve LoopSimplifyForm.
989     if (remainderLoop)
990       formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
991   }
992 
993   auto UnrollResult = LoopUnrollResult::Unmodified;
994   if (remainderLoop && UnrollRemainder) {
995     LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
996     UnrollResult =
997         UnrollLoop(remainderLoop,
998                    {/*Count*/ Count - 1, /*Force*/ false, /*Runtime*/ false,
999                     /*AllowExpensiveTripCount*/ false,
1000                     /*UnrollRemainder*/ false, ForgetAllSCEV},
1001                    LI, SE, DT, AC, TTI, /*ORE*/ nullptr, PreserveLCSSA);
1002   }
1003 
1004   if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
1005     *ResultLoop = remainderLoop;
1006   NumRuntimeUnrolled++;
1007   return true;
1008 }
1009