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