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     while (!DeadInsts.empty()) {
217       Value *V = DeadInsts.pop_back_val();
218       if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
219         RecursivelyDeleteTriviallyDeadInstructions(Inst);
220     }
221   }
222 
223   // At this point, the code is well formed.  Perform constprop, instsimplify,
224   // and dce.
225   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
226   SmallVector<WeakTrackingVH, 16> DeadInsts;
227   for (BasicBlock *BB : L->getBlocks()) {
228     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
229       Instruction *Inst = &*I++;
230       if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC}))
231         if (LI->replacementPreservesLCSSAForm(Inst, V))
232           Inst->replaceAllUsesWith(V);
233       if (isInstructionTriviallyDead(Inst))
234         DeadInsts.emplace_back(Inst);
235     }
236     // We can't do recursive deletion until we're done iterating, as we might
237     // have a phi which (potentially indirectly) uses instructions later in
238     // the block we're iterating through.
239     RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
240   }
241 }
242 
243 /// Unroll the given loop by Count. The loop must be in LCSSA form.  Unrolling
244 /// can only fail when the loop's latch block is not terminated by a conditional
245 /// branch instruction. However, if the trip count (and multiple) are not known,
246 /// loop unrolling will mostly produce more code that is no faster.
247 ///
248 /// TripCount is an upper bound on the number of times the loop header runs.
249 /// Note that the trip count does not need to be exact, it can be any upper
250 /// bound on the true trip count.
251 ///
252 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
253 /// execute without exiting the loop.
254 ///
255 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
256 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
257 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
258 /// iterations before branching into the unrolled loop.  UnrollLoop will not
259 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
260 /// AllowExpensiveTripCount is false.
261 ///
262 /// If we want to perform PGO-based loop peeling, PeelCount is set to the
263 /// number of iterations we want to peel off.
264 ///
265 /// The LoopInfo Analysis that is passed will be kept consistent.
266 ///
267 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
268 /// DominatorTree if they are non-null.
269 ///
270 /// If RemainderLoop is non-null, it will receive the remainder loop (if
271 /// required and not fully unrolled).
272 LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
273                                   ScalarEvolution *SE, DominatorTree *DT,
274                                   AssumptionCache *AC,
275                                   const TargetTransformInfo *TTI,
276                                   OptimizationRemarkEmitter *ORE,
277                                   bool PreserveLCSSA, Loop **RemainderLoop) {
278   assert(DT && "DomTree is required");
279 
280   if (!L->getLoopPreheader()) {
281     LLVM_DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
282     return LoopUnrollResult::Unmodified;
283   }
284 
285   if (!L->getLoopLatch()) {
286     LLVM_DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
287     return LoopUnrollResult::Unmodified;
288   }
289 
290   // Loops with indirectbr cannot be cloned.
291   if (!L->isSafeToClone()) {
292     LLVM_DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
293     return LoopUnrollResult::Unmodified;
294   }
295 
296   if (L->getHeader()->hasAddressTaken()) {
297     // The loop-rotate pass can be helpful to avoid this in many cases.
298     LLVM_DEBUG(
299         dbgs() << "  Won't unroll loop: address of header block is taken.\n");
300     return LoopUnrollResult::Unmodified;
301   }
302 
303   if (ULO.TripCount != 0)
304     LLVM_DEBUG(dbgs() << "  Trip Count = " << ULO.TripCount << "\n");
305   if (ULO.TripMultiple != 1)
306     LLVM_DEBUG(dbgs() << "  Trip Multiple = " << ULO.TripMultiple << "\n");
307 
308   // Effectively "DCE" unrolled iterations that are beyond the tripcount
309   // and will never be executed.
310   if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount)
311     ULO.Count = ULO.TripCount;
312 
313   // Don't enter the unroll code if there is nothing to do.
314   if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
315     LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
316     return LoopUnrollResult::Unmodified;
317   }
318 
319   assert(ULO.Count > 0);
320   assert(ULO.TripMultiple > 0);
321   assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
322 
323 
324   bool Peeled = false;
325   if (ULO.PeelCount) {
326     Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
327 
328     // Successful peeling may result in a change in the loop preheader/trip
329     // counts. If we later unroll the loop, we want these to be updated.
330     if (Peeled) {
331       // According to our guards and profitability checks the only
332       // meaningful exit should be latch block. Other exits go to deopt,
333       // so we do not worry about them.
334       BasicBlock *ExitingBlock = L->getLoopLatch();
335       assert(ExitingBlock && "Loop without exiting block?");
336       assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?");
337       ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
338       ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
339     }
340   }
341 
342   // Are we eliminating the loop control altogether?  Note that we can know
343   // we're eliminating the backedge without knowing exactly which iteration
344   // of the unrolled body exits.
345   const bool CompletelyUnroll = ULO.Count == ULO.TripCount;
346 
347   // We assume a run-time trip count if the compiler cannot
348   // figure out the loop trip count and the unroll-runtime
349   // flag is specified.
350   bool RuntimeTripCount =
351       (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime);
352 
353   assert((!RuntimeTripCount || !ULO.PeelCount) &&
354          "Did not expect runtime trip-count unrolling "
355          "and peeling for the same loop");
356 
357   // All these values should be taken only after peeling because they might have
358   // changed.
359   BasicBlock *Preheader = L->getLoopPreheader();
360   BasicBlock *Header = L->getHeader();
361   BasicBlock *LatchBlock = L->getLoopLatch();
362   SmallVector<BasicBlock *, 4> ExitBlocks;
363   L->getExitBlocks(ExitBlocks);
364   std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
365 
366   // Go through all exits of L and see if there are any phi-nodes there. We just
367   // conservatively assume that they're inserted to preserve LCSSA form, which
368   // means that complete unrolling might break this form. We need to either fix
369   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
370   // now we just recompute LCSSA for the outer loop, but it should be possible
371   // to fix it in-place.
372   bool NeedToFixLCSSA =
373       PreserveLCSSA && CompletelyUnroll &&
374       any_of(ExitBlocks,
375              [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
376 
377   const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
378   const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
379 
380   const bool PreserveOnlyFirst = ULO.Count == MaxTripCount && MaxOrZero;
381 
382   // The current loop unroll pass can unroll loops that have
383   // (1) single latch; and
384   // (2a) latch is unconditional; or
385   // (2b) latch is conditional and is an exiting block
386   // FIXME: The implementation can be extended to work with more complicated
387   // cases, e.g. loops with multiple latches.
388   BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
389 
390   // A conditional branch which exits the loop, which can be optimized to an
391   // unconditional branch in the unrolled loop in some cases.
392   BranchInst *ExitingBI = nullptr;
393   bool LatchIsExiting = L->isLoopExiting(LatchBlock);
394   if (LatchIsExiting)
395     ExitingBI = LatchBI;
396   else if (BasicBlock *ExitingBlock = L->getExitingBlock())
397     ExitingBI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
398   if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
399     // If the peeling guard is changed this assert may be relaxed or even
400     // deleted.
401     assert(!Peeled && "Peeling guard changed!");
402     LLVM_DEBUG(
403         dbgs() << "Can't unroll; a conditional latch must exit the loop");
404     return LoopUnrollResult::Unmodified;
405   }
406   LLVM_DEBUG({
407     if (ExitingBI)
408       dbgs() << "  Exiting Block = " << ExitingBI->getParent()->getName()
409              << "\n";
410     else
411       dbgs() << "  No single exiting block\n";
412   });
413 
414   // Warning: ExactTripCount is the exact trip count for the block ending in
415   // ExitingBI, not neccessarily an exact exit count *for the loop*.  The
416   // distinction comes when we have an exiting latch, but the loop exits
417   // through another exit first.
418   const unsigned ExactTripCount = ExitingBI ?
419     SE->getSmallConstantTripCount(L,ExitingBI->getParent()) : 0;
420   const bool ExactUnroll = (ExactTripCount && ExactTripCount == ULO.Count);
421 
422   // Loops containing convergent instructions must have a count that divides
423   // their TripMultiple.
424   LLVM_DEBUG(
425       {
426         bool HasConvergent = false;
427         for (auto &BB : L->blocks())
428           for (auto &I : *BB)
429             if (auto *CB = dyn_cast<CallBase>(&I))
430               HasConvergent |= CB->isConvergent();
431         assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&
432                "Unroll count must divide trip multiple if loop contains a "
433                "convergent operation.");
434       });
435 
436   bool EpilogProfitability =
437       UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
438                                               : isEpilogProfitable(L);
439 
440   if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 &&
441       !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
442                                   EpilogProfitability, ULO.UnrollRemainder,
443                                   ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
444                                   PreserveLCSSA, RemainderLoop)) {
445     if (ULO.Force)
446       RuntimeTripCount = false;
447     else {
448       LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
449                            "generated when assuming runtime trip count\n");
450       return LoopUnrollResult::Unmodified;
451     }
452   }
453 
454   // If we know the trip count, we know the multiple...
455   unsigned BreakoutTrip = 0;
456   if (ULO.TripCount != 0) {
457     BreakoutTrip = ULO.TripCount % ULO.Count;
458     ULO.TripMultiple = 0;
459   } else {
460     // Figure out what multiple to use.
461     BreakoutTrip = ULO.TripMultiple =
462         (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
463   }
464 
465   using namespace ore;
466   // Report the unrolling decision.
467   if (CompletelyUnroll) {
468     LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
469                       << " with trip count " << ULO.TripCount << "!\n");
470     if (ORE)
471       ORE->emit([&]() {
472         return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
473                                   L->getHeader())
474                << "completely unrolled loop with "
475                << NV("UnrollCount", ULO.TripCount) << " iterations";
476       });
477   } else if (ULO.PeelCount) {
478     LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()
479                       << " with iteration count " << ULO.PeelCount << "!\n");
480     if (ORE)
481       ORE->emit([&]() {
482         return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
483                                   L->getHeader())
484                << " peeled loop by " << NV("PeelCount", ULO.PeelCount)
485                << " iterations";
486       });
487   } else {
488     auto DiagBuilder = [&]() {
489       OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
490                               L->getHeader());
491       return Diag << "unrolled loop by a factor of "
492                   << NV("UnrollCount", ULO.Count);
493     };
494 
495     LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
496                       << ULO.Count);
497     if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) {
498       LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
499       if (ORE)
500         ORE->emit([&]() {
501           return DiagBuilder() << " with a breakout at trip "
502                                << NV("BreakoutTrip", BreakoutTrip);
503         });
504     } else if (ULO.TripMultiple != 1) {
505       LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch");
506       if (ORE)
507         ORE->emit([&]() {
508           return DiagBuilder()
509                  << " with " << NV("TripMultiple", ULO.TripMultiple)
510                  << " trips per branch";
511         });
512     } else if (RuntimeTripCount) {
513       LLVM_DEBUG(dbgs() << " with run-time trip count");
514       if (ORE)
515         ORE->emit(
516             [&]() { return DiagBuilder() << " with run-time trip count"; });
517     }
518     LLVM_DEBUG(dbgs() << "!\n");
519   }
520 
521   // We are going to make changes to this loop. SCEV may be keeping cached info
522   // about it, in particular about backedge taken count. The changes we make
523   // are guaranteed to invalidate this information for our loop. It is tempting
524   // to only invalidate the loop being unrolled, but it is incorrect as long as
525   // all exiting branches from all inner loops have impact on the outer loops,
526   // and if something changes inside them then any of outer loops may also
527   // change. When we forget outermost loop, we also forget all contained loops
528   // and this is what we need here.
529   if (SE) {
530     if (ULO.ForgetAllSCEV)
531       SE->forgetAllLoops();
532     else
533       SE->forgetTopmostLoop(L);
534   }
535 
536   if (!LatchIsExiting)
537     ++NumUnrolledNotLatch;
538 
539   // For the first iteration of the loop, we should use the precloned values for
540   // PHI nodes.  Insert associations now.
541   ValueToValueMapTy LastValueMap;
542   std::vector<PHINode*> OrigPHINode;
543   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
544     OrigPHINode.push_back(cast<PHINode>(I));
545   }
546 
547   std::vector<BasicBlock *> Headers;
548   std::vector<BasicBlock *> ExitingBlocks;
549   std::vector<BasicBlock *> Latches;
550   Headers.push_back(Header);
551   Latches.push_back(LatchBlock);
552   if (ExitingBI)
553     ExitingBlocks.push_back(ExitingBI->getParent());
554 
555   // The current on-the-fly SSA update requires blocks to be processed in
556   // reverse postorder so that LastValueMap contains the correct value at each
557   // exit.
558   LoopBlocksDFS DFS(L);
559   DFS.perform(LI);
560 
561   // Stash the DFS iterators before adding blocks to the loop.
562   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
563   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
564 
565   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
566 
567   // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
568   // might break loop-simplified form for these loops (as they, e.g., would
569   // share the same exit blocks). We'll keep track of loops for which we can
570   // break this so that later we can re-simplify them.
571   SmallSetVector<Loop *, 4> LoopsToSimplify;
572   for (Loop *SubLoop : *L)
573     LoopsToSimplify.insert(SubLoop);
574 
575   // When a FSDiscriminator is enabled, we don't need to add the multiply
576   // factors to the discriminators.
577   if (Header->getParent()->isDebugInfoForProfiling() && !EnableFSDiscriminator)
578     for (BasicBlock *BB : L->getBlocks())
579       for (Instruction &I : *BB)
580         if (!isa<DbgInfoIntrinsic>(&I))
581           if (const DILocation *DIL = I.getDebugLoc()) {
582             auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
583             if (NewDIL)
584               I.setDebugLoc(NewDIL.getValue());
585             else
586               LLVM_DEBUG(dbgs()
587                          << "Failed to create new discriminator: "
588                          << DIL->getFilename() << " Line: " << DIL->getLine());
589           }
590 
591   // Identify what noalias metadata is inside the loop: if it is inside the
592   // loop, the associated metadata must be cloned for each iteration.
593   SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
594   identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
595 
596   for (unsigned It = 1; It != ULO.Count; ++It) {
597     SmallVector<BasicBlock *, 8> NewBlocks;
598     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
599     NewLoops[L] = L;
600 
601     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
602       ValueToValueMapTy VMap;
603       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
604       Header->getParent()->getBasicBlockList().push_back(New);
605 
606       assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
607              "Header should not be in a sub-loop");
608       // Tell LI about New.
609       const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
610       if (OldLoop)
611         LoopsToSimplify.insert(NewLoops[OldLoop]);
612 
613       if (*BB == Header)
614         // Loop over all of the PHI nodes in the block, changing them to use
615         // the incoming values from the previous block.
616         for (PHINode *OrigPHI : OrigPHINode) {
617           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
618           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
619           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
620             if (It > 1 && L->contains(InValI))
621               InVal = LastValueMap[InValI];
622           VMap[OrigPHI] = InVal;
623           New->getInstList().erase(NewPHI);
624         }
625 
626       // Update our running map of newest clones
627       LastValueMap[*BB] = New;
628       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
629            VI != VE; ++VI)
630         LastValueMap[VI->first] = VI->second;
631 
632       // Add phi entries for newly created values to all exit blocks.
633       for (BasicBlock *Succ : successors(*BB)) {
634         if (L->contains(Succ))
635           continue;
636         for (PHINode &PHI : Succ->phis()) {
637           Value *Incoming = PHI.getIncomingValueForBlock(*BB);
638           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
639           if (It != LastValueMap.end())
640             Incoming = It->second;
641           PHI.addIncoming(Incoming, New);
642         }
643       }
644       // Keep track of new headers and latches as we create them, so that
645       // we can insert the proper branches later.
646       if (*BB == Header)
647         Headers.push_back(New);
648       if (*BB == LatchBlock)
649         Latches.push_back(New);
650 
651       // Keep track of the exiting block and its successor block contained in
652       // the loop for the current iteration.
653       if (ExitingBI)
654         if (*BB == ExitingBlocks[0])
655           ExitingBlocks.push_back(New);
656 
657       NewBlocks.push_back(New);
658       UnrolledLoopBlocks.push_back(New);
659 
660       // Update DomTree: since we just copy the loop body, and each copy has a
661       // dedicated entry block (copy of the header block), this header's copy
662       // dominates all copied blocks. That means, dominance relations in the
663       // copied body are the same as in the original body.
664       if (*BB == Header)
665         DT->addNewBlock(New, Latches[It - 1]);
666       else {
667         auto BBDomNode = DT->getNode(*BB);
668         auto BBIDom = BBDomNode->getIDom();
669         BasicBlock *OriginalBBIDom = BBIDom->getBlock();
670         DT->addNewBlock(
671             New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
672       }
673     }
674 
675     // Remap all instructions in the most recent iteration
676     remapInstructionsInBlocks(NewBlocks, LastValueMap);
677     for (BasicBlock *NewBlock : NewBlocks)
678       for (Instruction &I : *NewBlock)
679         if (auto *II = dyn_cast<AssumeInst>(&I))
680           AC->registerAssumption(II);
681 
682     {
683       // Identify what other metadata depends on the cloned version. After
684       // cloning, replace the metadata with the corrected version for both
685       // memory instructions and noalias intrinsics.
686       std::string ext = (Twine("It") + Twine(It)).str();
687       cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
688                                  Header->getContext(), ext);
689     }
690   }
691 
692   // Loop over the PHI nodes in the original block, setting incoming values.
693   for (PHINode *PN : OrigPHINode) {
694     if (CompletelyUnroll) {
695       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
696       Header->getInstList().erase(PN);
697     } else if (ULO.Count > 1) {
698       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
699       // If this value was defined in the loop, take the value defined by the
700       // last iteration of the loop.
701       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
702         if (L->contains(InValI))
703           InVal = LastValueMap[InVal];
704       }
705       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
706       PN->addIncoming(InVal, Latches.back());
707     }
708   }
709 
710   // Connect latches of the unrolled iterations to the headers of the next
711   // iteration. Currently they point to the header of the same iteration.
712   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
713     unsigned j = (i + 1) % e;
714     Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
715   }
716 
717   // Update dominators of blocks we might reach through exits.
718   // Immediate dominator of such block might change, because we add more
719   // routes which can lead to the exit: we can now reach it from the copied
720   // iterations too.
721   if (ULO.Count > 1) {
722     for (auto *BB : OriginalLoopBlocks) {
723       auto *BBDomNode = DT->getNode(BB);
724       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
725       for (auto *ChildDomNode : BBDomNode->children()) {
726         auto *ChildBB = ChildDomNode->getBlock();
727         if (!L->contains(ChildBB))
728           ChildrenToUpdate.push_back(ChildBB);
729       }
730       // The new idom of the block will be the nearest common dominator
731       // of all copies of the previous idom. This is equivalent to the
732       // nearest common dominator of the previous idom and the first latch,
733       // which dominates all copies of the previous idom.
734       BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
735       for (auto *ChildBB : ChildrenToUpdate)
736         DT->changeImmediateDominator(ChildBB, NewIDom);
737     }
738   }
739 
740   assert(!UnrollVerifyDomtree ||
741          DT->verify(DominatorTree::VerificationLevel::Fast));
742 
743   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
744 
745   if (ExitingBI) {
746     auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
747       auto *Term = cast<BranchInst>(Src->getTerminator());
748       const unsigned Idx = ExitOnTrue ^ WillExit;
749       BasicBlock *Dest = Term->getSuccessor(Idx);
750       BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
751 
752       // Remove predecessors from all non-Dest successors.
753       DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
754 
755       // Replace the conditional branch with an unconditional one.
756       BranchInst::Create(Dest, Term);
757       Term->eraseFromParent();
758 
759       DTU.applyUpdates({{DominatorTree::Delete, Src, DeadSucc}});
760     };
761 
762     auto WillExit = [&](unsigned i, unsigned j) -> Optional<bool> {
763       if (CompletelyUnroll) {
764         if (PreserveOnlyFirst) {
765           if (i == 0)
766             return None;
767           return j == 0;
768         }
769         // Complete (but possibly inexact) unrolling
770         if (j == 0)
771           return true;
772         if (MaxTripCount && j >= MaxTripCount)
773           return false;
774         // Warning: ExactTripCount is the trip count of the exiting
775         // block which ends in ExitingBI, not neccessarily the loop.
776         if (ExactTripCount && j != ExactTripCount)
777           return false;
778         return None;
779       }
780 
781       if (RuntimeTripCount && j != 0)
782         return false;
783 
784       if (j != BreakoutTrip &&
785           (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
786         // If we know the trip count or a multiple of it, we can safely use an
787         // unconditional branch for some iterations.
788         return false;
789       }
790       return None;
791     };
792 
793     // Fold branches for iterations where we know that they will exit or not
794     // exit.
795     bool ExitOnTrue = !L->contains(ExitingBI->getSuccessor(0));
796     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
797       // The branch destination.
798       unsigned j = (i + 1) % e;
799       Optional<bool> KnownWillExit = WillExit(i, j);
800       if (!KnownWillExit)
801         continue;
802 
803       // TODO: Also fold known-exiting branches for non-latch exits.
804       if (*KnownWillExit && !LatchIsExiting)
805         continue;
806 
807       SetDest(ExitingBlocks[i], *KnownWillExit, ExitOnTrue);
808     }
809   }
810 
811 
812   // When completely unrolling, the last latch becomes unreachable.
813   if (!LatchIsExiting && CompletelyUnroll)
814     changeToUnreachable(Latches.back()->getTerminator(), /* UseTrap */ false,
815                         PreserveLCSSA, &DTU);
816 
817   // Merge adjacent basic blocks, if possible.
818   for (BasicBlock *Latch : Latches) {
819     BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
820     assert((Term ||
821             (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
822            "Need a branch as terminator, except when fully unrolling with "
823            "unconditional latch");
824     if (Term && Term->isUnconditional()) {
825       BasicBlock *Dest = Term->getSuccessor(0);
826       BasicBlock *Fold = Dest->getUniquePredecessor();
827       if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
828         // Dest has been folded into Fold. Update our worklists accordingly.
829         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
830         llvm::erase_value(UnrolledLoopBlocks, Dest);
831       }
832     }
833   }
834   // Apply updates to the DomTree.
835   DT = &DTU.getDomTree();
836 
837   // At this point, the code is well formed.  We now simplify the unrolled loop,
838   // doing constant propagation and dead code elimination as we go.
839   simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
840                           SE, DT, AC, TTI);
841 
842   NumCompletelyUnrolled += CompletelyUnroll;
843   ++NumUnrolled;
844 
845   Loop *OuterL = L->getParentLoop();
846   // Update LoopInfo if the loop is completely removed.
847   if (CompletelyUnroll)
848     LI->erase(L);
849 
850   // After complete unrolling most of the blocks should be contained in OuterL.
851   // However, some of them might happen to be out of OuterL (e.g. if they
852   // precede a loop exit). In this case we might need to insert PHI nodes in
853   // order to preserve LCSSA form.
854   // We don't need to check this if we already know that we need to fix LCSSA
855   // form.
856   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
857   // it should be possible to fix it in-place.
858   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
859     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
860 
861   // Make sure that loop-simplify form is preserved. We want to simplify
862   // at least one layer outside of the loop that was unrolled so that any
863   // changes to the parent loop exposed by the unrolling are considered.
864   if (OuterL) {
865     // OuterL includes all loops for which we can break loop-simplify, so
866     // it's sufficient to simplify only it (it'll recursively simplify inner
867     // loops too).
868     if (NeedToFixLCSSA) {
869       // LCSSA must be performed on the outermost affected loop. The unrolled
870       // loop's last loop latch is guaranteed to be in the outermost loop
871       // after LoopInfo's been updated by LoopInfo::erase.
872       Loop *LatchLoop = LI->getLoopFor(Latches.back());
873       Loop *FixLCSSALoop = OuterL;
874       if (!FixLCSSALoop->contains(LatchLoop))
875         while (FixLCSSALoop->getParentLoop() != LatchLoop)
876           FixLCSSALoop = FixLCSSALoop->getParentLoop();
877 
878       formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
879     } else if (PreserveLCSSA) {
880       assert(OuterL->isLCSSAForm(*DT) &&
881              "Loops should be in LCSSA form after loop-unroll.");
882     }
883 
884     // TODO: That potentially might be compile-time expensive. We should try
885     // to fix the loop-simplified form incrementally.
886     simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
887   } else {
888     // Simplify loops for which we might've broken loop-simplify form.
889     for (Loop *SubLoop : LoopsToSimplify)
890       simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
891   }
892 
893   return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
894                           : LoopUnrollResult::PartiallyUnrolled;
895 }
896 
897 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
898 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
899 /// such metadata node exists, then nullptr is returned.
900 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
901   // First operand should refer to the loop id itself.
902   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
903   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
904 
905   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
906     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
907     if (!MD)
908       continue;
909 
910     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
911     if (!S)
912       continue;
913 
914     if (Name.equals(S->getString()))
915       return MD;
916   }
917   return nullptr;
918 }
919