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