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