1 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements some loop unrolling utilities for loops with run-time
11 // trip counts.  See LoopUnroll.cpp for unrolling loops with compile-time
12 // trip counts.
13 //
14 // The functions in this file are used to generate extra code when the
15 // run-time trip count modulo the unroll factor is not 0.  When this is the
16 // case, we need to generate code to execute these 'left over' iterations.
17 //
18 // The current strategy generates an if-then-else sequence prior to the
19 // unrolled loop to execute the 'left over' iterations before or after the
20 // unrolled loop.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/LoopIterator.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpander.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
39 #include "llvm/Transforms/Utils/LoopUtils.h"
40 #include "llvm/Transforms/Utils/UnrollLoop.h"
41 #include <algorithm>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "loop-unroll"
46 
47 STATISTIC(NumRuntimeUnrolled,
48           "Number of loops unrolled with run-time trip counts");
49 static cl::opt<bool> UnrollRuntimeMultiExit(
50     "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
51     cl::desc("Allow runtime unrolling for loops with multiple exits, when "
52              "epilog is generated"));
53 
54 /// Connect the unrolling prolog code to the original loop.
55 /// The unrolling prolog code contains code to execute the
56 /// 'extra' iterations if the run-time trip count modulo the
57 /// unroll count is non-zero.
58 ///
59 /// This function performs the following:
60 /// - Create PHI nodes at prolog end block to combine values
61 ///   that exit the prolog code and jump around the prolog.
62 /// - Add a PHI operand to a PHI node at the loop exit block
63 ///   for values that exit the prolog and go around the loop.
64 /// - Branch around the original loop if the trip count is less
65 ///   than the unroll factor.
66 ///
67 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
68                           BasicBlock *PrologExit,
69                           BasicBlock *OriginalLoopLatchExit,
70                           BasicBlock *PreHeader, BasicBlock *NewPreHeader,
71                           ValueToValueMapTy &VMap, DominatorTree *DT,
72                           LoopInfo *LI, bool PreserveLCSSA) {
73   BasicBlock *Latch = L->getLoopLatch();
74   assert(Latch && "Loop must have a latch");
75   BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
76 
77   // Create a PHI node for each outgoing value from the original loop
78   // (which means it is an outgoing value from the prolog code too).
79   // The new PHI node is inserted in the prolog end basic block.
80   // The new PHI node value is added as an operand of a PHI node in either
81   // the loop header or the loop exit block.
82   for (BasicBlock *Succ : successors(Latch)) {
83     for (Instruction &BBI : *Succ) {
84       PHINode *PN = dyn_cast<PHINode>(&BBI);
85       // Exit when we passed all PHI nodes.
86       if (!PN)
87         break;
88       // Add a new PHI node to the prolog end block and add the
89       // appropriate incoming values.
90       PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
91                                        PrologExit->getFirstNonPHI());
92       // Adding a value to the new PHI node from the original loop preheader.
93       // This is the value that skips all the prolog code.
94       if (L->contains(PN)) {
95         NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader),
96                            PreHeader);
97       } else {
98         NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
99       }
100 
101       Value *V = PN->getIncomingValueForBlock(Latch);
102       if (Instruction *I = dyn_cast<Instruction>(V)) {
103         if (L->contains(I)) {
104           V = VMap.lookup(I);
105         }
106       }
107       // Adding a value to the new PHI node from the last prolog block
108       // that was created.
109       NewPN->addIncoming(V, PrologLatch);
110 
111       // Update the existing PHI node operand with the value from the
112       // new PHI node.  How this is done depends on if the existing
113       // PHI node is in the original loop block, or the exit block.
114       if (L->contains(PN)) {
115         PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN);
116       } else {
117         PN->addIncoming(NewPN, PrologExit);
118       }
119     }
120   }
121 
122   // Make sure that created prolog loop is in simplified form
123   SmallVector<BasicBlock *, 4> PrologExitPreds;
124   Loop *PrologLoop = LI->getLoopFor(PrologLatch);
125   if (PrologLoop) {
126     for (BasicBlock *PredBB : predecessors(PrologExit))
127       if (PrologLoop->contains(PredBB))
128         PrologExitPreds.push_back(PredBB);
129 
130     SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
131                            PreserveLCSSA);
132   }
133 
134   // Create a branch around the original loop, which is taken if there are no
135   // iterations remaining to be executed after running the prologue.
136   Instruction *InsertPt = PrologExit->getTerminator();
137   IRBuilder<> B(InsertPt);
138 
139   assert(Count != 0 && "nonsensical Count!");
140 
141   // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
142   // This means %xtraiter is (BECount + 1) and all of the iterations of this
143   // loop were executed by the prologue.  Note that if BECount <u (Count - 1)
144   // then (BECount + 1) cannot unsigned-overflow.
145   Value *BrLoopExit =
146       B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
147   // Split the exit to maintain loop canonicalization guarantees
148   SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
149   SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
150                          PreserveLCSSA);
151   // Add the branch to the exit block (around the unrolled loop)
152   B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
153   InsertPt->eraseFromParent();
154   if (DT)
155     DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
156 }
157 
158 /// Connect the unrolling epilog code to the original loop.
159 /// The unrolling epilog code contains code to execute the
160 /// 'extra' iterations if the run-time trip count modulo the
161 /// unroll count is non-zero.
162 ///
163 /// This function performs the following:
164 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
165 /// - Create PHI nodes at the unrolling loop exit to combine
166 ///   values that exit the unrolling loop code and jump around it.
167 /// - Update PHI operands in the epilog loop by the new PHI nodes
168 /// - Branch around the epilog loop if extra iters (ModVal) is zero.
169 ///
170 static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
171                           BasicBlock *Exit, BasicBlock *PreHeader,
172                           BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
173                           ValueToValueMapTy &VMap, DominatorTree *DT,
174                           LoopInfo *LI, bool PreserveLCSSA)  {
175   BasicBlock *Latch = L->getLoopLatch();
176   assert(Latch && "Loop must have a latch");
177   BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
178 
179   // Loop structure should be the following:
180   //
181   // PreHeader
182   // NewPreHeader
183   //   Header
184   //   ...
185   //   Latch
186   // NewExit (PN)
187   // EpilogPreHeader
188   //   EpilogHeader
189   //   ...
190   //   EpilogLatch
191   // Exit (EpilogPN)
192 
193   // Update PHI nodes at NewExit and Exit.
194   for (Instruction &BBI : *NewExit) {
195     PHINode *PN = dyn_cast<PHINode>(&BBI);
196     // Exit when we passed all PHI nodes.
197     if (!PN)
198       break;
199     // PN should be used in another PHI located in Exit block as
200     // Exit was split by SplitBlockPredecessors into Exit and NewExit
201     // Basicaly it should look like:
202     // NewExit:
203     //   PN = PHI [I, Latch]
204     // ...
205     // Exit:
206     //   EpilogPN = PHI [PN, EpilogPreHeader]
207     //
208     // There is EpilogPreHeader incoming block instead of NewExit as
209     // NewExit was spilt 1 more time to get EpilogPreHeader.
210     assert(PN->hasOneUse() && "The phi should have 1 use");
211     PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser());
212     assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
213 
214     // Add incoming PreHeader from branch around the Loop
215     PN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
216 
217     Value *V = PN->getIncomingValueForBlock(Latch);
218     Instruction *I = dyn_cast<Instruction>(V);
219     if (I && L->contains(I))
220       // If value comes from an instruction in the loop add VMap value.
221       V = VMap.lookup(I);
222     // For the instruction out of the loop, constant or undefined value
223     // insert value itself.
224     EpilogPN->addIncoming(V, EpilogLatch);
225 
226     assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
227           "EpilogPN should have EpilogPreHeader incoming block");
228     // Change EpilogPreHeader incoming block to NewExit.
229     EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
230                                NewExit);
231     // Now PHIs should look like:
232     // NewExit:
233     //   PN = PHI [I, Latch], [undef, PreHeader]
234     // ...
235     // Exit:
236     //   EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
237   }
238 
239   // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
240   // Update corresponding PHI nodes in epilog loop.
241   for (BasicBlock *Succ : successors(Latch)) {
242     // Skip this as we already updated phis in exit blocks.
243     if (!L->contains(Succ))
244       continue;
245     for (Instruction &BBI : *Succ) {
246       PHINode *PN = dyn_cast<PHINode>(&BBI);
247       // Exit when we passed all PHI nodes.
248       if (!PN)
249         break;
250       // Add new PHI nodes to the loop exit block and update epilog
251       // PHIs with the new PHI values.
252       PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
253                                        NewExit->getFirstNonPHI());
254       // Adding a value to the new PHI node from the unrolling loop preheader.
255       NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader);
256       // Adding a value to the new PHI node from the unrolling loop latch.
257       NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch);
258 
259       // Update the existing PHI node operand with the value from the new PHI
260       // node.  Corresponding instruction in epilog loop should be PHI.
261       PHINode *VPN = cast<PHINode>(VMap[&BBI]);
262       VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
263     }
264   }
265 
266   Instruction *InsertPt = NewExit->getTerminator();
267   IRBuilder<> B(InsertPt);
268   Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
269   assert(Exit && "Loop must have a single exit block only");
270   // Split the epilogue exit to maintain loop canonicalization guarantees
271   SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
272   SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI,
273                          PreserveLCSSA);
274   // Add the branch to the exit block (around the unrolling loop)
275   B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
276   InsertPt->eraseFromParent();
277   if (DT)
278     DT->changeImmediateDominator(Exit, NewExit);
279 
280   // Split the main loop exit to maintain canonicalization guarantees.
281   SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
282   SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI,
283                          PreserveLCSSA);
284 }
285 
286 /// Create a clone of the blocks in a loop and connect them together.
287 /// If CreateRemainderLoop is false, loop structure will not be cloned,
288 /// otherwise a new loop will be created including all cloned blocks, and the
289 /// iterator of it switches to count NewIter down to 0.
290 /// The cloned blocks should be inserted between InsertTop and InsertBot.
291 /// If loop structure is cloned InsertTop should be new preheader, InsertBot
292 /// new loop exit.
293 /// Return the new cloned loop that is created when CreateRemainderLoop is true.
294 static Loop *
295 CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
296                 const bool UseEpilogRemainder, BasicBlock *InsertTop,
297                 BasicBlock *InsertBot, BasicBlock *Preheader,
298                 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
299                 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
300   StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
301   BasicBlock *Header = L->getHeader();
302   BasicBlock *Latch = L->getLoopLatch();
303   Function *F = Header->getParent();
304   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
305   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
306   Loop *ParentLoop = L->getParentLoop();
307   NewLoopsMap NewLoops;
308   NewLoops[ParentLoop] = ParentLoop;
309   if (!CreateRemainderLoop)
310     NewLoops[L] = ParentLoop;
311 
312   // For each block in the original loop, create a new copy,
313   // and update the value map with the newly created values.
314   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
315     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
316     NewBlocks.push_back(NewBB);
317 
318     // If we're unrolling the outermost loop, there's no remainder loop,
319     // and this block isn't in a nested loop, then the new block is not
320     // in any loop. Otherwise, add it to loopinfo.
321     if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
322       addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
323 
324     VMap[*BB] = NewBB;
325     if (Header == *BB) {
326       // For the first block, add a CFG connection to this newly
327       // created block.
328       InsertTop->getTerminator()->setSuccessor(0, NewBB);
329     }
330 
331     if (DT) {
332       if (Header == *BB) {
333         // The header is dominated by the preheader.
334         DT->addNewBlock(NewBB, InsertTop);
335       } else {
336         // Copy information from original loop to unrolled loop.
337         BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
338         DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
339       }
340     }
341 
342     if (Latch == *BB) {
343       // For the last block, if CreateRemainderLoop is false, create a direct
344       // jump to InsertBot. If not, create a loop back to cloned head.
345       VMap.erase((*BB)->getTerminator());
346       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
347       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
348       IRBuilder<> Builder(LatchBR);
349       if (!CreateRemainderLoop) {
350         Builder.CreateBr(InsertBot);
351       } else {
352         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
353                                           suffix + ".iter",
354                                           FirstLoopBB->getFirstNonPHI());
355         Value *IdxSub =
356             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
357                               NewIdx->getName() + ".sub");
358         Value *IdxCmp =
359             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
360         Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
361         NewIdx->addIncoming(NewIter, InsertTop);
362         NewIdx->addIncoming(IdxSub, NewBB);
363       }
364       LatchBR->eraseFromParent();
365     }
366   }
367 
368   // Change the incoming values to the ones defined in the preheader or
369   // cloned loop.
370   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
371     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
372     if (!CreateRemainderLoop) {
373       if (UseEpilogRemainder) {
374         unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
375         NewPHI->setIncomingBlock(idx, InsertTop);
376         NewPHI->removeIncomingValue(Latch, false);
377       } else {
378         VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
379         cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
380       }
381     } else {
382       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
383       NewPHI->setIncomingBlock(idx, InsertTop);
384       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
385       idx = NewPHI->getBasicBlockIndex(Latch);
386       Value *InVal = NewPHI->getIncomingValue(idx);
387       NewPHI->setIncomingBlock(idx, NewLatch);
388       if (Value *V = VMap.lookup(InVal))
389         NewPHI->setIncomingValue(idx, V);
390     }
391   }
392   if (CreateRemainderLoop) {
393     Loop *NewLoop = NewLoops[L];
394     assert(NewLoop && "L should have been cloned");
395     // Add unroll disable metadata to disable future unrolling for this loop.
396     SmallVector<Metadata *, 4> MDs;
397     // Reserve first location for self reference to the LoopID metadata node.
398     MDs.push_back(nullptr);
399     MDNode *LoopID = NewLoop->getLoopID();
400     if (LoopID) {
401       // First remove any existing loop unrolling metadata.
402       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
403         bool IsUnrollMetadata = false;
404         MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
405         if (MD) {
406           const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
407           IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
408         }
409         if (!IsUnrollMetadata)
410           MDs.push_back(LoopID->getOperand(i));
411       }
412     }
413 
414     LLVMContext &Context = NewLoop->getHeader()->getContext();
415     SmallVector<Metadata *, 1> DisableOperands;
416     DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
417     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
418     MDs.push_back(DisableNode);
419 
420     MDNode *NewLoopID = MDNode::get(Context, MDs);
421     // Set operand 0 to refer to the loop id itself.
422     NewLoopID->replaceOperandWith(0, NewLoopID);
423     NewLoop->setLoopID(NewLoopID);
424     return NewLoop;
425   }
426   else
427     return nullptr;
428 }
429 
430 /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
431 /// is populated with all the loop exit blocks other than the LatchExit block.
432 static bool
433 canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits,
434                              BasicBlock *LatchExit, bool PreserveLCSSA,
435                              bool UseEpilogRemainder) {
436 
437   // Support runtime unrolling for multiple exit blocks and multiple exiting
438   // blocks.
439   if (!UnrollRuntimeMultiExit)
440     return false;
441   // Even if runtime multi exit is enabled, we currently have some correctness
442   // constrains in unrolling a multi-exit loop.
443   // We rely on LCSSA form being preserved when the exit blocks are transformed.
444   if (!PreserveLCSSA)
445     return false;
446   SmallVector<BasicBlock *, 4> Exits;
447   L->getUniqueExitBlocks(Exits);
448   for (auto *BB : Exits)
449     if (BB != LatchExit)
450       OtherExits.push_back(BB);
451 
452   // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
453   // UnrollRuntimeMultiExit is true. This will need updating the logic in
454   // connectEpilog/connectProlog.
455   if (!LatchExit->getSinglePredecessor()) {
456     DEBUG(dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
457                     "predecessor.\n");
458     return false;
459   }
460   // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
461   // and L is an inner loop. This is because in presence of multiple exits, the
462   // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
463   // outer loop. This is automatically handled in the prolog case, so we do not
464   // have that bug in prolog generation.
465   if (UseEpilogRemainder && L->getParentLoop())
466     return false;
467 
468   // All constraints have been satisfied.
469   return true;
470 }
471 
472 
473 
474 /// Insert code in the prolog/epilog code when unrolling a loop with a
475 /// run-time trip-count.
476 ///
477 /// This method assumes that the loop unroll factor is total number
478 /// of loop bodies in the loop after unrolling. (Some folks refer
479 /// to the unroll factor as the number of *extra* copies added).
480 /// We assume also that the loop unroll factor is a power-of-two. So, after
481 /// unrolling the loop, the number of loop bodies executed is 2,
482 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
483 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
484 /// the switch instruction is generated.
485 ///
486 /// ***Prolog case***
487 ///        extraiters = tripcount % loopfactor
488 ///        if (extraiters == 0) jump Loop:
489 ///        else jump Prol:
490 /// Prol:  LoopBody;
491 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
492 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
493 ///        if (tripcount < loopfactor) jump End:
494 /// Loop:
495 /// ...
496 /// End:
497 ///
498 /// ***Epilog case***
499 ///        extraiters = tripcount % loopfactor
500 ///        if (tripcount < loopfactor) jump LoopExit:
501 ///        unroll_iters = tripcount - extraiters
502 /// Loop:  LoopBody; (executes unroll_iter times);
503 ///        unroll_iter -= 1
504 ///        if (unroll_iter != 0) jump Loop:
505 /// LoopExit:
506 ///        if (extraiters == 0) jump EpilExit:
507 /// Epil:  LoopBody; (executes extraiters times)
508 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
509 ///        if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
510 /// EpilExit:
511 
512 bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
513                                       bool AllowExpensiveTripCount,
514                                       bool UseEpilogRemainder,
515                                       LoopInfo *LI, ScalarEvolution *SE,
516                                       DominatorTree *DT, bool PreserveLCSSA) {
517   DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
518   DEBUG(L->dump());
519 
520   // Make sure the loop is in canonical form.
521   if (!L->isLoopSimplifyForm()) {
522     DEBUG(dbgs() << "Not in simplify form!\n");
523     return false;
524   }
525 
526   // Guaranteed by LoopSimplifyForm.
527   BasicBlock *Latch = L->getLoopLatch();
528   BasicBlock *Header = L->getHeader();
529 
530   BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
531   unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
532   BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
533   // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
534   // targets of the Latch be an exit block out of the loop. This needs
535   // to be guaranteed by the callers of UnrollRuntimeLoopRemainder.
536   assert(!L->contains(LatchExit) &&
537          "one of the loop latch successors should be the exit block!");
538   // These are exit blocks other than the target of the latch exiting block.
539   SmallVector<BasicBlock *, 4> OtherExits;
540   bool isMultiExitUnrollingEnabled = canSafelyUnrollMultiExitLoop(
541       L, OtherExits, LatchExit, PreserveLCSSA, UseEpilogRemainder);
542   // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
543   if (!isMultiExitUnrollingEnabled &&
544       (!L->getExitingBlock() || OtherExits.size())) {
545     DEBUG(
546         dbgs()
547         << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
548            "enabled!\n");
549     return false;
550   }
551   // Use Scalar Evolution to compute the trip count. This allows more loops to
552   // be unrolled than relying on induction var simplification.
553   if (!SE)
554     return false;
555 
556   // Only unroll loops with a computable trip count, and the trip count needs
557   // to be an int value (allowing a pointer type is a TODO item).
558   // We calculate the backedge count by using getExitCount on the Latch block,
559   // which is proven to be the only exiting block in this loop. This is same as
560   // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
561   // exiting blocks).
562   const SCEV *BECountSC = SE->getExitCount(L, Latch);
563   if (isa<SCEVCouldNotCompute>(BECountSC) ||
564       !BECountSC->getType()->isIntegerTy()) {
565     DEBUG(dbgs() << "Could not compute exit block SCEV\n");
566     return false;
567   }
568 
569   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
570 
571   // Add 1 since the backedge count doesn't include the first loop iteration.
572   const SCEV *TripCountSC =
573       SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
574   if (isa<SCEVCouldNotCompute>(TripCountSC)) {
575     DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
576     return false;
577   }
578 
579   BasicBlock *PreHeader = L->getLoopPreheader();
580   BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
581   const DataLayout &DL = Header->getModule()->getDataLayout();
582   SCEVExpander Expander(*SE, DL, "loop-unroll");
583   if (!AllowExpensiveTripCount &&
584       Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
585     DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
586     return false;
587   }
588 
589   // This constraint lets us deal with an overflowing trip count easily; see the
590   // comment on ModVal below.
591   if (Log2_32(Count) > BEWidth) {
592     DEBUG(dbgs()
593           << "Count failed constraint on overflow trip count calculation.\n");
594     return false;
595   }
596 
597   // Loop structure is the following:
598   //
599   // PreHeader
600   //   Header
601   //   ...
602   //   Latch
603   // LatchExit
604 
605   BasicBlock *NewPreHeader;
606   BasicBlock *NewExit = nullptr;
607   BasicBlock *PrologExit = nullptr;
608   BasicBlock *EpilogPreHeader = nullptr;
609   BasicBlock *PrologPreHeader = nullptr;
610 
611   if (UseEpilogRemainder) {
612     // If epilog remainder
613     // Split PreHeader to insert a branch around loop for unrolling.
614     NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
615     NewPreHeader->setName(PreHeader->getName() + ".new");
616     // Split LatchExit to create phi nodes from branch above.
617     SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
618     NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa",
619                                      DT, LI, PreserveLCSSA);
620     // Split NewExit to insert epilog remainder loop.
621     EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI);
622     EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
623   } else {
624     // If prolog remainder
625     // Split the original preheader twice to insert prolog remainder loop
626     PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
627     PrologPreHeader->setName(Header->getName() + ".prol.preheader");
628     PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
629                             DT, LI);
630     PrologExit->setName(Header->getName() + ".prol.loopexit");
631     // Split PrologExit to get NewPreHeader.
632     NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
633     NewPreHeader->setName(PreHeader->getName() + ".new");
634   }
635   // Loop structure should be the following:
636   //  Epilog             Prolog
637   //
638   // PreHeader         PreHeader
639   // *NewPreHeader     *PrologPreHeader
640   //   Header          *PrologExit
641   //   ...             *NewPreHeader
642   //   Latch             Header
643   // *NewExit            ...
644   // *EpilogPreHeader    Latch
645   // LatchExit              LatchExit
646 
647   // Calculate conditions for branch around loop for unrolling
648   // in epilog case and around prolog remainder loop in prolog case.
649   // Compute the number of extra iterations required, which is:
650   //  extra iterations = run-time trip count % loop unroll factor
651   PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
652   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
653                                             PreHeaderBR);
654   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
655                                           PreHeaderBR);
656   IRBuilder<> B(PreHeaderBR);
657   Value *ModVal;
658   // Calculate ModVal = (BECount + 1) % Count.
659   // Note that TripCount is BECount + 1.
660   if (isPowerOf2_32(Count)) {
661     // When Count is power of 2 we don't BECount for epilog case, however we'll
662     // need it for a branch around unrolling loop for prolog case.
663     ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
664     //  1. There are no iterations to be run in the prolog/epilog loop.
665     // OR
666     //  2. The addition computing TripCount overflowed.
667     //
668     // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
669     // the number of iterations that remain to be run in the original loop is a
670     // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
671     // explicitly check this above).
672   } else {
673     // As (BECount + 1) can potentially unsigned overflow we count
674     // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
675     Value *ModValTmp = B.CreateURem(BECount,
676                                     ConstantInt::get(BECount->getType(),
677                                                      Count));
678     Value *ModValAdd = B.CreateAdd(ModValTmp,
679                                    ConstantInt::get(ModValTmp->getType(), 1));
680     // At that point (BECount % Count) + 1 could be equal to Count.
681     // To handle this case we need to take mod by Count one more time.
682     ModVal = B.CreateURem(ModValAdd,
683                           ConstantInt::get(BECount->getType(), Count),
684                           "xtraiter");
685   }
686   Value *BranchVal =
687       UseEpilogRemainder ? B.CreateICmpULT(BECount,
688                                            ConstantInt::get(BECount->getType(),
689                                                             Count - 1)) :
690                            B.CreateIsNotNull(ModVal, "lcmp.mod");
691   BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
692   BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
693   // Branch to either remainder (extra iterations) loop or unrolling loop.
694   B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
695   PreHeaderBR->eraseFromParent();
696   if (DT) {
697     if (UseEpilogRemainder)
698       DT->changeImmediateDominator(NewExit, PreHeader);
699     else
700       DT->changeImmediateDominator(PrologExit, PreHeader);
701   }
702   Function *F = Header->getParent();
703   // Get an ordered list of blocks in the loop to help with the ordering of the
704   // cloned blocks in the prolog/epilog code
705   LoopBlocksDFS LoopBlocks(L);
706   LoopBlocks.perform(LI);
707 
708   //
709   // For each extra loop iteration, create a copy of the loop's basic blocks
710   // and generate a condition that branches to the copy depending on the
711   // number of 'left over' iterations.
712   //
713   std::vector<BasicBlock *> NewBlocks;
714   ValueToValueMapTy VMap;
715 
716   // For unroll factor 2 remainder loop will have 1 iterations.
717   // Do not create 1 iteration loop.
718   bool CreateRemainderLoop = (Count != 2);
719 
720   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
721   // the loop, otherwise we create a cloned loop to execute the extra
722   // iterations. This function adds the appropriate CFG connections.
723   BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
724   BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
725   Loop *remainderLoop = CloneLoopBlocks(
726       L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop, InsertBot,
727       NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
728 
729   // Insert the cloned blocks into the function.
730   F->getBasicBlockList().splice(InsertBot->getIterator(),
731                                 F->getBasicBlockList(),
732                                 NewBlocks[0]->getIterator(),
733                                 F->end());
734 
735   // Now the loop blocks are cloned and the other exiting blocks from the
736   // remainder are connected to the original Loop's exit blocks. The remaining
737   // work is to update the phi nodes in the original loop, and take in the
738   // values from the cloned region. Also update the dominator info for
739   // OtherExits, since we have new edges into OtherExits.
740   for (auto *BB : OtherExits) {
741    for (auto &II : *BB) {
742 
743      // Given we preserve LCSSA form, we know that the values used outside the
744      // loop will be used through these phi nodes at the exit blocks that are
745      // transformed below.
746      if (!isa<PHINode>(II))
747        break;
748      PHINode *Phi = cast<PHINode>(&II);
749      unsigned oldNumOperands = Phi->getNumIncomingValues();
750      // Add the incoming values from the remainder code to the end of the phi
751      // node.
752      for (unsigned i =0; i < oldNumOperands; i++){
753        Value *newVal = VMap[Phi->getIncomingValue(i)];
754        // newVal can be a constant or derived from values outside the loop, and
755        // hence need not have a VMap value.
756        if (!newVal)
757          newVal = Phi->getIncomingValue(i);
758        Phi->addIncoming(newVal,
759                            cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
760      }
761    }
762    // Update the dominator info because the immediate dominator is no longer the
763    // header of the original Loop. BB has edges both from L and remainder code.
764    // Since the preheader determines which loop is run (L or directly jump to
765    // the remainder code), we set the immediate dominator as the preheader.
766    if (DT)
767      DT->changeImmediateDominator(BB, PreHeader);
768   }
769 
770   // Loop structure should be the following:
771   //  Epilog             Prolog
772   //
773   // PreHeader         PreHeader
774   // NewPreHeader      PrologPreHeader
775   //   Header            PrologHeader
776   //   ...               ...
777   //   Latch             PrologLatch
778   // NewExit           PrologExit
779   // EpilogPreHeader   NewPreHeader
780   //   EpilogHeader      Header
781   //   ...               ...
782   //   EpilogLatch       Latch
783   // LatchExit              LatchExit
784 
785   // Rewrite the cloned instruction operands to use the values created when the
786   // clone is created.
787   for (BasicBlock *BB : NewBlocks) {
788     for (Instruction &I : *BB) {
789       RemapInstruction(&I, VMap,
790                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
791     }
792   }
793 
794   if (UseEpilogRemainder) {
795     // Connect the epilog code to the original loop and update the
796     // PHI functions.
797     ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
798                   EpilogPreHeader, NewPreHeader, VMap, DT, LI,
799                   PreserveLCSSA);
800 
801     // Update counter in loop for unrolling.
802     // I should be multiply of Count.
803     IRBuilder<> B2(NewPreHeader->getTerminator());
804     Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
805     BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
806     B2.SetInsertPoint(LatchBR);
807     PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
808                                       Header->getFirstNonPHI());
809     Value *IdxSub =
810         B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
811                      NewIdx->getName() + ".nsub");
812     Value *IdxCmp;
813     if (LatchBR->getSuccessor(0) == Header)
814       IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
815     else
816       IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
817     NewIdx->addIncoming(TestVal, NewPreHeader);
818     NewIdx->addIncoming(IdxSub, Latch);
819     LatchBR->setCondition(IdxCmp);
820   } else {
821     // Connect the prolog code to the original loop and update the
822     // PHI functions.
823     ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
824                   NewPreHeader, VMap, DT, LI, PreserveLCSSA);
825   }
826 
827   // If this loop is nested, then the loop unroller changes the code in the
828   // parent loop, so the Scalar Evolution pass needs to be run again.
829   if (Loop *ParentLoop = L->getParentLoop())
830     SE->forgetLoop(ParentLoop);
831 
832   // Canonicalize to LoopSimplifyForm both original and remainder loops. We
833   // cannot rely on the LoopUnrollPass to do this because it only does
834   // canonicalization for parent/subloops and not the sibling loops.
835   if (OtherExits.size() > 0) {
836     // Generate dedicated exit blocks for the original loop, to preserve
837     // LoopSimplifyForm.
838     formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA);
839     // Generate dedicated exit blocks for the remainder loop if one exists, to
840     // preserve LoopSimplifyForm.
841     if (remainderLoop)
842       formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA);
843   }
844 
845   NumRuntimeUnrolled++;
846   return true;
847 }
848