1 //===-- UnrollLoop.cpp - 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. It does not define any
10 // actual pass or policy, but provides a single function to perform loop
11 // unrolling.
12 //
13 // The process of unrolling can produce extraneous basic blocks linked with
14 // unconditional branches.  This will be corrected in the future.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/LoopIterator.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/LoopSimplify.h"
38 #include "llvm/Transforms/Utils/LoopUtils.h"
39 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
40 #include "llvm/Transforms/Utils/UnrollLoop.h"
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "loop-unroll"
44 
45 // TODO: Should these be here or in LoopUnroll?
46 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
47 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
48 STATISTIC(NumUnrolledWithHeader, "Number of loops unrolled without a "
49                                  "conditional latch (completely or otherwise)");
50 
51 static cl::opt<bool>
52 UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
53                     cl::desc("Allow runtime unrolled loops to be unrolled "
54                              "with epilog instead of prolog."));
55 
56 static cl::opt<bool>
57 UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
58                     cl::desc("Verify domtree after unrolling"),
59 #ifdef EXPENSIVE_CHECKS
60     cl::init(true)
61 #else
62     cl::init(false)
63 #endif
64                     );
65 
66 /// Check if unrolling created a situation where we need to insert phi nodes to
67 /// preserve LCSSA form.
68 /// \param Blocks is a vector of basic blocks representing unrolled loop.
69 /// \param L is the outer loop.
70 /// It's possible that some of the blocks are in L, and some are not. In this
71 /// case, if there is a use is outside L, and definition is inside L, we need to
72 /// insert a phi-node, otherwise LCSSA will be broken.
73 /// The function is just a helper function for llvm::UnrollLoop that returns
74 /// true if this situation occurs, indicating that LCSSA needs to be fixed.
75 static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks,
76                                      LoopInfo *LI) {
77   for (BasicBlock *BB : Blocks) {
78     if (LI->getLoopFor(BB) == L)
79       continue;
80     for (Instruction &I : *BB) {
81       for (Use &U : I.operands()) {
82         if (auto Def = dyn_cast<Instruction>(U)) {
83           Loop *DefLoop = LI->getLoopFor(Def->getParent());
84           if (!DefLoop)
85             continue;
86           if (DefLoop->contains(L))
87             return true;
88         }
89       }
90     }
91   }
92   return false;
93 }
94 
95 /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
96 /// and adds a mapping from the original loop to the new loop to NewLoops.
97 /// Returns nullptr if no new loop was created and a pointer to the
98 /// original loop OriginalBB was part of otherwise.
99 const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
100                                            BasicBlock *ClonedBB, LoopInfo *LI,
101                                            NewLoopsMap &NewLoops) {
102   // Figure out which loop New is in.
103   const Loop *OldLoop = LI->getLoopFor(OriginalBB);
104   assert(OldLoop && "Should (at least) be in the loop being unrolled!");
105 
106   Loop *&NewLoop = NewLoops[OldLoop];
107   if (!NewLoop) {
108     // Found a new sub-loop.
109     assert(OriginalBB == OldLoop->getHeader() &&
110            "Header should be first in RPO");
111 
112     NewLoop = LI->AllocateLoop();
113     Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
114 
115     if (NewLoopParent)
116       NewLoopParent->addChildLoop(NewLoop);
117     else
118       LI->addTopLevelLoop(NewLoop);
119 
120     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
121     return OldLoop;
122   } else {
123     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
124     return nullptr;
125   }
126 }
127 
128 /// The function chooses which type of unroll (epilog or prolog) is more
129 /// profitabale.
130 /// Epilog unroll is more profitable when there is PHI that starts from
131 /// constant.  In this case epilog will leave PHI start from constant,
132 /// but prolog will convert it to non-constant.
133 ///
134 /// loop:
135 ///   PN = PHI [I, Latch], [CI, PreHeader]
136 ///   I = foo(PN)
137 ///   ...
138 ///
139 /// Epilog unroll case.
140 /// loop:
141 ///   PN = PHI [I2, Latch], [CI, PreHeader]
142 ///   I1 = foo(PN)
143 ///   I2 = foo(I1)
144 ///   ...
145 /// Prolog unroll case.
146 ///   NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
147 /// loop:
148 ///   PN = PHI [I2, Latch], [NewPN, PreHeader]
149 ///   I1 = foo(PN)
150 ///   I2 = foo(I1)
151 ///   ...
152 ///
153 static bool isEpilogProfitable(Loop *L) {
154   BasicBlock *PreHeader = L->getLoopPreheader();
155   BasicBlock *Header = L->getHeader();
156   assert(PreHeader && Header);
157   for (const PHINode &PN : Header->phis()) {
158     if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
159       return true;
160   }
161   return false;
162 }
163 
164 /// Perform some cleanup and simplifications on loops after unrolling. It is
165 /// useful to simplify the IV's in the new loop, as well as do a quick
166 /// simplify/dce pass of the instructions.
167 void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
168                                    ScalarEvolution *SE, DominatorTree *DT,
169                                    AssumptionCache *AC) {
170   // Simplify any new induction variables in the partially unrolled loop.
171   if (SE && SimplifyIVs) {
172     SmallVector<WeakTrackingVH, 16> DeadInsts;
173     simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
174 
175     // Aggressively clean up dead instructions that simplifyLoopIVs already
176     // identified. Any remaining should be cleaned up below.
177     while (!DeadInsts.empty()) {
178       Value *V = DeadInsts.pop_back_val();
179       if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
180         RecursivelyDeleteTriviallyDeadInstructions(Inst);
181     }
182   }
183 
184   // At this point, the code is well formed.  We now do a quick sweep over the
185   // inserted code, doing constant propagation and dead code elimination as we
186   // go.
187   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
188   for (BasicBlock *BB : L->getBlocks()) {
189     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
190       Instruction *Inst = &*I++;
191 
192       if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC}))
193         if (LI->replacementPreservesLCSSAForm(Inst, V))
194           Inst->replaceAllUsesWith(V);
195       if (isInstructionTriviallyDead(Inst))
196         BB->getInstList().erase(Inst);
197     }
198   }
199 
200   // TODO: after peeling or unrolling, previously loop variant conditions are
201   // likely to fold to constants, eagerly propagating those here will require
202   // fewer cleanup passes to be run.  Alternatively, a LoopEarlyCSE might be
203   // appropriate.
204 }
205 
206 /// Unroll the given loop by Count. The loop must be in LCSSA form.  Unrolling
207 /// can only fail when the loop's latch block is not terminated by a conditional
208 /// branch instruction. However, if the trip count (and multiple) are not known,
209 /// loop unrolling will mostly produce more code that is no faster.
210 ///
211 /// TripCount is the upper bound of the iteration on which control exits
212 /// LatchBlock. Control may exit the loop prior to TripCount iterations either
213 /// via an early branch in other loop block or via LatchBlock terminator. This
214 /// is relaxed from the general definition of trip count which is the number of
215 /// times the loop header executes. Note that UnrollLoop assumes that the loop
216 /// counter test is in LatchBlock in order to remove unnecesssary instances of
217 /// the test.  If control can exit the loop from the LatchBlock's terminator
218 /// prior to TripCount iterations, flag PreserveCondBr needs to be set.
219 ///
220 /// PreserveCondBr indicates whether the conditional branch of the LatchBlock
221 /// needs to be preserved.  It is needed when we use trip count upper bound to
222 /// fully unroll the loop. If PreserveOnlyFirst is also set then only the first
223 /// conditional branch needs to be preserved.
224 ///
225 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
226 /// execute without exiting the loop.
227 ///
228 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
229 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
230 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
231 /// iterations before branching into the unrolled loop.  UnrollLoop will not
232 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
233 /// AllowExpensiveTripCount is false.
234 ///
235 /// If we want to perform PGO-based loop peeling, PeelCount is set to the
236 /// number of iterations we want to peel off.
237 ///
238 /// The LoopInfo Analysis that is passed will be kept consistent.
239 ///
240 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
241 /// DominatorTree if they are non-null.
242 ///
243 /// If RemainderLoop is non-null, it will receive the remainder loop (if
244 /// required and not fully unrolled).
245 LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
246                                   ScalarEvolution *SE, DominatorTree *DT,
247                                   AssumptionCache *AC,
248                                   OptimizationRemarkEmitter *ORE,
249                                   bool PreserveLCSSA, Loop **RemainderLoop) {
250 
251   BasicBlock *Preheader = L->getLoopPreheader();
252   if (!Preheader) {
253     LLVM_DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
254     return LoopUnrollResult::Unmodified;
255   }
256 
257   BasicBlock *LatchBlock = L->getLoopLatch();
258   if (!LatchBlock) {
259     LLVM_DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
260     return LoopUnrollResult::Unmodified;
261   }
262 
263   // Loops with indirectbr cannot be cloned.
264   if (!L->isSafeToClone()) {
265     LLVM_DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
266     return LoopUnrollResult::Unmodified;
267   }
268 
269   // The current loop unroll pass can unroll loops with a single latch or header
270   // that's a conditional branch exiting the loop.
271   // FIXME: The implementation can be extended to work with more complicated
272   // cases, e.g. loops with multiple latches.
273   BasicBlock *Header = L->getHeader();
274   BranchInst *HeaderBI = dyn_cast<BranchInst>(Header->getTerminator());
275   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
276 
277   // FIXME: Support loops without conditional latch and multiple exiting blocks.
278   if (!BI ||
279       (BI->isUnconditional() && (!HeaderBI || HeaderBI->isUnconditional() ||
280                                  L->getExitingBlock() != Header))) {
281     LLVM_DEBUG(dbgs() << "  Can't unroll; loop not terminated by a conditional "
282                          "branch in the latch or header.\n");
283     return LoopUnrollResult::Unmodified;
284   }
285 
286   auto CheckLatchSuccessors = [&](unsigned S1, unsigned S2) {
287     return BI->isConditional() && BI->getSuccessor(S1) == Header &&
288            !L->contains(BI->getSuccessor(S2));
289   };
290 
291   // If we have a conditional latch, it must exit the loop.
292   if (BI && BI->isConditional() && !CheckLatchSuccessors(0, 1) &&
293       !CheckLatchSuccessors(1, 0)) {
294     LLVM_DEBUG(
295         dbgs() << "Can't unroll; a conditional latch must exit the loop");
296     return LoopUnrollResult::Unmodified;
297   }
298 
299   auto CheckHeaderSuccessors = [&](unsigned S1, unsigned S2) {
300     return HeaderBI && HeaderBI->isConditional() &&
301            L->contains(HeaderBI->getSuccessor(S1)) &&
302            !L->contains(HeaderBI->getSuccessor(S2));
303   };
304 
305   // If we do not have a conditional latch, the header must exit the loop.
306   if (BI && !BI->isConditional() && HeaderBI && HeaderBI->isConditional() &&
307       !CheckHeaderSuccessors(0, 1) && !CheckHeaderSuccessors(1, 0)) {
308     LLVM_DEBUG(dbgs() << "Can't unroll; conditional header must exit the loop");
309     return LoopUnrollResult::Unmodified;
310   }
311 
312   if (Header->hasAddressTaken()) {
313     // The loop-rotate pass can be helpful to avoid this in many cases.
314     LLVM_DEBUG(
315         dbgs() << "  Won't unroll loop: address of header block is taken.\n");
316     return LoopUnrollResult::Unmodified;
317   }
318 
319   if (ULO.TripCount != 0)
320     LLVM_DEBUG(dbgs() << "  Trip Count = " << ULO.TripCount << "\n");
321   if (ULO.TripMultiple != 1)
322     LLVM_DEBUG(dbgs() << "  Trip Multiple = " << ULO.TripMultiple << "\n");
323 
324   // Effectively "DCE" unrolled iterations that are beyond the tripcount
325   // and will never be executed.
326   if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount)
327     ULO.Count = ULO.TripCount;
328 
329   // Don't enter the unroll code if there is nothing to do.
330   if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
331     LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
332     return LoopUnrollResult::Unmodified;
333   }
334 
335   assert(ULO.Count > 0);
336   assert(ULO.TripMultiple > 0);
337   assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
338 
339   // Are we eliminating the loop control altogether?
340   bool CompletelyUnroll = ULO.Count == ULO.TripCount;
341   SmallVector<BasicBlock *, 4> ExitBlocks;
342   L->getExitBlocks(ExitBlocks);
343   std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
344 
345   // Go through all exits of L and see if there are any phi-nodes there. We just
346   // conservatively assume that they're inserted to preserve LCSSA form, which
347   // means that complete unrolling might break this form. We need to either fix
348   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
349   // now we just recompute LCSSA for the outer loop, but it should be possible
350   // to fix it in-place.
351   bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
352                         any_of(ExitBlocks, [](const BasicBlock *BB) {
353                           return isa<PHINode>(BB->begin());
354                         });
355 
356   // We assume a run-time trip count if the compiler cannot
357   // figure out the loop trip count and the unroll-runtime
358   // flag is specified.
359   bool RuntimeTripCount =
360       (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime);
361 
362   assert((!RuntimeTripCount || !ULO.PeelCount) &&
363          "Did not expect runtime trip-count unrolling "
364          "and peeling for the same loop");
365 
366   bool Peeled = false;
367   if (ULO.PeelCount) {
368     Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
369 
370     // Successful peeling may result in a change in the loop preheader/trip
371     // counts. If we later unroll the loop, we want these to be updated.
372     if (Peeled) {
373       // According to our guards and profitability checks the only
374       // meaningful exit should be latch block. Other exits go to deopt,
375       // so we do not worry about them.
376       BasicBlock *ExitingBlock = L->getLoopLatch();
377       assert(ExitingBlock && "Loop without exiting block?");
378       assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?");
379       Preheader = L->getLoopPreheader();
380       ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
381       ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
382     }
383   }
384 
385   // Loops containing convergent instructions must have a count that divides
386   // their TripMultiple.
387   LLVM_DEBUG(
388       {
389         bool HasConvergent = false;
390         for (auto &BB : L->blocks())
391           for (auto &I : *BB)
392             if (auto CS = CallSite(&I))
393               HasConvergent |= CS.isConvergent();
394         assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&
395                "Unroll count must divide trip multiple if loop contains a "
396                "convergent operation.");
397       });
398 
399   bool EpilogProfitability =
400       UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
401                                               : isEpilogProfitable(L);
402 
403   if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 &&
404       !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
405                                   EpilogProfitability, ULO.UnrollRemainder,
406                                   ULO.ForgetAllSCEV, LI, SE, DT, AC,
407                                   PreserveLCSSA, RemainderLoop)) {
408     if (ULO.Force)
409       RuntimeTripCount = false;
410     else {
411       LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
412                            "generated when assuming runtime trip count\n");
413       return LoopUnrollResult::Unmodified;
414     }
415   }
416 
417   // If we know the trip count, we know the multiple...
418   unsigned BreakoutTrip = 0;
419   if (ULO.TripCount != 0) {
420     BreakoutTrip = ULO.TripCount % ULO.Count;
421     ULO.TripMultiple = 0;
422   } else {
423     // Figure out what multiple to use.
424     BreakoutTrip = ULO.TripMultiple =
425         (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
426   }
427 
428   using namespace ore;
429   // Report the unrolling decision.
430   if (CompletelyUnroll) {
431     LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
432                       << " with trip count " << ULO.TripCount << "!\n");
433     if (ORE)
434       ORE->emit([&]() {
435         return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
436                                   L->getHeader())
437                << "completely unrolled loop with "
438                << NV("UnrollCount", ULO.TripCount) << " iterations";
439       });
440   } else if (ULO.PeelCount) {
441     LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()
442                       << " with iteration count " << ULO.PeelCount << "!\n");
443     if (ORE)
444       ORE->emit([&]() {
445         return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
446                                   L->getHeader())
447                << " peeled loop by " << NV("PeelCount", ULO.PeelCount)
448                << " iterations";
449       });
450   } else {
451     auto DiagBuilder = [&]() {
452       OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
453                               L->getHeader());
454       return Diag << "unrolled loop by a factor of "
455                   << NV("UnrollCount", ULO.Count);
456     };
457 
458     LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
459                       << ULO.Count);
460     if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) {
461       LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
462       if (ORE)
463         ORE->emit([&]() {
464           return DiagBuilder() << " with a breakout at trip "
465                                << NV("BreakoutTrip", BreakoutTrip);
466         });
467     } else if (ULO.TripMultiple != 1) {
468       LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch");
469       if (ORE)
470         ORE->emit([&]() {
471           return DiagBuilder()
472                  << " with " << NV("TripMultiple", ULO.TripMultiple)
473                  << " trips per branch";
474         });
475     } else if (RuntimeTripCount) {
476       LLVM_DEBUG(dbgs() << " with run-time trip count");
477       if (ORE)
478         ORE->emit(
479             [&]() { return DiagBuilder() << " with run-time trip count"; });
480     }
481     LLVM_DEBUG(dbgs() << "!\n");
482   }
483 
484   // We are going to make changes to this loop. SCEV may be keeping cached info
485   // about it, in particular about backedge taken count. The changes we make
486   // are guaranteed to invalidate this information for our loop. It is tempting
487   // to only invalidate the loop being unrolled, but it is incorrect as long as
488   // all exiting branches from all inner loops have impact on the outer loops,
489   // and if something changes inside them then any of outer loops may also
490   // change. When we forget outermost loop, we also forget all contained loops
491   // and this is what we need here.
492   if (SE) {
493     if (ULO.ForgetAllSCEV)
494       SE->forgetAllLoops();
495     else
496       SE->forgetTopmostLoop(L);
497   }
498 
499   bool ContinueOnTrue;
500   bool LatchIsExiting = BI->isConditional();
501   BasicBlock *LoopExit = nullptr;
502   if (LatchIsExiting) {
503     ContinueOnTrue = L->contains(BI->getSuccessor(0));
504     LoopExit = BI->getSuccessor(ContinueOnTrue);
505   } else {
506     NumUnrolledWithHeader++;
507     ContinueOnTrue = L->contains(HeaderBI->getSuccessor(0));
508     LoopExit = HeaderBI->getSuccessor(ContinueOnTrue);
509   }
510 
511   // For the first iteration of the loop, we should use the precloned values for
512   // PHI nodes.  Insert associations now.
513   ValueToValueMapTy LastValueMap;
514   std::vector<PHINode*> OrigPHINode;
515   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
516     OrigPHINode.push_back(cast<PHINode>(I));
517   }
518 
519   std::vector<BasicBlock *> Headers;
520   std::vector<BasicBlock *> HeaderSucc;
521   std::vector<BasicBlock *> Latches;
522   Headers.push_back(Header);
523   Latches.push_back(LatchBlock);
524 
525   if (!LatchIsExiting) {
526     auto *Term = cast<BranchInst>(Header->getTerminator());
527     if (Term->isUnconditional() || L->contains(Term->getSuccessor(0))) {
528       assert(L->contains(Term->getSuccessor(0)));
529       HeaderSucc.push_back(Term->getSuccessor(0));
530     } else {
531       assert(L->contains(Term->getSuccessor(1)));
532       HeaderSucc.push_back(Term->getSuccessor(1));
533     }
534   }
535 
536   // The current on-the-fly SSA update requires blocks to be processed in
537   // reverse postorder so that LastValueMap contains the correct value at each
538   // exit.
539   LoopBlocksDFS DFS(L);
540   DFS.perform(LI);
541 
542   // Stash the DFS iterators before adding blocks to the loop.
543   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
544   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
545 
546   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
547 
548   // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
549   // might break loop-simplified form for these loops (as they, e.g., would
550   // share the same exit blocks). We'll keep track of loops for which we can
551   // break this so that later we can re-simplify them.
552   SmallSetVector<Loop *, 4> LoopsToSimplify;
553   for (Loop *SubLoop : *L)
554     LoopsToSimplify.insert(SubLoop);
555 
556   if (Header->getParent()->isDebugInfoForProfiling())
557     for (BasicBlock *BB : L->getBlocks())
558       for (Instruction &I : *BB)
559         if (!isa<DbgInfoIntrinsic>(&I))
560           if (const DILocation *DIL = I.getDebugLoc()) {
561             auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
562             if (NewDIL)
563               I.setDebugLoc(NewDIL.getValue());
564             else
565               LLVM_DEBUG(dbgs()
566                          << "Failed to create new discriminator: "
567                          << DIL->getFilename() << " Line: " << DIL->getLine());
568           }
569 
570   for (unsigned It = 1; It != ULO.Count; ++It) {
571     SmallVector<BasicBlock *, 8> NewBlocks;
572     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
573     NewLoops[L] = L;
574 
575     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
576       ValueToValueMapTy VMap;
577       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
578       Header->getParent()->getBasicBlockList().push_back(New);
579 
580       assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
581              "Header should not be in a sub-loop");
582       // Tell LI about New.
583       const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
584       if (OldLoop)
585         LoopsToSimplify.insert(NewLoops[OldLoop]);
586 
587       if (*BB == Header)
588         // Loop over all of the PHI nodes in the block, changing them to use
589         // the incoming values from the previous block.
590         for (PHINode *OrigPHI : OrigPHINode) {
591           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
592           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
593           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
594             if (It > 1 && L->contains(InValI))
595               InVal = LastValueMap[InValI];
596           VMap[OrigPHI] = InVal;
597           New->getInstList().erase(NewPHI);
598         }
599 
600       // Update our running map of newest clones
601       LastValueMap[*BB] = New;
602       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
603            VI != VE; ++VI)
604         LastValueMap[VI->first] = VI->second;
605 
606       // Add phi entries for newly created values to all exit blocks.
607       for (BasicBlock *Succ : successors(*BB)) {
608         if (L->contains(Succ))
609           continue;
610         for (PHINode &PHI : Succ->phis()) {
611           Value *Incoming = PHI.getIncomingValueForBlock(*BB);
612           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
613           if (It != LastValueMap.end())
614             Incoming = It->second;
615           PHI.addIncoming(Incoming, New);
616         }
617       }
618       // Keep track of new headers and latches as we create them, so that
619       // we can insert the proper branches later.
620       if (*BB == Header)
621         Headers.push_back(New);
622       if (*BB == LatchBlock)
623         Latches.push_back(New);
624 
625       // Keep track of the successor of the new header in the current iteration.
626       for (auto *Pred : predecessors(*BB))
627         if (Pred == Header) {
628           HeaderSucc.push_back(New);
629           break;
630         }
631 
632       NewBlocks.push_back(New);
633       UnrolledLoopBlocks.push_back(New);
634 
635       // Update DomTree: since we just copy the loop body, and each copy has a
636       // dedicated entry block (copy of the header block), this header's copy
637       // dominates all copied blocks. That means, dominance relations in the
638       // copied body are the same as in the original body.
639       if (DT) {
640         if (*BB == Header)
641           DT->addNewBlock(New, Latches[It - 1]);
642         else {
643           auto BBDomNode = DT->getNode(*BB);
644           auto BBIDom = BBDomNode->getIDom();
645           BasicBlock *OriginalBBIDom = BBIDom->getBlock();
646           DT->addNewBlock(
647               New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
648         }
649       }
650     }
651 
652     // Remap all instructions in the most recent iteration
653     remapInstructionsInBlocks(NewBlocks, LastValueMap);
654     for (BasicBlock *NewBlock : NewBlocks) {
655       for (Instruction &I : *NewBlock) {
656         if (auto *II = dyn_cast<IntrinsicInst>(&I))
657           if (II->getIntrinsicID() == Intrinsic::assume)
658             AC->registerAssumption(II);
659       }
660     }
661   }
662 
663   // Loop over the PHI nodes in the original block, setting incoming values.
664   for (PHINode *PN : OrigPHINode) {
665     if (CompletelyUnroll) {
666       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
667       Header->getInstList().erase(PN);
668     } else if (ULO.Count > 1) {
669       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
670       // If this value was defined in the loop, take the value defined by the
671       // last iteration of the loop.
672       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
673         if (L->contains(InValI))
674           InVal = LastValueMap[InVal];
675       }
676       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
677       PN->addIncoming(InVal, Latches.back());
678     }
679   }
680 
681   auto setDest = [LoopExit, ContinueOnTrue](BasicBlock *Src, BasicBlock *Dest,
682                                             ArrayRef<BasicBlock *> NextBlocks,
683                                             BasicBlock *BlockInLoop,
684                                             bool NeedConditional) {
685     auto *Term = cast<BranchInst>(Src->getTerminator());
686     if (NeedConditional) {
687       // Update the conditional branch's successor for the following
688       // iteration.
689       Term->setSuccessor(!ContinueOnTrue, Dest);
690     } else {
691       // Remove phi operands at this loop exit
692       if (Dest != LoopExit) {
693         BasicBlock *BB = Src;
694         for (BasicBlock *Succ : successors(BB)) {
695           // Preserve the incoming value from BB if we are jumping to the block
696           // in the current loop.
697           if (Succ == BlockInLoop)
698             continue;
699           for (PHINode &Phi : Succ->phis())
700             Phi.removeIncomingValue(BB, false);
701         }
702       }
703       // Replace the conditional branch with an unconditional one.
704       BranchInst::Create(Dest, Term);
705       Term->eraseFromParent();
706     }
707   };
708 
709   // Now that all the basic blocks for the unrolled iterations are in place,
710   // set up the branches to connect them.
711   if (LatchIsExiting) {
712     // Set up latches to branch to the new header in the unrolled iterations or
713     // the loop exit for the last latch in a fully unrolled loop.
714     for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
715       // The branch destination.
716       unsigned j = (i + 1) % e;
717       BasicBlock *Dest = Headers[j];
718       bool NeedConditional = true;
719 
720       if (RuntimeTripCount && j != 0) {
721         NeedConditional = false;
722       }
723 
724       // For a complete unroll, make the last iteration end with a branch
725       // to the exit block.
726       if (CompletelyUnroll) {
727         if (j == 0)
728           Dest = LoopExit;
729         // If using trip count upper bound to completely unroll, we need to keep
730         // the conditional branch except the last one because the loop may exit
731         // after any iteration.
732         assert(NeedConditional &&
733                "NeedCondition cannot be modified by both complete "
734                "unrolling and runtime unrolling");
735         NeedConditional =
736             (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0));
737       } else if (j != BreakoutTrip &&
738                  (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
739         // If we know the trip count or a multiple of it, we can safely use an
740         // unconditional branch for some iterations.
741         NeedConditional = false;
742       }
743 
744       setDest(Latches[i], Dest, Headers, Headers[i], NeedConditional);
745     }
746   } else {
747     // Setup headers to branch to their new successors in the unrolled
748     // iterations.
749     for (unsigned i = 0, e = Headers.size(); i != e; ++i) {
750       // The branch destination.
751       unsigned j = (i + 1) % e;
752       BasicBlock *Dest = HeaderSucc[i];
753       bool NeedConditional = true;
754 
755       if (RuntimeTripCount && j != 0)
756         NeedConditional = false;
757 
758       if (CompletelyUnroll)
759         // We cannot drop the conditional branch for the last condition, as we
760         // may have to execute the loop body depending on the condition.
761         NeedConditional = j == 0 || ULO.PreserveCondBr;
762       else if (j != BreakoutTrip &&
763                (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0))
764         // If we know the trip count or a multiple of it, we can safely use an
765         // unconditional branch for some iterations.
766         NeedConditional = false;
767 
768       setDest(Headers[i], Dest, Headers, HeaderSucc[i], NeedConditional);
769     }
770 
771     // Set up latches to branch to the new header in the unrolled iterations or
772     // the loop exit for the last latch in a fully unrolled loop.
773 
774     for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
775       // The original branch was replicated in each unrolled iteration.
776       BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
777 
778       // The branch destination.
779       unsigned j = (i + 1) % e;
780       BasicBlock *Dest = Headers[j];
781 
782       // When completely unrolling, the last latch becomes unreachable.
783       if (CompletelyUnroll && j == 0)
784         new UnreachableInst(Term->getContext(), Term);
785       else
786         // Replace the conditional branch with an unconditional one.
787         BranchInst::Create(Dest, Term);
788 
789       Term->eraseFromParent();
790     }
791   }
792 
793   // Update dominators of blocks we might reach through exits.
794   // Immediate dominator of such block might change, because we add more
795   // routes which can lead to the exit: we can now reach it from the copied
796   // iterations too.
797   if (DT && ULO.Count > 1) {
798     for (auto *BB : OriginalLoopBlocks) {
799       auto *BBDomNode = DT->getNode(BB);
800       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
801       for (auto *ChildDomNode : BBDomNode->getChildren()) {
802         auto *ChildBB = ChildDomNode->getBlock();
803         if (!L->contains(ChildBB))
804           ChildrenToUpdate.push_back(ChildBB);
805       }
806       BasicBlock *NewIDom;
807       BasicBlock *&TermBlock = LatchIsExiting ? LatchBlock : Header;
808       auto &TermBlocks = LatchIsExiting ? Latches : Headers;
809       if (BB == TermBlock) {
810         // The latch is special because we emit unconditional branches in
811         // some cases where the original loop contained a conditional branch.
812         // Since the latch is always at the bottom of the loop, if the latch
813         // dominated an exit before unrolling, the new dominator of that exit
814         // must also be a latch.  Specifically, the dominator is the first
815         // latch which ends in a conditional branch, or the last latch if
816         // there is no such latch.
817         // For loops exiting from the header, we limit the supported loops
818         // to have a single exiting block.
819         NewIDom = TermBlocks.back();
820         for (BasicBlock *Iter : TermBlocks) {
821           Instruction *Term = Iter->getTerminator();
822           if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
823             NewIDom = Iter;
824             break;
825           }
826         }
827       } else {
828         // The new idom of the block will be the nearest common dominator
829         // of all copies of the previous idom. This is equivalent to the
830         // nearest common dominator of the previous idom and the first latch,
831         // which dominates all copies of the previous idom.
832         NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
833       }
834       for (auto *ChildBB : ChildrenToUpdate)
835         DT->changeImmediateDominator(ChildBB, NewIDom);
836     }
837   }
838 
839   assert(!DT || !UnrollVerifyDomtree ||
840          DT->verify(DominatorTree::VerificationLevel::Fast));
841 
842   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
843   // Merge adjacent basic blocks, if possible.
844   for (BasicBlock *Latch : Latches) {
845     BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
846     assert((Term ||
847             (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
848            "Need a branch as terminator, except when fully unrolling with "
849            "unconditional latch");
850     if (Term && Term->isUnconditional()) {
851       BasicBlock *Dest = Term->getSuccessor(0);
852       BasicBlock *Fold = Dest->getUniquePredecessor();
853       if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
854         // Dest has been folded into Fold. Update our worklists accordingly.
855         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
856         UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
857                                              UnrolledLoopBlocks.end(), Dest),
858                                  UnrolledLoopBlocks.end());
859       }
860     }
861   }
862   // Apply updates to the DomTree.
863   DT = &DTU.getDomTree();
864 
865   // At this point, the code is well formed.  We now simplify the unrolled loop,
866   // doing constant propagation and dead code elimination as we go.
867   simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
868                           SE, DT, AC);
869 
870   NumCompletelyUnrolled += CompletelyUnroll;
871   ++NumUnrolled;
872 
873   Loop *OuterL = L->getParentLoop();
874   // Update LoopInfo if the loop is completely removed.
875   if (CompletelyUnroll)
876     LI->erase(L);
877 
878   // After complete unrolling most of the blocks should be contained in OuterL.
879   // However, some of them might happen to be out of OuterL (e.g. if they
880   // precede a loop exit). In this case we might need to insert PHI nodes in
881   // order to preserve LCSSA form.
882   // We don't need to check this if we already know that we need to fix LCSSA
883   // form.
884   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
885   // it should be possible to fix it in-place.
886   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
887     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
888 
889   // If we have a pass and a DominatorTree we should re-simplify impacted loops
890   // to ensure subsequent analyses can rely on this form. We want to simplify
891   // at least one layer outside of the loop that was unrolled so that any
892   // changes to the parent loop exposed by the unrolling are considered.
893   if (DT) {
894     if (OuterL) {
895       // OuterL includes all loops for which we can break loop-simplify, so
896       // it's sufficient to simplify only it (it'll recursively simplify inner
897       // loops too).
898       if (NeedToFixLCSSA) {
899         // LCSSA must be performed on the outermost affected loop. The unrolled
900         // loop's last loop latch is guaranteed to be in the outermost loop
901         // after LoopInfo's been updated by LoopInfo::erase.
902         Loop *LatchLoop = LI->getLoopFor(Latches.back());
903         Loop *FixLCSSALoop = OuterL;
904         if (!FixLCSSALoop->contains(LatchLoop))
905           while (FixLCSSALoop->getParentLoop() != LatchLoop)
906             FixLCSSALoop = FixLCSSALoop->getParentLoop();
907 
908         formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
909       } else if (PreserveLCSSA) {
910         assert(OuterL->isLCSSAForm(*DT) &&
911                "Loops should be in LCSSA form after loop-unroll.");
912       }
913 
914       // TODO: That potentially might be compile-time expensive. We should try
915       // to fix the loop-simplified form incrementally.
916       simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
917     } else {
918       // Simplify loops for which we might've broken loop-simplify form.
919       for (Loop *SubLoop : LoopsToSimplify)
920         simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
921     }
922   }
923 
924   return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
925                           : LoopUnrollResult::PartiallyUnrolled;
926 }
927 
928 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
929 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
930 /// such metadata node exists, then nullptr is returned.
931 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
932   // First operand should refer to the loop id itself.
933   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
934   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
935 
936   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
937     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
938     if (!MD)
939       continue;
940 
941     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
942     if (!S)
943       continue;
944 
945     if (Name.equals(S->getString()))
946       return MD;
947   }
948   return nullptr;
949 }
950