Revert "Revert r253253 and r253126: "Don't recompute LCSSA after loop-unrolling when...
[oota-llvm.git] / lib / Transforms / Utils / LoopUnroll.cpp
1 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements some loop unrolling utilities. It does not define any
11 // actual pass or policy, but provides a single function to perform loop
12 // unrolling.
13 //
14 // The process of unrolling can produce extraneous basic blocks linked with
15 // unconditional branches.  This will be corrected in the future.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Transforms/Utils/UnrollLoop.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LoopIterator.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/LoopUtils.h"
38 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
39 using namespace llvm;
40
41 #define DEBUG_TYPE "loop-unroll"
42
43 // TODO: Should these be here or in LoopUnroll?
44 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
45 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
46
47 /// RemapInstruction - Convert the instruction operands from referencing the
48 /// current values into those specified by VMap.
49 static inline void RemapInstruction(Instruction *I,
50                                     ValueToValueMapTy &VMap) {
51   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
52     Value *Op = I->getOperand(op);
53     ValueToValueMapTy::iterator It = VMap.find(Op);
54     if (It != VMap.end())
55       I->setOperand(op, It->second);
56   }
57
58   if (PHINode *PN = dyn_cast<PHINode>(I)) {
59     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
60       ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
61       if (It != VMap.end())
62         PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
63     }
64   }
65 }
66
67 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
68 /// only has one predecessor, and that predecessor only has one successor.
69 /// The LoopInfo Analysis that is passed will be kept consistent.  If folding is
70 /// successful references to the containing loop must be removed from
71 /// ScalarEvolution by calling ScalarEvolution::forgetLoop because SE may have
72 /// references to the eliminated BB.  The argument ForgottenLoops contains a set
73 /// of loops that have already been forgotten to prevent redundant, expensive
74 /// calls to ScalarEvolution::forgetLoop.  Returns the new combined block.
75 static BasicBlock *
76 FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI, LPPassManager *LPM,
77                          SmallPtrSetImpl<Loop *> &ForgottenLoops) {
78   // Merge basic blocks into their predecessor if there is only one distinct
79   // pred, and if there is only one distinct successor of the predecessor, and
80   // if there are no PHI nodes.
81   BasicBlock *OnlyPred = BB->getSinglePredecessor();
82   if (!OnlyPred) return nullptr;
83
84   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
85     return nullptr;
86
87   DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
88
89   // Resolve any PHI nodes at the start of the block.  They are all
90   // guaranteed to have exactly one entry if they exist, unless there are
91   // multiple duplicate (but guaranteed to be equal) entries for the
92   // incoming edges.  This occurs when there are multiple edges from
93   // OnlyPred to OnlySucc.
94   FoldSingleEntryPHINodes(BB);
95
96   // Delete the unconditional branch from the predecessor...
97   OnlyPred->getInstList().pop_back();
98
99   // Make all PHI nodes that referred to BB now refer to Pred as their
100   // source...
101   BB->replaceAllUsesWith(OnlyPred);
102
103   // Move all definitions in the successor to the predecessor...
104   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
105
106   // OldName will be valid until erased.
107   StringRef OldName = BB->getName();
108
109   // Erase basic block from the function...
110
111   // ScalarEvolution holds references to loop exit blocks.
112   if (LPM) {
113     if (auto *SEWP =
114             LPM->getAnalysisIfAvailable<ScalarEvolutionWrapperPass>()) {
115       if (Loop *L = LI->getLoopFor(BB)) {
116         if (ForgottenLoops.insert(L).second)
117           SEWP->getSE().forgetLoop(L);
118       }
119     }
120   }
121   LI->removeBlock(BB);
122
123   // Inherit predecessor's name if it exists...
124   if (!OldName.empty() && !OnlyPred->hasName())
125     OnlyPred->setName(OldName);
126
127   BB->eraseFromParent();
128
129   return OnlyPred;
130 }
131
132 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
133 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
134 /// can only fail when the loop's latch block is not terminated by a conditional
135 /// branch instruction. However, if the trip count (and multiple) are not known,
136 /// loop unrolling will mostly produce more code that is no faster.
137 ///
138 /// TripCount is generally defined as the number of times the loop header
139 /// executes. UnrollLoop relaxes the definition to permit early exits: here
140 /// TripCount is the iteration on which control exits LatchBlock if no early
141 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
142 /// terminates LatchBlock in order to remove unnecesssary instances of the
143 /// test. In other words, control may exit the loop prior to TripCount
144 /// iterations via an early branch, but control may not exit the loop from the
145 /// LatchBlock's terminator prior to TripCount iterations.
146 ///
147 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
148 /// execute without exiting the loop.
149 ///
150 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
151 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
152 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
153 /// iterations before branching into the unrolled loop.  UnrollLoop will not
154 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
155 /// AllowExpensiveTripCount is false.
156 ///
157 /// The LoopInfo Analysis that is passed will be kept consistent.
158 ///
159 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
160 /// removed from the LoopPassManager as well. LPM can also be NULL.
161 ///
162 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
163 /// available from the Pass it must also preserve those analyses.
164 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
165                       bool AllowRuntime, bool AllowExpensiveTripCount,
166                       unsigned TripMultiple, LoopInfo *LI, Pass *PP,
167                       LPPassManager *LPM, AssumptionCache *AC) {
168   BasicBlock *Preheader = L->getLoopPreheader();
169   if (!Preheader) {
170     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
171     return false;
172   }
173
174   BasicBlock *LatchBlock = L->getLoopLatch();
175   if (!LatchBlock) {
176     DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
177     return false;
178   }
179
180   // Loops with indirectbr cannot be cloned.
181   if (!L->isSafeToClone()) {
182     DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
183     return false;
184   }
185
186   BasicBlock *Header = L->getHeader();
187   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
188
189   if (!BI || BI->isUnconditional()) {
190     // The loop-rotate pass can be helpful to avoid this in many cases.
191     DEBUG(dbgs() <<
192              "  Can't unroll; loop not terminated by a conditional branch.\n");
193     return false;
194   }
195
196   if (Header->hasAddressTaken()) {
197     // The loop-rotate pass can be helpful to avoid this in many cases.
198     DEBUG(dbgs() <<
199           "  Won't unroll loop: address of header block is taken.\n");
200     return false;
201   }
202
203   if (TripCount != 0)
204     DEBUG(dbgs() << "  Trip Count = " << TripCount << "\n");
205   if (TripMultiple != 1)
206     DEBUG(dbgs() << "  Trip Multiple = " << TripMultiple << "\n");
207
208   // Effectively "DCE" unrolled iterations that are beyond the tripcount
209   // and will never be executed.
210   if (TripCount != 0 && Count > TripCount)
211     Count = TripCount;
212
213   // Don't enter the unroll code if there is nothing to do. This way we don't
214   // need to support "partial unrolling by 1".
215   if (TripCount == 0 && Count < 2)
216     return false;
217
218   assert(Count > 0);
219   assert(TripMultiple > 0);
220   assert(TripCount == 0 || TripCount % TripMultiple == 0);
221
222   // Are we eliminating the loop control altogether?
223   bool CompletelyUnroll = Count == TripCount;
224   SmallVector<BasicBlock *, 4> ExitBlocks;
225   L->getExitBlocks(ExitBlocks);
226   Loop *ParentL = L->getParentLoop();
227   bool AllExitsAreInsideParentLoop = !ParentL ||
228       std::all_of(ExitBlocks.begin(), ExitBlocks.end(),
229                   [&](BasicBlock *BB) { return ParentL->contains(BB); });
230
231   // We assume a run-time trip count if the compiler cannot
232   // figure out the loop trip count and the unroll-runtime
233   // flag is specified.
234   bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
235
236   if (RuntimeTripCount &&
237       !UnrollRuntimeLoopProlog(L, Count, AllowExpensiveTripCount, LI, LPM))
238     return false;
239
240   // Notify ScalarEvolution that the loop will be substantially changed,
241   // if not outright eliminated.
242   auto *SEWP =
243       PP ? PP->getAnalysisIfAvailable<ScalarEvolutionWrapperPass>() : nullptr;
244   ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
245   if (SE)
246     SE->forgetLoop(L);
247
248   // If we know the trip count, we know the multiple...
249   unsigned BreakoutTrip = 0;
250   if (TripCount != 0) {
251     BreakoutTrip = TripCount % Count;
252     TripMultiple = 0;
253   } else {
254     // Figure out what multiple to use.
255     BreakoutTrip = TripMultiple =
256       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
257   }
258
259   // Report the unrolling decision.
260   DebugLoc LoopLoc = L->getStartLoc();
261   Function *F = Header->getParent();
262   LLVMContext &Ctx = F->getContext();
263
264   if (CompletelyUnroll) {
265     DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
266           << " with trip count " << TripCount << "!\n");
267     emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
268                            Twine("completely unrolled loop with ") +
269                                Twine(TripCount) + " iterations");
270   } else {
271     auto EmitDiag = [&](const Twine &T) {
272       emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
273                              "unrolled loop by a factor of " + Twine(Count) +
274                                  T);
275     };
276
277     DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
278           << " by " << Count);
279     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
280       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
281       EmitDiag(" with a breakout at trip " + Twine(BreakoutTrip));
282     } else if (TripMultiple != 1) {
283       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
284       EmitDiag(" with " + Twine(TripMultiple) + " trips per branch");
285     } else if (RuntimeTripCount) {
286       DEBUG(dbgs() << " with run-time trip count");
287       EmitDiag(" with run-time trip count");
288     }
289     DEBUG(dbgs() << "!\n");
290   }
291
292   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
293   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
294
295   // For the first iteration of the loop, we should use the precloned values for
296   // PHI nodes.  Insert associations now.
297   ValueToValueMapTy LastValueMap;
298   std::vector<PHINode*> OrigPHINode;
299   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
300     OrigPHINode.push_back(cast<PHINode>(I));
301   }
302
303   std::vector<BasicBlock*> Headers;
304   std::vector<BasicBlock*> Latches;
305   Headers.push_back(Header);
306   Latches.push_back(LatchBlock);
307
308   // The current on-the-fly SSA update requires blocks to be processed in
309   // reverse postorder so that LastValueMap contains the correct value at each
310   // exit.
311   LoopBlocksDFS DFS(L);
312   DFS.perform(LI);
313
314   // Stash the DFS iterators before adding blocks to the loop.
315   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
316   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
317
318   for (unsigned It = 1; It != Count; ++It) {
319     std::vector<BasicBlock*> NewBlocks;
320     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
321     NewLoops[L] = L;
322
323     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
324       ValueToValueMapTy VMap;
325       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
326       Header->getParent()->getBasicBlockList().push_back(New);
327
328       // Tell LI about New.
329       if (*BB == Header) {
330         assert(LI->getLoopFor(*BB) == L && "Header should not be in a sub-loop");
331         L->addBasicBlockToLoop(New, *LI);
332       } else {
333         // Figure out which loop New is in.
334         const Loop *OldLoop = LI->getLoopFor(*BB);
335         assert(OldLoop && "Should (at least) be in the loop being unrolled!");
336
337         Loop *&NewLoop = NewLoops[OldLoop];
338         if (!NewLoop) {
339           // Found a new sub-loop.
340           assert(*BB == OldLoop->getHeader() &&
341                  "Header should be first in RPO");
342
343           Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
344           assert(NewLoopParent &&
345                  "Expected parent loop before sub-loop in RPO");
346           NewLoop = new Loop;
347           NewLoopParent->addChildLoop(NewLoop);
348
349           // Forget the old loop, since its inputs may have changed.
350           if (SE)
351             SE->forgetLoop(OldLoop);
352         }
353         NewLoop->addBasicBlockToLoop(New, *LI);
354       }
355
356       if (*BB == Header)
357         // Loop over all of the PHI nodes in the block, changing them to use
358         // the incoming values from the previous block.
359         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
360           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
361           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
362           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
363             if (It > 1 && L->contains(InValI))
364               InVal = LastValueMap[InValI];
365           VMap[OrigPHINode[i]] = InVal;
366           New->getInstList().erase(NewPHI);
367         }
368
369       // Update our running map of newest clones
370       LastValueMap[*BB] = New;
371       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
372            VI != VE; ++VI)
373         LastValueMap[VI->first] = VI->second;
374
375       // Add phi entries for newly created values to all exit blocks.
376       for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
377            SI != SE; ++SI) {
378         if (L->contains(*SI))
379           continue;
380         for (BasicBlock::iterator BBI = (*SI)->begin();
381              PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
382           Value *Incoming = phi->getIncomingValueForBlock(*BB);
383           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
384           if (It != LastValueMap.end())
385             Incoming = It->second;
386           phi->addIncoming(Incoming, New);
387         }
388       }
389       // Keep track of new headers and latches as we create them, so that
390       // we can insert the proper branches later.
391       if (*BB == Header)
392         Headers.push_back(New);
393       if (*BB == LatchBlock)
394         Latches.push_back(New);
395
396       NewBlocks.push_back(New);
397     }
398
399     // Remap all instructions in the most recent iteration
400     for (unsigned i = 0; i < NewBlocks.size(); ++i)
401       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
402            E = NewBlocks[i]->end(); I != E; ++I)
403         ::RemapInstruction(&*I, LastValueMap);
404   }
405
406   // Loop over the PHI nodes in the original block, setting incoming values.
407   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
408     PHINode *PN = OrigPHINode[i];
409     if (CompletelyUnroll) {
410       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
411       Header->getInstList().erase(PN);
412     }
413     else if (Count > 1) {
414       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
415       // If this value was defined in the loop, take the value defined by the
416       // last iteration of the loop.
417       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
418         if (L->contains(InValI))
419           InVal = LastValueMap[InVal];
420       }
421       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
422       PN->addIncoming(InVal, Latches.back());
423     }
424   }
425
426   // Now that all the basic blocks for the unrolled iterations are in place,
427   // set up the branches to connect them.
428   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
429     // The original branch was replicated in each unrolled iteration.
430     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
431
432     // The branch destination.
433     unsigned j = (i + 1) % e;
434     BasicBlock *Dest = Headers[j];
435     bool NeedConditional = true;
436
437     if (RuntimeTripCount && j != 0) {
438       NeedConditional = false;
439     }
440
441     // For a complete unroll, make the last iteration end with a branch
442     // to the exit block.
443     if (CompletelyUnroll) {
444       if (j == 0)
445         Dest = LoopExit;
446       NeedConditional = false;
447     }
448
449     // If we know the trip count or a multiple of it, we can safely use an
450     // unconditional branch for some iterations.
451     if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
452       NeedConditional = false;
453     }
454
455     if (NeedConditional) {
456       // Update the conditional branch's successor for the following
457       // iteration.
458       Term->setSuccessor(!ContinueOnTrue, Dest);
459     } else {
460       // Remove phi operands at this loop exit
461       if (Dest != LoopExit) {
462         BasicBlock *BB = Latches[i];
463         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
464              SI != SE; ++SI) {
465           if (*SI == Headers[i])
466             continue;
467           for (BasicBlock::iterator BBI = (*SI)->begin();
468                PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
469             Phi->removeIncomingValue(BB, false);
470           }
471         }
472       }
473       // Replace the conditional branch with an unconditional one.
474       BranchInst::Create(Dest, Term);
475       Term->eraseFromParent();
476     }
477   }
478
479   // Merge adjacent basic blocks, if possible.
480   SmallPtrSet<Loop *, 4> ForgottenLoops;
481   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
482     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
483     if (Term->isUnconditional()) {
484       BasicBlock *Dest = Term->getSuccessor(0);
485       if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM,
486                                                       ForgottenLoops))
487         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
488     }
489   }
490
491   // FIXME: We could register any cloned assumptions instead of clearing the
492   // whole function's cache.
493   AC->clear();
494
495   DominatorTree *DT = nullptr;
496   if (PP) {
497     // FIXME: Reconstruct dom info, because it is not preserved properly.
498     // Incrementally updating domtree after loop unrolling would be easy.
499     if (DominatorTreeWrapperPass *DTWP =
500             PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
501       DT = &DTWP->getDomTree();
502       DT->recalculate(*L->getHeader()->getParent());
503     }
504
505     // Simplify any new induction variables in the partially unrolled loop.
506     if (SE && !CompletelyUnroll) {
507       SmallVector<WeakVH, 16> DeadInsts;
508       simplifyLoopIVs(L, SE, DT, LPM, DeadInsts);
509
510       // Aggressively clean up dead instructions that simplifyLoopIVs already
511       // identified. Any remaining should be cleaned up below.
512       while (!DeadInsts.empty())
513         if (Instruction *Inst =
514             dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
515           RecursivelyDeleteTriviallyDeadInstructions(Inst);
516     }
517   }
518   // At this point, the code is well formed.  We now do a quick sweep over the
519   // inserted code, doing constant propagation and dead code elimination as we
520   // go.
521   const DataLayout &DL = Header->getModule()->getDataLayout();
522   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
523   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
524        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
525     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
526       Instruction *Inst = &*I++;
527
528       if (isInstructionTriviallyDead(Inst))
529         (*BB)->getInstList().erase(Inst);
530       else if (Value *V = SimplifyInstruction(Inst, DL))
531         if (LI->replacementPreservesLCSSAForm(Inst, V)) {
532           Inst->replaceAllUsesWith(V);
533           (*BB)->getInstList().erase(Inst);
534         }
535     }
536
537   NumCompletelyUnrolled += CompletelyUnroll;
538   ++NumUnrolled;
539
540   Loop *OuterL = L->getParentLoop();
541   // Remove the loop from the LoopPassManager if it's completely removed.
542   if (CompletelyUnroll && LPM != nullptr)
543     LPM->deleteLoopFromQueue(L);
544
545   // If we have a pass and a DominatorTree we should re-simplify impacted loops
546   // to ensure subsequent analyses can rely on this form. We want to simplify
547   // at least one layer outside of the loop that was unrolled so that any
548   // changes to the parent loop exposed by the unrolling are considered.
549   if (PP && DT) {
550     if (!OuterL && !CompletelyUnroll)
551       OuterL = L;
552     if (OuterL) {
553       bool Simplified = simplifyLoop(OuterL, DT, LI, PP, SE, AC);
554
555       // LCSSA must be performed on the outermost affected loop. The unrolled
556       // loop's last loop latch is guaranteed to be in the outermost loop after
557       // deleteLoopFromQueue updates LoopInfo.
558       Loop *LatchLoop = LI->getLoopFor(Latches.back());
559       if (!OuterL->contains(LatchLoop))
560         while (OuterL->getParentLoop() != LatchLoop)
561           OuterL = OuterL->getParentLoop();
562
563       if (CompletelyUnroll && (!AllExitsAreInsideParentLoop || Simplified))
564         formLCSSARecursively(*OuterL, *DT, LI, SE);
565       else
566         assert(OuterL->isLCSSAForm(*DT) &&
567                "Loops should be in LCSSA form after loop-unroll.");
568     }
569   }
570
571   return true;
572 }
573
574 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
575 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
576 /// such metadata node exists, then nullptr is returned.
577 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
578   // First operand should refer to the loop id itself.
579   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
580   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
581
582   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
583     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
584     if (!MD)
585       continue;
586
587     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
588     if (!S)
589       continue;
590
591     if (Name.equals(S->getString()))
592       return MD;
593   }
594   return nullptr;
595 }