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