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, ScalarEvolution *SE,
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 (SE) {
113     if (Loop *L = LI->getLoopFor(BB)) {
114       if (ForgottenLoops.insert(L).second)
115         SE->forgetLoop(L);
116     }
117   }
118   LI->removeBlock(BB);
119 
120   // Inherit predecessor's name if it exists...
121   if (!OldName.empty() && !OnlyPred->hasName())
122     OnlyPred->setName(OldName);
123 
124   BB->eraseFromParent();
125 
126   return OnlyPred;
127 }
128 
129 /// Check if unrolling created a situation where we need to insert phi nodes to
130 /// preserve LCSSA form.
131 /// \param Blocks is a vector of basic blocks representing unrolled loop.
132 /// \param L is the outer loop.
133 /// It's possible that some of the blocks are in L, and some are not. In this
134 /// case, if there is a use is outside L, and definition is inside L, we need to
135 /// insert a phi-node, otherwise LCSSA will be broken.
136 /// The function is just a helper function for llvm::UnrollLoop that returns
137 /// true if this situation occurs, indicating that LCSSA needs to be fixed.
138 static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks,
139                                      LoopInfo *LI) {
140   for (BasicBlock *BB : Blocks) {
141     if (LI->getLoopFor(BB) == L)
142       continue;
143     for (Instruction &I : *BB) {
144       for (Use &U : I.operands()) {
145         if (auto Def = dyn_cast<Instruction>(U))
146           if (LI->getLoopFor(Def->getParent()) == L)
147             return true;
148       }
149     }
150   }
151   return false;
152 }
153 
154 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
155 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
156 /// can only fail when the loop's latch block is not terminated by a conditional
157 /// branch instruction. However, if the trip count (and multiple) are not known,
158 /// loop unrolling will mostly produce more code that is no faster.
159 ///
160 /// TripCount is generally defined as the number of times the loop header
161 /// executes. UnrollLoop relaxes the definition to permit early exits: here
162 /// TripCount is the iteration on which control exits LatchBlock if no early
163 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
164 /// terminates LatchBlock in order to remove unnecesssary instances of the
165 /// test. In other words, control may exit the loop prior to TripCount
166 /// iterations via an early branch, but control may not exit the loop from the
167 /// LatchBlock's terminator prior to TripCount iterations.
168 ///
169 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
170 /// execute without exiting the loop.
171 ///
172 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
173 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
174 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
175 /// iterations before branching into the unrolled loop.  UnrollLoop will not
176 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
177 /// AllowExpensiveTripCount is false.
178 ///
179 /// The LoopInfo Analysis that is passed will be kept consistent.
180 ///
181 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
182 /// DominatorTree if they are non-null.
183 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
184                       bool AllowRuntime, bool AllowExpensiveTripCount,
185                       unsigned TripMultiple, LoopInfo *LI, ScalarEvolution *SE,
186                       DominatorTree *DT, AssumptionCache *AC,
187                       bool PreserveLCSSA) {
188   BasicBlock *Preheader = L->getLoopPreheader();
189   if (!Preheader) {
190     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
191     return false;
192   }
193 
194   BasicBlock *LatchBlock = L->getLoopLatch();
195   if (!LatchBlock) {
196     DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
197     return false;
198   }
199 
200   // Loops with indirectbr cannot be cloned.
201   if (!L->isSafeToClone()) {
202     DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
203     return false;
204   }
205 
206   BasicBlock *Header = L->getHeader();
207   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
208 
209   if (!BI || BI->isUnconditional()) {
210     // The loop-rotate pass can be helpful to avoid this in many cases.
211     DEBUG(dbgs() <<
212              "  Can't unroll; loop not terminated by a conditional branch.\n");
213     return false;
214   }
215 
216   if (Header->hasAddressTaken()) {
217     // The loop-rotate pass can be helpful to avoid this in many cases.
218     DEBUG(dbgs() <<
219           "  Won't unroll loop: address of header block is taken.\n");
220     return false;
221   }
222 
223   if (TripCount != 0)
224     DEBUG(dbgs() << "  Trip Count = " << TripCount << "\n");
225   if (TripMultiple != 1)
226     DEBUG(dbgs() << "  Trip Multiple = " << TripMultiple << "\n");
227 
228   // Effectively "DCE" unrolled iterations that are beyond the tripcount
229   // and will never be executed.
230   if (TripCount != 0 && Count > TripCount)
231     Count = TripCount;
232 
233   // Don't enter the unroll code if there is nothing to do. This way we don't
234   // need to support "partial unrolling by 1".
235   if (TripCount == 0 && Count < 2)
236     return false;
237 
238   assert(Count > 0);
239   assert(TripMultiple > 0);
240   assert(TripCount == 0 || TripCount % TripMultiple == 0);
241 
242   // Are we eliminating the loop control altogether?
243   bool CompletelyUnroll = Count == TripCount;
244   SmallVector<BasicBlock *, 4> ExitBlocks;
245   L->getExitBlocks(ExitBlocks);
246 
247   // Go through all exits of L and see if there are any phi-nodes there. We just
248   // conservatively assume that they're inserted to preserve LCSSA form, which
249   // means that complete unrolling might break this form. We need to either fix
250   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
251   // now we just recompute LCSSA for the outer loop, but it should be possible
252   // to fix it in-place.
253   bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
254       std::any_of(ExitBlocks.begin(), ExitBlocks.end(),
255                   [&](BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
256 
257   // We assume a run-time trip count if the compiler cannot
258   // figure out the loop trip count and the unroll-runtime
259   // flag is specified.
260   bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
261 
262   if (RuntimeTripCount &&
263       !UnrollRuntimeLoopProlog(L, Count, AllowExpensiveTripCount, LI, SE, DT,
264                                PreserveLCSSA))
265     return false;
266 
267   // Notify ScalarEvolution that the loop will be substantially changed,
268   // if not outright eliminated.
269   if (SE)
270     SE->forgetLoop(L);
271 
272   // If we know the trip count, we know the multiple...
273   unsigned BreakoutTrip = 0;
274   if (TripCount != 0) {
275     BreakoutTrip = TripCount % Count;
276     TripMultiple = 0;
277   } else {
278     // Figure out what multiple to use.
279     BreakoutTrip = TripMultiple =
280       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
281   }
282 
283   // Report the unrolling decision.
284   DebugLoc LoopLoc = L->getStartLoc();
285   Function *F = Header->getParent();
286   LLVMContext &Ctx = F->getContext();
287 
288   if (CompletelyUnroll) {
289     DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
290           << " with trip count " << TripCount << "!\n");
291     emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
292                            Twine("completely unrolled loop with ") +
293                                Twine(TripCount) + " iterations");
294   } else {
295     auto EmitDiag = [&](const Twine &T) {
296       emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
297                              "unrolled loop by a factor of " + Twine(Count) +
298                                  T);
299     };
300 
301     DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
302           << " by " << Count);
303     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
304       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
305       EmitDiag(" with a breakout at trip " + Twine(BreakoutTrip));
306     } else if (TripMultiple != 1) {
307       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
308       EmitDiag(" with " + Twine(TripMultiple) + " trips per branch");
309     } else if (RuntimeTripCount) {
310       DEBUG(dbgs() << " with run-time trip count");
311       EmitDiag(" with run-time trip count");
312     }
313     DEBUG(dbgs() << "!\n");
314   }
315 
316   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
317   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
318 
319   // For the first iteration of the loop, we should use the precloned values for
320   // PHI nodes.  Insert associations now.
321   ValueToValueMapTy LastValueMap;
322   std::vector<PHINode*> OrigPHINode;
323   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
324     OrigPHINode.push_back(cast<PHINode>(I));
325   }
326 
327   std::vector<BasicBlock*> Headers;
328   std::vector<BasicBlock*> Latches;
329   Headers.push_back(Header);
330   Latches.push_back(LatchBlock);
331 
332   // The current on-the-fly SSA update requires blocks to be processed in
333   // reverse postorder so that LastValueMap contains the correct value at each
334   // exit.
335   LoopBlocksDFS DFS(L);
336   DFS.perform(LI);
337 
338   // Stash the DFS iterators before adding blocks to the loop.
339   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
340   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
341 
342   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
343   for (unsigned It = 1; It != Count; ++It) {
344     std::vector<BasicBlock*> NewBlocks;
345     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
346     NewLoops[L] = L;
347 
348     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
349       ValueToValueMapTy VMap;
350       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
351       Header->getParent()->getBasicBlockList().push_back(New);
352 
353       // Tell LI about New.
354       if (*BB == Header) {
355         assert(LI->getLoopFor(*BB) == L && "Header should not be in a sub-loop");
356         L->addBasicBlockToLoop(New, *LI);
357       } else {
358         // Figure out which loop New is in.
359         const Loop *OldLoop = LI->getLoopFor(*BB);
360         assert(OldLoop && "Should (at least) be in the loop being unrolled!");
361 
362         Loop *&NewLoop = NewLoops[OldLoop];
363         if (!NewLoop) {
364           // Found a new sub-loop.
365           assert(*BB == OldLoop->getHeader() &&
366                  "Header should be first in RPO");
367 
368           Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
369           assert(NewLoopParent &&
370                  "Expected parent loop before sub-loop in RPO");
371           NewLoop = new Loop;
372           NewLoopParent->addChildLoop(NewLoop);
373 
374           // Forget the old loop, since its inputs may have changed.
375           if (SE)
376             SE->forgetLoop(OldLoop);
377         }
378         NewLoop->addBasicBlockToLoop(New, *LI);
379       }
380 
381       if (*BB == Header)
382         // Loop over all of the PHI nodes in the block, changing them to use
383         // the incoming values from the previous block.
384         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
385           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
386           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
387           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
388             if (It > 1 && L->contains(InValI))
389               InVal = LastValueMap[InValI];
390           VMap[OrigPHINode[i]] = InVal;
391           New->getInstList().erase(NewPHI);
392         }
393 
394       // Update our running map of newest clones
395       LastValueMap[*BB] = New;
396       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
397            VI != VE; ++VI)
398         LastValueMap[VI->first] = VI->second;
399 
400       // Add phi entries for newly created values to all exit blocks.
401       for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
402            SI != SE; ++SI) {
403         if (L->contains(*SI))
404           continue;
405         for (BasicBlock::iterator BBI = (*SI)->begin();
406              PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
407           Value *Incoming = phi->getIncomingValueForBlock(*BB);
408           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
409           if (It != LastValueMap.end())
410             Incoming = It->second;
411           phi->addIncoming(Incoming, New);
412         }
413       }
414       // Keep track of new headers and latches as we create them, so that
415       // we can insert the proper branches later.
416       if (*BB == Header)
417         Headers.push_back(New);
418       if (*BB == LatchBlock)
419         Latches.push_back(New);
420 
421       NewBlocks.push_back(New);
422       UnrolledLoopBlocks.push_back(New);
423     }
424 
425     // Remap all instructions in the most recent iteration
426     for (unsigned i = 0; i < NewBlocks.size(); ++i)
427       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
428            E = NewBlocks[i]->end(); I != E; ++I)
429         ::RemapInstruction(&*I, LastValueMap);
430   }
431 
432   // Loop over the PHI nodes in the original block, setting incoming values.
433   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
434     PHINode *PN = OrigPHINode[i];
435     if (CompletelyUnroll) {
436       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
437       Header->getInstList().erase(PN);
438     }
439     else if (Count > 1) {
440       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
441       // If this value was defined in the loop, take the value defined by the
442       // last iteration of the loop.
443       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
444         if (L->contains(InValI))
445           InVal = LastValueMap[InVal];
446       }
447       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
448       PN->addIncoming(InVal, Latches.back());
449     }
450   }
451 
452   // Now that all the basic blocks for the unrolled iterations are in place,
453   // set up the branches to connect them.
454   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
455     // The original branch was replicated in each unrolled iteration.
456     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
457 
458     // The branch destination.
459     unsigned j = (i + 1) % e;
460     BasicBlock *Dest = Headers[j];
461     bool NeedConditional = true;
462 
463     if (RuntimeTripCount && j != 0) {
464       NeedConditional = false;
465     }
466 
467     // For a complete unroll, make the last iteration end with a branch
468     // to the exit block.
469     if (CompletelyUnroll) {
470       if (j == 0)
471         Dest = LoopExit;
472       NeedConditional = false;
473     }
474 
475     // If we know the trip count or a multiple of it, we can safely use an
476     // unconditional branch for some iterations.
477     if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
478       NeedConditional = false;
479     }
480 
481     if (NeedConditional) {
482       // Update the conditional branch's successor for the following
483       // iteration.
484       Term->setSuccessor(!ContinueOnTrue, Dest);
485     } else {
486       // Remove phi operands at this loop exit
487       if (Dest != LoopExit) {
488         BasicBlock *BB = Latches[i];
489         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
490              SI != SE; ++SI) {
491           if (*SI == Headers[i])
492             continue;
493           for (BasicBlock::iterator BBI = (*SI)->begin();
494                PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
495             Phi->removeIncomingValue(BB, false);
496           }
497         }
498       }
499       // Replace the conditional branch with an unconditional one.
500       BranchInst::Create(Dest, Term);
501       Term->eraseFromParent();
502     }
503   }
504 
505   // Merge adjacent basic blocks, if possible.
506   SmallPtrSet<Loop *, 4> ForgottenLoops;
507   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
508     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
509     if (Term->isUnconditional()) {
510       BasicBlock *Dest = Term->getSuccessor(0);
511       if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, SE,
512                                                       ForgottenLoops)) {
513         // Dest has been folded into Fold. Update our worklists accordingly.
514         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
515         UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
516                                              UnrolledLoopBlocks.end(), Dest),
517                                  UnrolledLoopBlocks.end());
518       }
519     }
520   }
521 
522   // FIXME: We could register any cloned assumptions instead of clearing the
523   // whole function's cache.
524   AC->clear();
525 
526   // FIXME: Reconstruct dom info, because it is not preserved properly.
527   // Incrementally updating domtree after loop unrolling would be easy.
528   if (DT)
529     DT->recalculate(*L->getHeader()->getParent());
530 
531   // Simplify any new induction variables in the partially unrolled loop.
532   if (SE && !CompletelyUnroll) {
533     SmallVector<WeakVH, 16> DeadInsts;
534     simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
535 
536     // Aggressively clean up dead instructions that simplifyLoopIVs already
537     // identified. Any remaining should be cleaned up below.
538     while (!DeadInsts.empty())
539       if (Instruction *Inst =
540               dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
541         RecursivelyDeleteTriviallyDeadInstructions(Inst);
542   }
543 
544   // At this point, the code is well formed.  We now do a quick sweep over the
545   // inserted code, doing constant propagation and dead code elimination as we
546   // go.
547   const DataLayout &DL = Header->getModule()->getDataLayout();
548   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
549   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
550        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
551     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
552       Instruction *Inst = &*I++;
553 
554       if (isInstructionTriviallyDead(Inst))
555         (*BB)->getInstList().erase(Inst);
556       else if (Value *V = SimplifyInstruction(Inst, DL))
557         if (LI->replacementPreservesLCSSAForm(Inst, V)) {
558           Inst->replaceAllUsesWith(V);
559           (*BB)->getInstList().erase(Inst);
560         }
561     }
562 
563   NumCompletelyUnrolled += CompletelyUnroll;
564   ++NumUnrolled;
565 
566   Loop *OuterL = L->getParentLoop();
567   // Update LoopInfo if the loop is completely removed.
568   if (CompletelyUnroll)
569     LI->markAsRemoved(L);
570 
571   // After complete unrolling most of the blocks should be contained in OuterL.
572   // However, some of them might happen to be out of OuterL (e.g. if they
573   // precede a loop exit). In this case we might need to insert PHI nodes in
574   // order to preserve LCSSA form.
575   // We don't need to check this if we already know that we need to fix LCSSA
576   // form.
577   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
578   // it should be possible to fix it in-place.
579   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
580     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
581 
582   // If we have a pass and a DominatorTree we should re-simplify impacted loops
583   // to ensure subsequent analyses can rely on this form. We want to simplify
584   // at least one layer outside of the loop that was unrolled so that any
585   // changes to the parent loop exposed by the unrolling are considered.
586   if (DT) {
587     if (!OuterL && !CompletelyUnroll)
588       OuterL = L;
589     if (OuterL) {
590       simplifyLoop(OuterL, DT, LI, SE, AC, PreserveLCSSA);
591 
592       // LCSSA must be performed on the outermost affected loop. The unrolled
593       // loop's last loop latch is guaranteed to be in the outermost loop after
594       // LoopInfo's been updated by markAsRemoved.
595       Loop *LatchLoop = LI->getLoopFor(Latches.back());
596       if (!OuterL->contains(LatchLoop))
597         while (OuterL->getParentLoop() != LatchLoop)
598           OuterL = OuterL->getParentLoop();
599 
600       if (NeedToFixLCSSA)
601         formLCSSARecursively(*OuterL, *DT, LI, SE);
602       else
603         assert(OuterL->isLCSSAForm(*DT) &&
604                "Loops should be in LCSSA form after loop-unroll.");
605     }
606   }
607 
608   return true;
609 }
610 
611 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
612 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
613 /// such metadata node exists, then nullptr is returned.
614 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
615   // First operand should refer to the loop id itself.
616   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
617   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
618 
619   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
620     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
621     if (!MD)
622       continue;
623 
624     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
625     if (!S)
626       continue;
627 
628     if (Name.equals(S->getString()))
629       return MD;
630   }
631   return nullptr;
632 }
633