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/CallSite.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Metadata.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/Use.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/ValueHandle.h"
53 #include "llvm/IR/ValueMap.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/GenericDomTree.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
61 #include "llvm/Transforms/Utils/Cloning.h"
62 #include "llvm/Transforms/Utils/Local.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(NumUnrolledWithHeader, "Number of loops unrolled without a "
86                                  "conditional 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, 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 (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 with a single latch or header
309   // that's a conditional branch exiting the loop.
310   // FIXME: The implementation can be extended to work with more complicated
311   // cases, e.g. loops with multiple latches.
312   BasicBlock *Header = L->getHeader();
313   BranchInst *HeaderBI = dyn_cast<BranchInst>(Header->getTerminator());
314   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
315 
316   // FIXME: Support loops without conditional latch and multiple exiting blocks.
317   if (!BI ||
318       (BI->isUnconditional() && (!HeaderBI || HeaderBI->isUnconditional() ||
319                                  L->getExitingBlock() != Header))) {
320     LLVM_DEBUG(dbgs() << "  Can't unroll; loop not terminated by a conditional "
321                          "branch in the latch or header.\n");
322     return LoopUnrollResult::Unmodified;
323   }
324 
325   auto CheckLatchSuccessors = [&](unsigned S1, unsigned S2) {
326     return BI->isConditional() && BI->getSuccessor(S1) == Header &&
327            !L->contains(BI->getSuccessor(S2));
328   };
329 
330   // If we have a conditional latch, it must exit the loop.
331   if (BI && BI->isConditional() && !CheckLatchSuccessors(0, 1) &&
332       !CheckLatchSuccessors(1, 0)) {
333     LLVM_DEBUG(
334         dbgs() << "Can't unroll; a conditional latch must exit the loop");
335     return LoopUnrollResult::Unmodified;
336   }
337 
338   auto CheckHeaderSuccessors = [&](unsigned S1, unsigned S2) {
339     return HeaderBI && HeaderBI->isConditional() &&
340            L->contains(HeaderBI->getSuccessor(S1)) &&
341            !L->contains(HeaderBI->getSuccessor(S2));
342   };
343 
344   // If we do not have a conditional latch, the header must exit the loop.
345   if (BI && !BI->isConditional() && HeaderBI && HeaderBI->isConditional() &&
346       !CheckHeaderSuccessors(0, 1) && !CheckHeaderSuccessors(1, 0)) {
347     LLVM_DEBUG(dbgs() << "Can't unroll; conditional header must exit the loop");
348     return LoopUnrollResult::Unmodified;
349   }
350 
351   if (Header->hasAddressTaken()) {
352     // The loop-rotate pass can be helpful to avoid this in many cases.
353     LLVM_DEBUG(
354         dbgs() << "  Won't unroll loop: address of header block is taken.\n");
355     return LoopUnrollResult::Unmodified;
356   }
357 
358   if (ULO.TripCount != 0)
359     LLVM_DEBUG(dbgs() << "  Trip Count = " << ULO.TripCount << "\n");
360   if (ULO.TripMultiple != 1)
361     LLVM_DEBUG(dbgs() << "  Trip Multiple = " << ULO.TripMultiple << "\n");
362 
363   // Effectively "DCE" unrolled iterations that are beyond the tripcount
364   // and will never be executed.
365   if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount)
366     ULO.Count = ULO.TripCount;
367 
368   // Don't enter the unroll code if there is nothing to do.
369   if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
370     LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
371     return LoopUnrollResult::Unmodified;
372   }
373 
374   assert(ULO.Count > 0);
375   assert(ULO.TripMultiple > 0);
376   assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
377 
378   // Are we eliminating the loop control altogether?
379   bool CompletelyUnroll = ULO.Count == ULO.TripCount;
380   SmallVector<BasicBlock *, 4> ExitBlocks;
381   L->getExitBlocks(ExitBlocks);
382   std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
383 
384   // Go through all exits of L and see if there are any phi-nodes there. We just
385   // conservatively assume that they're inserted to preserve LCSSA form, which
386   // means that complete unrolling might break this form. We need to either fix
387   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
388   // now we just recompute LCSSA for the outer loop, but it should be possible
389   // to fix it in-place.
390   bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
391                         any_of(ExitBlocks, [](const BasicBlock *BB) {
392                           return isa<PHINode>(BB->begin());
393                         });
394 
395   // We assume a run-time trip count if the compiler cannot
396   // figure out the loop trip count and the unroll-runtime
397   // flag is specified.
398   bool RuntimeTripCount =
399       (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime);
400 
401   assert((!RuntimeTripCount || !ULO.PeelCount) &&
402          "Did not expect runtime trip-count unrolling "
403          "and peeling for the same loop");
404 
405   bool Peeled = false;
406   if (ULO.PeelCount) {
407     Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
408 
409     // Successful peeling may result in a change in the loop preheader/trip
410     // counts. If we later unroll the loop, we want these to be updated.
411     if (Peeled) {
412       // According to our guards and profitability checks the only
413       // meaningful exit should be latch block. Other exits go to deopt,
414       // so we do not worry about them.
415       BasicBlock *ExitingBlock = L->getLoopLatch();
416       assert(ExitingBlock && "Loop without exiting block?");
417       assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?");
418       Preheader = L->getLoopPreheader();
419       ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
420       ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
421     }
422   }
423 
424   // Loops containing convergent instructions must have a count that divides
425   // their TripMultiple.
426   LLVM_DEBUG(
427       {
428         bool HasConvergent = false;
429         for (auto &BB : L->blocks())
430           for (auto &I : *BB)
431             if (auto CS = CallSite(&I))
432               HasConvergent |= CS.isConvergent();
433         assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&
434                "Unroll count must divide trip multiple if loop contains a "
435                "convergent operation.");
436       });
437 
438   bool EpilogProfitability =
439       UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
440                                               : isEpilogProfitable(L);
441 
442   if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 &&
443       !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
444                                   EpilogProfitability, ULO.UnrollRemainder,
445                                   ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
446                                   PreserveLCSSA, RemainderLoop)) {
447     if (ULO.Force)
448       RuntimeTripCount = false;
449     else {
450       LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
451                            "generated when assuming runtime trip count\n");
452       return LoopUnrollResult::Unmodified;
453     }
454   }
455 
456   // If we know the trip count, we know the multiple...
457   unsigned BreakoutTrip = 0;
458   if (ULO.TripCount != 0) {
459     BreakoutTrip = ULO.TripCount % ULO.Count;
460     ULO.TripMultiple = 0;
461   } else {
462     // Figure out what multiple to use.
463     BreakoutTrip = ULO.TripMultiple =
464         (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
465   }
466 
467   using namespace ore;
468   // Report the unrolling decision.
469   if (CompletelyUnroll) {
470     LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
471                       << " with trip count " << ULO.TripCount << "!\n");
472     if (ORE)
473       ORE->emit([&]() {
474         return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
475                                   L->getHeader())
476                << "completely unrolled loop with "
477                << NV("UnrollCount", ULO.TripCount) << " iterations";
478       });
479   } else if (ULO.PeelCount) {
480     LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()
481                       << " with iteration count " << ULO.PeelCount << "!\n");
482     if (ORE)
483       ORE->emit([&]() {
484         return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
485                                   L->getHeader())
486                << " peeled loop by " << NV("PeelCount", ULO.PeelCount)
487                << " iterations";
488       });
489   } else {
490     auto DiagBuilder = [&]() {
491       OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
492                               L->getHeader());
493       return Diag << "unrolled loop by a factor of "
494                   << NV("UnrollCount", ULO.Count);
495     };
496 
497     LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
498                       << ULO.Count);
499     if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) {
500       LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
501       if (ORE)
502         ORE->emit([&]() {
503           return DiagBuilder() << " with a breakout at trip "
504                                << NV("BreakoutTrip", BreakoutTrip);
505         });
506     } else if (ULO.TripMultiple != 1) {
507       LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch");
508       if (ORE)
509         ORE->emit([&]() {
510           return DiagBuilder()
511                  << " with " << NV("TripMultiple", ULO.TripMultiple)
512                  << " trips per branch";
513         });
514     } else if (RuntimeTripCount) {
515       LLVM_DEBUG(dbgs() << " with run-time trip count");
516       if (ORE)
517         ORE->emit(
518             [&]() { return DiagBuilder() << " with run-time trip count"; });
519     }
520     LLVM_DEBUG(dbgs() << "!\n");
521   }
522 
523   // We are going to make changes to this loop. SCEV may be keeping cached info
524   // about it, in particular about backedge taken count. The changes we make
525   // are guaranteed to invalidate this information for our loop. It is tempting
526   // to only invalidate the loop being unrolled, but it is incorrect as long as
527   // all exiting branches from all inner loops have impact on the outer loops,
528   // and if something changes inside them then any of outer loops may also
529   // change. When we forget outermost loop, we also forget all contained loops
530   // and this is what we need here.
531   if (SE) {
532     if (ULO.ForgetAllSCEV)
533       SE->forgetAllLoops();
534     else
535       SE->forgetTopmostLoop(L);
536   }
537 
538   bool ContinueOnTrue;
539   bool LatchIsExiting = BI->isConditional();
540   BasicBlock *LoopExit = nullptr;
541   if (LatchIsExiting) {
542     ContinueOnTrue = L->contains(BI->getSuccessor(0));
543     LoopExit = BI->getSuccessor(ContinueOnTrue);
544   } else {
545     NumUnrolledWithHeader++;
546     ContinueOnTrue = L->contains(HeaderBI->getSuccessor(0));
547     LoopExit = HeaderBI->getSuccessor(ContinueOnTrue);
548   }
549 
550   // For the first iteration of the loop, we should use the precloned values for
551   // PHI nodes.  Insert associations now.
552   ValueToValueMapTy LastValueMap;
553   std::vector<PHINode*> OrigPHINode;
554   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
555     OrigPHINode.push_back(cast<PHINode>(I));
556   }
557 
558   std::vector<BasicBlock *> Headers;
559   std::vector<BasicBlock *> HeaderSucc;
560   std::vector<BasicBlock *> Latches;
561   Headers.push_back(Header);
562   Latches.push_back(LatchBlock);
563 
564   if (!LatchIsExiting) {
565     auto *Term = cast<BranchInst>(Header->getTerminator());
566     if (Term->isUnconditional() || L->contains(Term->getSuccessor(0))) {
567       assert(L->contains(Term->getSuccessor(0)));
568       HeaderSucc.push_back(Term->getSuccessor(0));
569     } else {
570       assert(L->contains(Term->getSuccessor(1)));
571       HeaderSucc.push_back(Term->getSuccessor(1));
572     }
573   }
574 
575   // The current on-the-fly SSA update requires blocks to be processed in
576   // reverse postorder so that LastValueMap contains the correct value at each
577   // exit.
578   LoopBlocksDFS DFS(L);
579   DFS.perform(LI);
580 
581   // Stash the DFS iterators before adding blocks to the loop.
582   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
583   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
584 
585   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
586 
587   // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
588   // might break loop-simplified form for these loops (as they, e.g., would
589   // share the same exit blocks). We'll keep track of loops for which we can
590   // break this so that later we can re-simplify them.
591   SmallSetVector<Loop *, 4> LoopsToSimplify;
592   for (Loop *SubLoop : *L)
593     LoopsToSimplify.insert(SubLoop);
594 
595   if (Header->getParent()->isDebugInfoForProfiling())
596     for (BasicBlock *BB : L->getBlocks())
597       for (Instruction &I : *BB)
598         if (!isa<DbgInfoIntrinsic>(&I))
599           if (const DILocation *DIL = I.getDebugLoc()) {
600             auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
601             if (NewDIL)
602               I.setDebugLoc(NewDIL.getValue());
603             else
604               LLVM_DEBUG(dbgs()
605                          << "Failed to create new discriminator: "
606                          << DIL->getFilename() << " Line: " << DIL->getLine());
607           }
608 
609   for (unsigned It = 1; It != ULO.Count; ++It) {
610     SmallVector<BasicBlock *, 8> NewBlocks;
611     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
612     NewLoops[L] = L;
613 
614     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
615       ValueToValueMapTy VMap;
616       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
617       Header->getParent()->getBasicBlockList().push_back(New);
618 
619       assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
620              "Header should not be in a sub-loop");
621       // Tell LI about New.
622       const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
623       if (OldLoop)
624         LoopsToSimplify.insert(NewLoops[OldLoop]);
625 
626       if (*BB == Header)
627         // Loop over all of the PHI nodes in the block, changing them to use
628         // the incoming values from the previous block.
629         for (PHINode *OrigPHI : OrigPHINode) {
630           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
631           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
632           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
633             if (It > 1 && L->contains(InValI))
634               InVal = LastValueMap[InValI];
635           VMap[OrigPHI] = InVal;
636           New->getInstList().erase(NewPHI);
637         }
638 
639       // Update our running map of newest clones
640       LastValueMap[*BB] = New;
641       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
642            VI != VE; ++VI)
643         LastValueMap[VI->first] = VI->second;
644 
645       // Add phi entries for newly created values to all exit blocks.
646       for (BasicBlock *Succ : successors(*BB)) {
647         if (L->contains(Succ))
648           continue;
649         for (PHINode &PHI : Succ->phis()) {
650           Value *Incoming = PHI.getIncomingValueForBlock(*BB);
651           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
652           if (It != LastValueMap.end())
653             Incoming = It->second;
654           PHI.addIncoming(Incoming, New);
655         }
656       }
657       // Keep track of new headers and latches as we create them, so that
658       // we can insert the proper branches later.
659       if (*BB == Header)
660         Headers.push_back(New);
661       if (*BB == LatchBlock)
662         Latches.push_back(New);
663 
664       // Keep track of the successor of the new header in the current iteration.
665       for (auto *Pred : predecessors(*BB))
666         if (Pred == Header) {
667           HeaderSucc.push_back(New);
668           break;
669         }
670 
671       NewBlocks.push_back(New);
672       UnrolledLoopBlocks.push_back(New);
673 
674       // Update DomTree: since we just copy the loop body, and each copy has a
675       // dedicated entry block (copy of the header block), this header's copy
676       // dominates all copied blocks. That means, dominance relations in the
677       // copied body are the same as in the original body.
678       if (DT) {
679         if (*BB == Header)
680           DT->addNewBlock(New, Latches[It - 1]);
681         else {
682           auto BBDomNode = DT->getNode(*BB);
683           auto BBIDom = BBDomNode->getIDom();
684           BasicBlock *OriginalBBIDom = BBIDom->getBlock();
685           DT->addNewBlock(
686               New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
687         }
688       }
689     }
690 
691     // Remap all instructions in the most recent iteration
692     remapInstructionsInBlocks(NewBlocks, LastValueMap);
693     for (BasicBlock *NewBlock : NewBlocks) {
694       for (Instruction &I : *NewBlock) {
695         if (auto *II = dyn_cast<IntrinsicInst>(&I))
696           if (II->getIntrinsicID() == Intrinsic::assume)
697             AC->registerAssumption(II);
698       }
699     }
700   }
701 
702   // Loop over the PHI nodes in the original block, setting incoming values.
703   for (PHINode *PN : OrigPHINode) {
704     if (CompletelyUnroll) {
705       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
706       Header->getInstList().erase(PN);
707     } else if (ULO.Count > 1) {
708       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
709       // If this value was defined in the loop, take the value defined by the
710       // last iteration of the loop.
711       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
712         if (L->contains(InValI))
713           InVal = LastValueMap[InVal];
714       }
715       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
716       PN->addIncoming(InVal, Latches.back());
717     }
718   }
719 
720   auto setDest = [LoopExit, ContinueOnTrue](BasicBlock *Src, BasicBlock *Dest,
721                                             ArrayRef<BasicBlock *> NextBlocks,
722                                             BasicBlock *BlockInLoop,
723                                             bool NeedConditional) {
724     auto *Term = cast<BranchInst>(Src->getTerminator());
725     if (NeedConditional) {
726       // Update the conditional branch's successor for the following
727       // iteration.
728       Term->setSuccessor(!ContinueOnTrue, Dest);
729     } else {
730       // Remove phi operands at this loop exit
731       if (Dest != LoopExit) {
732         BasicBlock *BB = Src;
733         for (BasicBlock *Succ : successors(BB)) {
734           // Preserve the incoming value from BB if we are jumping to the block
735           // in the current loop.
736           if (Succ == BlockInLoop)
737             continue;
738           for (PHINode &Phi : Succ->phis())
739             Phi.removeIncomingValue(BB, false);
740         }
741       }
742       // Replace the conditional branch with an unconditional one.
743       BranchInst::Create(Dest, Term);
744       Term->eraseFromParent();
745     }
746   };
747 
748   // Now that all the basic blocks for the unrolled iterations are in place,
749   // set up the branches to connect them.
750   if (LatchIsExiting) {
751     // Set up latches to branch to the new header in the unrolled iterations or
752     // the loop exit for the last latch in a fully unrolled loop.
753     for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
754       // The branch destination.
755       unsigned j = (i + 1) % e;
756       BasicBlock *Dest = Headers[j];
757       bool NeedConditional = true;
758 
759       if (RuntimeTripCount && j != 0) {
760         NeedConditional = false;
761       }
762 
763       // For a complete unroll, make the last iteration end with a branch
764       // to the exit block.
765       if (CompletelyUnroll) {
766         if (j == 0)
767           Dest = LoopExit;
768         // If using trip count upper bound to completely unroll, we need to keep
769         // the conditional branch except the last one because the loop may exit
770         // after any iteration.
771         assert(NeedConditional &&
772                "NeedCondition cannot be modified by both complete "
773                "unrolling and runtime unrolling");
774         NeedConditional =
775             (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0));
776       } else if (j != BreakoutTrip &&
777                  (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
778         // If we know the trip count or a multiple of it, we can safely use an
779         // unconditional branch for some iterations.
780         NeedConditional = false;
781       }
782 
783       setDest(Latches[i], Dest, Headers, Headers[i], NeedConditional);
784     }
785   } else {
786     // Setup headers to branch to their new successors in the unrolled
787     // iterations.
788     for (unsigned i = 0, e = Headers.size(); i != e; ++i) {
789       // The branch destination.
790       unsigned j = (i + 1) % e;
791       BasicBlock *Dest = HeaderSucc[i];
792       bool NeedConditional = true;
793 
794       if (RuntimeTripCount && j != 0)
795         NeedConditional = false;
796 
797       if (CompletelyUnroll)
798         // We cannot drop the conditional branch for the last condition, as we
799         // may have to execute the loop body depending on the condition.
800         NeedConditional = j == 0 || ULO.PreserveCondBr;
801       else if (j != BreakoutTrip &&
802                (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0))
803         // If we know the trip count or a multiple of it, we can safely use an
804         // unconditional branch for some iterations.
805         NeedConditional = false;
806 
807       setDest(Headers[i], Dest, Headers, HeaderSucc[i], NeedConditional);
808     }
809 
810     // Set up latches to branch to the new header in the unrolled iterations or
811     // the loop exit for the last latch in a fully unrolled loop.
812 
813     for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
814       // The original branch was replicated in each unrolled iteration.
815       BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
816 
817       // The branch destination.
818       unsigned j = (i + 1) % e;
819       BasicBlock *Dest = Headers[j];
820 
821       // When completely unrolling, the last latch becomes unreachable.
822       if (CompletelyUnroll && j == 0)
823         new UnreachableInst(Term->getContext(), Term);
824       else
825         // Replace the conditional branch with an unconditional one.
826         BranchInst::Create(Dest, Term);
827 
828       Term->eraseFromParent();
829     }
830   }
831 
832   // Update dominators of blocks we might reach through exits.
833   // Immediate dominator of such block might change, because we add more
834   // routes which can lead to the exit: we can now reach it from the copied
835   // iterations too.
836   if (DT && ULO.Count > 1) {
837     for (auto *BB : OriginalLoopBlocks) {
838       auto *BBDomNode = DT->getNode(BB);
839       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
840       for (auto *ChildDomNode : BBDomNode->getChildren()) {
841         auto *ChildBB = ChildDomNode->getBlock();
842         if (!L->contains(ChildBB))
843           ChildrenToUpdate.push_back(ChildBB);
844       }
845       BasicBlock *NewIDom;
846       BasicBlock *&TermBlock = LatchIsExiting ? LatchBlock : Header;
847       auto &TermBlocks = LatchIsExiting ? Latches : Headers;
848       if (BB == TermBlock) {
849         // The latch is special because we emit unconditional branches in
850         // some cases where the original loop contained a conditional branch.
851         // Since the latch is always at the bottom of the loop, if the latch
852         // dominated an exit before unrolling, the new dominator of that exit
853         // must also be a latch.  Specifically, the dominator is the first
854         // latch which ends in a conditional branch, or the last latch if
855         // there is no such latch.
856         // For loops exiting from the header, we limit the supported loops
857         // to have a single exiting block.
858         NewIDom = TermBlocks.back();
859         for (BasicBlock *Iter : TermBlocks) {
860           Instruction *Term = Iter->getTerminator();
861           if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
862             NewIDom = Iter;
863             break;
864           }
865         }
866       } else {
867         // The new idom of the block will be the nearest common dominator
868         // of all copies of the previous idom. This is equivalent to the
869         // nearest common dominator of the previous idom and the first latch,
870         // which dominates all copies of the previous idom.
871         NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
872       }
873       for (auto *ChildBB : ChildrenToUpdate)
874         DT->changeImmediateDominator(ChildBB, NewIDom);
875     }
876   }
877 
878   assert(!DT || !UnrollVerifyDomtree ||
879          DT->verify(DominatorTree::VerificationLevel::Fast));
880 
881   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
882   // Merge adjacent basic blocks, if possible.
883   for (BasicBlock *Latch : Latches) {
884     BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
885     assert((Term ||
886             (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
887            "Need a branch as terminator, except when fully unrolling with "
888            "unconditional latch");
889     if (Term && Term->isUnconditional()) {
890       BasicBlock *Dest = Term->getSuccessor(0);
891       BasicBlock *Fold = Dest->getUniquePredecessor();
892       if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
893         // Dest has been folded into Fold. Update our worklists accordingly.
894         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
895         UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
896                                              UnrolledLoopBlocks.end(), Dest),
897                                  UnrolledLoopBlocks.end());
898       }
899     }
900   }
901   // Apply updates to the DomTree.
902   DT = &DTU.getDomTree();
903 
904   // At this point, the code is well formed.  We now simplify the unrolled loop,
905   // doing constant propagation and dead code elimination as we go.
906   simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
907                           SE, DT, AC, TTI);
908 
909   NumCompletelyUnrolled += CompletelyUnroll;
910   ++NumUnrolled;
911 
912   Loop *OuterL = L->getParentLoop();
913   // Update LoopInfo if the loop is completely removed.
914   if (CompletelyUnroll)
915     LI->erase(L);
916 
917   // After complete unrolling most of the blocks should be contained in OuterL.
918   // However, some of them might happen to be out of OuterL (e.g. if they
919   // precede a loop exit). In this case we might need to insert PHI nodes in
920   // order to preserve LCSSA form.
921   // We don't need to check this if we already know that we need to fix LCSSA
922   // form.
923   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
924   // it should be possible to fix it in-place.
925   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
926     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
927 
928   // If we have a pass and a DominatorTree we should re-simplify impacted loops
929   // to ensure subsequent analyses can rely on this form. We want to simplify
930   // at least one layer outside of the loop that was unrolled so that any
931   // changes to the parent loop exposed by the unrolling are considered.
932   if (DT) {
933     if (OuterL) {
934       // OuterL includes all loops for which we can break loop-simplify, so
935       // it's sufficient to simplify only it (it'll recursively simplify inner
936       // loops too).
937       if (NeedToFixLCSSA) {
938         // LCSSA must be performed on the outermost affected loop. The unrolled
939         // loop's last loop latch is guaranteed to be in the outermost loop
940         // after LoopInfo's been updated by LoopInfo::erase.
941         Loop *LatchLoop = LI->getLoopFor(Latches.back());
942         Loop *FixLCSSALoop = OuterL;
943         if (!FixLCSSALoop->contains(LatchLoop))
944           while (FixLCSSALoop->getParentLoop() != LatchLoop)
945             FixLCSSALoop = FixLCSSALoop->getParentLoop();
946 
947         formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
948       } else if (PreserveLCSSA) {
949         assert(OuterL->isLCSSAForm(*DT) &&
950                "Loops should be in LCSSA form after loop-unroll.");
951       }
952 
953       // TODO: That potentially might be compile-time expensive. We should try
954       // to fix the loop-simplified form incrementally.
955       simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
956     } else {
957       // Simplify loops for which we might've broken loop-simplify form.
958       for (Loop *SubLoop : LoopsToSimplify)
959         simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
960     }
961   }
962 
963   return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
964                           : LoopUnrollResult::PartiallyUnrolled;
965 }
966 
967 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
968 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
969 /// such metadata node exists, then nullptr is returned.
970 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
971   // First operand should refer to the loop id itself.
972   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
973   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
974 
975   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
976     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
977     if (!MD)
978       continue;
979 
980     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
981     if (!S)
982       continue;
983 
984     if (Name.equals(S->getString()))
985       return MD;
986   }
987   return nullptr;
988 }
989