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(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
85                                "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,
112                                      const std::vector<BasicBlock *> &Blocks,
113                                      LoopInfo *LI) {
114   for (BasicBlock *BB : Blocks) {
115     if (LI->getLoopFor(BB) == L)
116       continue;
117     for (Instruction &I : *BB) {
118       for (Use &U : I.operands()) {
119         if (const auto *Def = dyn_cast<Instruction>(U)) {
120           Loop *DefLoop = LI->getLoopFor(Def->getParent());
121           if (!DefLoop)
122             continue;
123           if (DefLoop->contains(L))
124             return true;
125         }
126       }
127     }
128   }
129   return false;
130 }
131 
132 /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
133 /// and adds a mapping from the original loop to the new loop to NewLoops.
134 /// Returns nullptr if no new loop was created and a pointer to the
135 /// original loop OriginalBB was part of otherwise.
136 const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
137                                            BasicBlock *ClonedBB, LoopInfo *LI,
138                                            NewLoopsMap &NewLoops) {
139   // Figure out which loop New is in.
140   const Loop *OldLoop = LI->getLoopFor(OriginalBB);
141   assert(OldLoop && "Should (at least) be in the loop being unrolled!");
142 
143   Loop *&NewLoop = NewLoops[OldLoop];
144   if (!NewLoop) {
145     // Found a new sub-loop.
146     assert(OriginalBB == OldLoop->getHeader() &&
147            "Header should be first in RPO");
148 
149     NewLoop = LI->AllocateLoop();
150     Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
151 
152     if (NewLoopParent)
153       NewLoopParent->addChildLoop(NewLoop);
154     else
155       LI->addTopLevelLoop(NewLoop);
156 
157     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
158     return OldLoop;
159   } else {
160     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
161     return nullptr;
162   }
163 }
164 
165 /// The function chooses which type of unroll (epilog or prolog) is more
166 /// profitabale.
167 /// Epilog unroll is more profitable when there is PHI that starts from
168 /// constant.  In this case epilog will leave PHI start from constant,
169 /// but prolog will convert it to non-constant.
170 ///
171 /// loop:
172 ///   PN = PHI [I, Latch], [CI, PreHeader]
173 ///   I = foo(PN)
174 ///   ...
175 ///
176 /// Epilog unroll case.
177 /// loop:
178 ///   PN = PHI [I2, Latch], [CI, PreHeader]
179 ///   I1 = foo(PN)
180 ///   I2 = foo(I1)
181 ///   ...
182 /// Prolog unroll case.
183 ///   NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
184 /// loop:
185 ///   PN = PHI [I2, Latch], [NewPN, PreHeader]
186 ///   I1 = foo(PN)
187 ///   I2 = foo(I1)
188 ///   ...
189 ///
190 static bool isEpilogProfitable(Loop *L) {
191   BasicBlock *PreHeader = L->getLoopPreheader();
192   BasicBlock *Header = L->getHeader();
193   assert(PreHeader && Header);
194   for (const PHINode &PN : Header->phis()) {
195     if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
196       return true;
197   }
198   return false;
199 }
200 
201 /// Perform some cleanup and simplifications on loops after unrolling. It is
202 /// useful to simplify the IV's in the new loop, as well as do a quick
203 /// simplify/dce pass of the instructions.
204 void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
205                                    ScalarEvolution *SE, DominatorTree *DT,
206                                    AssumptionCache *AC,
207                                    const TargetTransformInfo *TTI) {
208   // Simplify any new induction variables in the partially unrolled loop.
209   if (SE && SimplifyIVs) {
210     SmallVector<WeakTrackingVH, 16> DeadInsts;
211     simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
212 
213     // Aggressively clean up dead instructions that simplifyLoopIVs already
214     // identified. Any remaining should be cleaned up below.
215     while (!DeadInsts.empty()) {
216       Value *V = DeadInsts.pop_back_val();
217       if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
218         RecursivelyDeleteTriviallyDeadInstructions(Inst);
219     }
220   }
221 
222   // At this point, the code is well formed.  We now do a quick sweep over the
223   // inserted code, doing constant propagation and dead code elimination as we
224   // go.
225   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
226   for (BasicBlock *BB : L->getBlocks()) {
227     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
228       Instruction *Inst = &*I++;
229 
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         BB->getInstList().erase(Inst);
235     }
236   }
237 
238   // TODO: after peeling or unrolling, previously loop variant conditions are
239   // likely to fold to constants, eagerly propagating those here will require
240   // fewer cleanup passes to be run.  Alternatively, a LoopEarlyCSE might be
241   // appropriate.
242 }
243 
244 /// Unroll the given loop by Count. The loop must be in LCSSA form.  Unrolling
245 /// can only fail when the loop's latch block is not terminated by a conditional
246 /// branch instruction. However, if the trip count (and multiple) are not known,
247 /// loop unrolling will mostly produce more code that is no faster.
248 ///
249 /// TripCount is the upper bound of the iteration on which control exits
250 /// LatchBlock. Control may exit the loop prior to TripCount iterations either
251 /// via an early branch in other loop block or via LatchBlock terminator. This
252 /// is relaxed from the general definition of trip count which is the number of
253 /// times the loop header executes. Note that UnrollLoop assumes that the loop
254 /// counter test is in LatchBlock in order to remove unnecesssary instances of
255 /// the test.  If control can exit the loop from the LatchBlock's terminator
256 /// prior to TripCount iterations, flag PreserveCondBr needs to be set.
257 ///
258 /// PreserveCondBr indicates whether the conditional branch of the LatchBlock
259 /// needs to be preserved.  It is needed when we use trip count upper bound to
260 /// fully unroll the loop. If PreserveOnlyFirst is also set then only the first
261 /// conditional branch needs to be preserved.
262 ///
263 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
264 /// execute without exiting the loop.
265 ///
266 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
267 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
268 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
269 /// iterations before branching into the unrolled loop.  UnrollLoop will not
270 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
271 /// AllowExpensiveTripCount is false.
272 ///
273 /// If we want to perform PGO-based loop peeling, PeelCount is set to the
274 /// number of iterations we want to peel off.
275 ///
276 /// The LoopInfo Analysis that is passed will be kept consistent.
277 ///
278 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
279 /// DominatorTree if they are non-null.
280 ///
281 /// If RemainderLoop is non-null, it will receive the remainder loop (if
282 /// required and not fully unrolled).
283 LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
284                                   ScalarEvolution *SE, DominatorTree *DT,
285                                   AssumptionCache *AC,
286                                   const TargetTransformInfo *TTI,
287                                   OptimizationRemarkEmitter *ORE,
288                                   bool PreserveLCSSA, Loop **RemainderLoop) {
289 
290   BasicBlock *Preheader = L->getLoopPreheader();
291   if (!Preheader) {
292     LLVM_DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
293     return LoopUnrollResult::Unmodified;
294   }
295 
296   BasicBlock *LatchBlock = L->getLoopLatch();
297   if (!LatchBlock) {
298     LLVM_DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
299     return LoopUnrollResult::Unmodified;
300   }
301 
302   // Loops with indirectbr cannot be cloned.
303   if (!L->isSafeToClone()) {
304     LLVM_DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
305     return LoopUnrollResult::Unmodified;
306   }
307 
308   // The current loop unroll pass can unroll loops that have
309   // (1) single latch; and
310   // (2a) latch is unconditional; or
311   // (2b) latch is conditional and is an exiting block
312   // FIXME: The implementation can be extended to work with more complicated
313   // cases, e.g. loops with multiple latches.
314   BasicBlock *Header = L->getHeader();
315   BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
316 
317   // A conditional branch which exits the loop, which can be optimized to an
318   // unconditional branch in the unrolled loop in some cases.
319   BranchInst *ExitingBI = nullptr;
320   bool LatchIsExiting = L->isLoopExiting(LatchBlock);
321   if (LatchIsExiting)
322     ExitingBI = LatchBI;
323   else if (BasicBlock *ExitingBlock = L->getExitingBlock())
324     ExitingBI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
325   if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
326     LLVM_DEBUG(
327         dbgs() << "Can't unroll; a conditional latch must exit the loop");
328     return LoopUnrollResult::Unmodified;
329   }
330   LLVM_DEBUG({
331     if (ExitingBI)
332       dbgs() << "  Exiting Block = " << ExitingBI->getParent()->getName()
333              << "\n";
334     else
335       dbgs() << "  No single exiting block\n";
336   });
337 
338   if (Header->hasAddressTaken()) {
339     // The loop-rotate pass can be helpful to avoid this in many cases.
340     LLVM_DEBUG(
341         dbgs() << "  Won't unroll loop: address of header block is taken.\n");
342     return LoopUnrollResult::Unmodified;
343   }
344 
345   if (ULO.TripCount != 0)
346     LLVM_DEBUG(dbgs() << "  Trip Count = " << ULO.TripCount << "\n");
347   if (ULO.TripMultiple != 1)
348     LLVM_DEBUG(dbgs() << "  Trip Multiple = " << ULO.TripMultiple << "\n");
349 
350   // Effectively "DCE" unrolled iterations that are beyond the tripcount
351   // and will never be executed.
352   if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount)
353     ULO.Count = ULO.TripCount;
354 
355   // Don't enter the unroll code if there is nothing to do.
356   if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
357     LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
358     return LoopUnrollResult::Unmodified;
359   }
360 
361   assert(ULO.Count > 0);
362   assert(ULO.TripMultiple > 0);
363   assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
364 
365   // Are we eliminating the loop control altogether?
366   bool CompletelyUnroll = ULO.Count == ULO.TripCount;
367   SmallVector<BasicBlock *, 4> ExitBlocks;
368   L->getExitBlocks(ExitBlocks);
369   std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
370 
371   // Go through all exits of L and see if there are any phi-nodes there. We just
372   // conservatively assume that they're inserted to preserve LCSSA form, which
373   // means that complete unrolling might break this form. We need to either fix
374   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
375   // now we just recompute LCSSA for the outer loop, but it should be possible
376   // to fix it in-place.
377   bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
378                         any_of(ExitBlocks, [](const BasicBlock *BB) {
379                           return isa<PHINode>(BB->begin());
380                         });
381 
382   // We assume a run-time trip count if the compiler cannot
383   // figure out the loop trip count and the unroll-runtime
384   // flag is specified.
385   bool RuntimeTripCount =
386       (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime);
387 
388   assert((!RuntimeTripCount || !ULO.PeelCount) &&
389          "Did not expect runtime trip-count unrolling "
390          "and peeling for the same loop");
391 
392   bool Peeled = false;
393   if (ULO.PeelCount) {
394     Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
395 
396     // Successful peeling may result in a change in the loop preheader/trip
397     // counts. If we later unroll the loop, we want these to be updated.
398     if (Peeled) {
399       // According to our guards and profitability checks the only
400       // meaningful exit should be latch block. Other exits go to deopt,
401       // so we do not worry about them.
402       BasicBlock *ExitingBlock = L->getLoopLatch();
403       assert(ExitingBlock && "Loop without exiting block?");
404       assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?");
405       Preheader = L->getLoopPreheader();
406       ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
407       ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
408     }
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   if (Header->getParent()->isDebugInfoForProfiling())
574     for (BasicBlock *BB : L->getBlocks())
575       for (Instruction &I : *BB)
576         if (!isa<DbgInfoIntrinsic>(&I))
577           if (const DILocation *DIL = I.getDebugLoc()) {
578             auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
579             if (NewDIL)
580               I.setDebugLoc(NewDIL.getValue());
581             else
582               LLVM_DEBUG(dbgs()
583                          << "Failed to create new discriminator: "
584                          << DIL->getFilename() << " Line: " << DIL->getLine());
585           }
586 
587   for (unsigned It = 1; It != ULO.Count; ++It) {
588     SmallVector<BasicBlock *, 8> NewBlocks;
589     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
590     NewLoops[L] = L;
591 
592     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
593       ValueToValueMapTy VMap;
594       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
595       Header->getParent()->getBasicBlockList().push_back(New);
596 
597       assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
598              "Header should not be in a sub-loop");
599       // Tell LI about New.
600       const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
601       if (OldLoop)
602         LoopsToSimplify.insert(NewLoops[OldLoop]);
603 
604       if (*BB == Header)
605         // Loop over all of the PHI nodes in the block, changing them to use
606         // the incoming values from the previous block.
607         for (PHINode *OrigPHI : OrigPHINode) {
608           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
609           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
610           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
611             if (It > 1 && L->contains(InValI))
612               InVal = LastValueMap[InValI];
613           VMap[OrigPHI] = InVal;
614           New->getInstList().erase(NewPHI);
615         }
616 
617       // Update our running map of newest clones
618       LastValueMap[*BB] = New;
619       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
620            VI != VE; ++VI)
621         LastValueMap[VI->first] = VI->second;
622 
623       // Add phi entries for newly created values to all exit blocks.
624       for (BasicBlock *Succ : successors(*BB)) {
625         if (L->contains(Succ))
626           continue;
627         for (PHINode &PHI : Succ->phis()) {
628           Value *Incoming = PHI.getIncomingValueForBlock(*BB);
629           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
630           if (It != LastValueMap.end())
631             Incoming = It->second;
632           PHI.addIncoming(Incoming, New);
633         }
634       }
635       // Keep track of new headers and latches as we create them, so that
636       // we can insert the proper branches later.
637       if (*BB == Header)
638         Headers.push_back(New);
639       if (*BB == LatchBlock)
640         Latches.push_back(New);
641 
642       // Keep track of the exiting block and its successor block contained in
643       // the loop for the current iteration.
644       if (ExitingBI) {
645         if (*BB == ExitingBlocks[0])
646           ExitingBlocks.push_back(New);
647         if (*BB == ExitingSucc[0])
648           ExitingSucc.push_back(New);
649       }
650 
651       NewBlocks.push_back(New);
652       UnrolledLoopBlocks.push_back(New);
653 
654       // Update DomTree: since we just copy the loop body, and each copy has a
655       // dedicated entry block (copy of the header block), this header's copy
656       // dominates all copied blocks. That means, dominance relations in the
657       // copied body are the same as in the original body.
658       if (DT) {
659         if (*BB == Header)
660           DT->addNewBlock(New, Latches[It - 1]);
661         else {
662           auto BBDomNode = DT->getNode(*BB);
663           auto BBIDom = BBDomNode->getIDom();
664           BasicBlock *OriginalBBIDom = BBIDom->getBlock();
665           DT->addNewBlock(
666               New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
667         }
668       }
669     }
670 
671     // Remap all instructions in the most recent iteration
672     remapInstructionsInBlocks(NewBlocks, LastValueMap);
673     for (BasicBlock *NewBlock : NewBlocks) {
674       for (Instruction &I : *NewBlock) {
675         if (auto *II = dyn_cast<IntrinsicInst>(&I))
676           if (II->getIntrinsicID() == Intrinsic::assume)
677             AC->registerAssumption(II);
678       }
679     }
680   }
681 
682   // Loop over the PHI nodes in the original block, setting incoming values.
683   for (PHINode *PN : OrigPHINode) {
684     if (CompletelyUnroll) {
685       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
686       Header->getInstList().erase(PN);
687     } else if (ULO.Count > 1) {
688       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
689       // If this value was defined in the loop, take the value defined by the
690       // last iteration of the loop.
691       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
692         if (L->contains(InValI))
693           InVal = LastValueMap[InVal];
694       }
695       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
696       PN->addIncoming(InVal, Latches.back());
697     }
698   }
699 
700   auto setDest = [](BasicBlock *Src, BasicBlock *Dest, BasicBlock *BlockInLoop,
701                     bool NeedConditional, Optional<bool> ContinueOnTrue,
702                     bool IsDestLoopExit) {
703     auto *Term = cast<BranchInst>(Src->getTerminator());
704     if (NeedConditional) {
705       // Update the conditional branch's successor for the following
706       // iteration.
707       assert(ContinueOnTrue.hasValue() &&
708              "Expecting valid ContinueOnTrue when NeedConditional is true");
709       Term->setSuccessor(!(*ContinueOnTrue), Dest);
710     } else {
711       // Remove phi operands at this loop exit
712       if (!IsDestLoopExit) {
713         BasicBlock *BB = Src;
714         for (BasicBlock *Succ : successors(BB)) {
715           // Preserve the incoming value from BB if we are jumping to the block
716           // in the current loop.
717           if (Succ == BlockInLoop)
718             continue;
719           for (PHINode &Phi : Succ->phis())
720             Phi.removeIncomingValue(BB, false);
721         }
722       }
723       // Replace the conditional branch with an unconditional one.
724       BranchInst::Create(Dest, Term);
725       Term->eraseFromParent();
726     }
727   };
728 
729   // Connect latches of the unrolled iterations to the headers of the next
730   // iteration. If the latch is also the exiting block, the conditional branch
731   // may have to be preserved.
732   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
733     // The branch destination.
734     unsigned j = (i + 1) % e;
735     BasicBlock *Dest = Headers[j];
736     bool NeedConditional = LatchIsExiting;
737 
738     if (LatchIsExiting) {
739       if (RuntimeTripCount && j != 0)
740         NeedConditional = false;
741 
742       // For a complete unroll, make the last iteration end with a branch
743       // to the exit block.
744       if (CompletelyUnroll) {
745         if (j == 0)
746           Dest = LoopExit;
747         // If using trip count upper bound to completely unroll, we need to
748         // keep the conditional branch except the last one because the loop
749         // may exit after any iteration.
750         assert(NeedConditional &&
751                "NeedCondition cannot be modified by both complete "
752                "unrolling and runtime unrolling");
753         NeedConditional =
754             (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0));
755       } else if (j != BreakoutTrip &&
756                  (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
757         // If we know the trip count or a multiple of it, we can safely use an
758         // unconditional branch for some iterations.
759         NeedConditional = false;
760       }
761     }
762 
763     setDest(Latches[i], Dest, Headers[i], NeedConditional, ContinueOnTrue,
764             Dest == LoopExit);
765   }
766 
767   if (!LatchIsExiting) {
768     // If the latch is not exiting, we may be able to simplify the conditional
769     // branches in the unrolled exiting blocks.
770     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
771       // The branch destination.
772       unsigned j = (i + 1) % e;
773       bool NeedConditional = true;
774 
775       if (RuntimeTripCount && j != 0)
776         NeedConditional = false;
777 
778       if (CompletelyUnroll)
779         // We cannot drop the conditional branch for the last condition, as we
780         // may have to execute the loop body depending on the condition.
781         NeedConditional = j == 0 || ULO.PreserveCondBr;
782       else if (j != BreakoutTrip &&
783                (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0))
784         // If we know the trip count or a multiple of it, we can safely use an
785         // unconditional branch for some iterations.
786         NeedConditional = false;
787 
788       // Conditional branches from non-latch exiting block have successors
789       // either in the same loop iteration or outside the loop. The branches are
790       // already correct.
791       if (NeedConditional)
792         continue;
793       setDest(ExitingBlocks[i], ExitingSucc[i], ExitingSucc[i], NeedConditional,
794               None, false);
795     }
796 
797     // When completely unrolling, the last latch becomes unreachable.
798     if (CompletelyUnroll) {
799       BranchInst *Term = cast<BranchInst>(Latches.back()->getTerminator());
800       new UnreachableInst(Term->getContext(), Term);
801       Term->eraseFromParent();
802     }
803   }
804 
805   // Update dominators of blocks we might reach through exits.
806   // Immediate dominator of such block might change, because we add more
807   // routes which can lead to the exit: we can now reach it from the copied
808   // iterations too.
809   if (DT && ULO.Count > 1) {
810     for (auto *BB : OriginalLoopBlocks) {
811       auto *BBDomNode = DT->getNode(BB);
812       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
813       for (auto *ChildDomNode : BBDomNode->children()) {
814         auto *ChildBB = ChildDomNode->getBlock();
815         if (!L->contains(ChildBB))
816           ChildrenToUpdate.push_back(ChildBB);
817       }
818       BasicBlock *NewIDom;
819       if (ExitingBI && BB == ExitingBlocks[0]) {
820         // The latch is special because we emit unconditional branches in
821         // some cases where the original loop contained a conditional branch.
822         // Since the latch is always at the bottom of the loop, if the latch
823         // dominated an exit before unrolling, the new dominator of that exit
824         // must also be a latch.  Specifically, the dominator is the first
825         // latch which ends in a conditional branch, or the last latch if
826         // there is no such latch.
827         // For loops exiting from non latch exiting block, we limit the
828         // branch simplification to single exiting block loops.
829         NewIDom = ExitingBlocks.back();
830         for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
831           Instruction *Term = ExitingBlocks[i]->getTerminator();
832           if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
833             NewIDom =
834                 DT->findNearestCommonDominator(ExitingBlocks[i], Latches[i]);
835             break;
836           }
837         }
838       } else {
839         // The new idom of the block will be the nearest common dominator
840         // of all copies of the previous idom. This is equivalent to the
841         // nearest common dominator of the previous idom and the first latch,
842         // which dominates all copies of the previous idom.
843         NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
844       }
845       for (auto *ChildBB : ChildrenToUpdate)
846         DT->changeImmediateDominator(ChildBB, NewIDom);
847     }
848   }
849 
850   assert(!DT || !UnrollVerifyDomtree ||
851          DT->verify(DominatorTree::VerificationLevel::Fast));
852 
853   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
854   // Merge adjacent basic blocks, if possible.
855   for (BasicBlock *Latch : Latches) {
856     BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
857     assert((Term ||
858             (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
859            "Need a branch as terminator, except when fully unrolling with "
860            "unconditional latch");
861     if (Term && Term->isUnconditional()) {
862       BasicBlock *Dest = Term->getSuccessor(0);
863       BasicBlock *Fold = Dest->getUniquePredecessor();
864       if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
865         // Dest has been folded into Fold. Update our worklists accordingly.
866         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
867         UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
868                                              UnrolledLoopBlocks.end(), Dest),
869                                  UnrolledLoopBlocks.end());
870       }
871     }
872   }
873   // Apply updates to the DomTree.
874   DT = &DTU.getDomTree();
875 
876   // At this point, the code is well formed.  We now simplify the unrolled loop,
877   // doing constant propagation and dead code elimination as we go.
878   simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
879                           SE, DT, AC, TTI);
880 
881   NumCompletelyUnrolled += CompletelyUnroll;
882   ++NumUnrolled;
883 
884   Loop *OuterL = L->getParentLoop();
885   // Update LoopInfo if the loop is completely removed.
886   if (CompletelyUnroll)
887     LI->erase(L);
888 
889   // After complete unrolling most of the blocks should be contained in OuterL.
890   // However, some of them might happen to be out of OuterL (e.g. if they
891   // precede a loop exit). In this case we might need to insert PHI nodes in
892   // order to preserve LCSSA form.
893   // We don't need to check this if we already know that we need to fix LCSSA
894   // form.
895   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
896   // it should be possible to fix it in-place.
897   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
898     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
899 
900   // If we have a pass and a DominatorTree we should re-simplify impacted loops
901   // to ensure subsequent analyses can rely on this form. We want to simplify
902   // at least one layer outside of the loop that was unrolled so that any
903   // changes to the parent loop exposed by the unrolling are considered.
904   if (DT) {
905     if (OuterL) {
906       // OuterL includes all loops for which we can break loop-simplify, so
907       // it's sufficient to simplify only it (it'll recursively simplify inner
908       // loops too).
909       if (NeedToFixLCSSA) {
910         // LCSSA must be performed on the outermost affected loop. The unrolled
911         // loop's last loop latch is guaranteed to be in the outermost loop
912         // after LoopInfo's been updated by LoopInfo::erase.
913         Loop *LatchLoop = LI->getLoopFor(Latches.back());
914         Loop *FixLCSSALoop = OuterL;
915         if (!FixLCSSALoop->contains(LatchLoop))
916           while (FixLCSSALoop->getParentLoop() != LatchLoop)
917             FixLCSSALoop = FixLCSSALoop->getParentLoop();
918 
919         formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
920       } else if (PreserveLCSSA) {
921         assert(OuterL->isLCSSAForm(*DT) &&
922                "Loops should be in LCSSA form after loop-unroll.");
923       }
924 
925       // TODO: That potentially might be compile-time expensive. We should try
926       // to fix the loop-simplified form incrementally.
927       simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
928     } else {
929       // Simplify loops for which we might've broken loop-simplify form.
930       for (Loop *SubLoop : LoopsToSimplify)
931         simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
932     }
933   }
934 
935   return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
936                           : LoopUnrollResult::PartiallyUnrolled;
937 }
938 
939 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
940 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
941 /// such metadata node exists, then nullptr is returned.
942 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
943   // First operand should refer to the loop id itself.
944   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
945   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
946 
947   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
948     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
949     if (!MD)
950       continue;
951 
952     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
953     if (!S)
954       continue;
955 
956     if (Name.equals(S->getString()))
957       return MD;
958   }
959   return nullptr;
960 }
961