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