1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
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 defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG.  Note that the
12 // loops identified may actually be several natural loops that share the same
13 // header node... not just a single natural loop.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Analysis/LoopInfoImpl.h"
21 #include "llvm/Analysis/LoopIterator.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugLoc.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/PassManager.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm>
35 using namespace llvm;
36 
37 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
38 template class llvm::LoopBase<BasicBlock, Loop>;
39 template class llvm::LoopInfoBase<BasicBlock, Loop>;
40 
41 // Always verify loopinfo if expensive checking is enabled.
42 #ifdef EXPENSIVE_CHECKS
43 static bool VerifyLoopInfo = true;
44 #else
45 static bool VerifyLoopInfo = false;
46 #endif
47 static cl::opt<bool,true>
48 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
49                 cl::desc("Verify loop info (time consuming)"));
50 
51 //===----------------------------------------------------------------------===//
52 // Loop implementation
53 //
54 
55 bool Loop::isLoopInvariant(const Value *V) const {
56   if (const Instruction *I = dyn_cast<Instruction>(V))
57     return !contains(I);
58   return true;  // All non-instructions are loop invariant
59 }
60 
61 bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
62   return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
63 }
64 
65 bool Loop::makeLoopInvariant(Value *V, bool &Changed,
66                              Instruction *InsertPt) const {
67   if (Instruction *I = dyn_cast<Instruction>(V))
68     return makeLoopInvariant(I, Changed, InsertPt);
69   return true;  // All non-instructions are loop-invariant.
70 }
71 
72 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
73                              Instruction *InsertPt) const {
74   // Test if the value is already loop-invariant.
75   if (isLoopInvariant(I))
76     return true;
77   if (!isSafeToSpeculativelyExecute(I))
78     return false;
79   if (I->mayReadFromMemory())
80     return false;
81   // EH block instructions are immobile.
82   if (I->isEHPad())
83     return false;
84   // Determine the insertion point, unless one was given.
85   if (!InsertPt) {
86     BasicBlock *Preheader = getLoopPreheader();
87     // Without a preheader, hoisting is not feasible.
88     if (!Preheader)
89       return false;
90     InsertPt = Preheader->getTerminator();
91   }
92   // Don't hoist instructions with loop-variant operands.
93   for (Value *Operand : I->operands())
94     if (!makeLoopInvariant(Operand, Changed, InsertPt))
95       return false;
96 
97   // Hoist.
98   I->moveBefore(InsertPt);
99 
100   // There is possibility of hoisting this instruction above some arbitrary
101   // condition. Any metadata defined on it can be control dependent on this
102   // condition. Conservatively strip it here so that we don't give any wrong
103   // information to the optimizer.
104   I->dropUnknownNonDebugMetadata();
105 
106   Changed = true;
107   return true;
108 }
109 
110 PHINode *Loop::getCanonicalInductionVariable() const {
111   BasicBlock *H = getHeader();
112 
113   BasicBlock *Incoming = nullptr, *Backedge = nullptr;
114   pred_iterator PI = pred_begin(H);
115   assert(PI != pred_end(H) &&
116          "Loop must have at least one backedge!");
117   Backedge = *PI++;
118   if (PI == pred_end(H)) return nullptr;  // dead loop
119   Incoming = *PI++;
120   if (PI != pred_end(H)) return nullptr;  // multiple backedges?
121 
122   if (contains(Incoming)) {
123     if (contains(Backedge))
124       return nullptr;
125     std::swap(Incoming, Backedge);
126   } else if (!contains(Backedge))
127     return nullptr;
128 
129   // Loop over all of the PHI nodes, looking for a canonical indvar.
130   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
131     PHINode *PN = cast<PHINode>(I);
132     if (ConstantInt *CI =
133         dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
134       if (CI->isNullValue())
135         if (Instruction *Inc =
136             dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
137           if (Inc->getOpcode() == Instruction::Add &&
138                 Inc->getOperand(0) == PN)
139             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
140               if (CI->equalsInt(1))
141                 return PN;
142   }
143   return nullptr;
144 }
145 
146 // Check that 'BB' doesn't have any uses outside of the 'L'
147 static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
148                                DominatorTree &DT) {
149   for (const Instruction &I : BB) {
150     // Tokens can't be used in PHI nodes and live-out tokens prevent loop
151     // optimizations, so for the purposes of considered LCSSA form, we
152     // can ignore them.
153     if (I.getType()->isTokenTy())
154       continue;
155 
156     for (const Use &U : I.uses()) {
157       const Instruction *UI = cast<Instruction>(U.getUser());
158       const BasicBlock *UserBB = UI->getParent();
159       if (const PHINode *P = dyn_cast<PHINode>(UI))
160         UserBB = P->getIncomingBlock(U);
161 
162       // Check the current block, as a fast-path, before checking whether
163       // the use is anywhere in the loop.  Most values are used in the same
164       // block they are defined in.  Also, blocks not reachable from the
165       // entry are special; uses in them don't need to go through PHIs.
166       if (UserBB != &BB && !L.contains(UserBB) &&
167           DT.isReachableFromEntry(UserBB))
168         return false;
169     }
170   }
171   return true;
172 }
173 
174 bool Loop::isLCSSAForm(DominatorTree &DT) const {
175   // For each block we check that it doesn't have any uses outside of this loop.
176   return all_of(this->blocks(), [&](const BasicBlock *BB) {
177     return isBlockInLCSSAForm(*this, *BB, DT);
178   });
179 }
180 
181 bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const {
182   // For each block we check that it doesn't have any uses outside of it's
183   // innermost loop. This process will transitivelly guarntee that current loop
184   // and all of the nested loops are in the LCSSA form.
185   return all_of(this->blocks(), [&](const BasicBlock *BB) {
186     return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
187   });
188 }
189 
190 bool Loop::isLoopSimplifyForm() const {
191   // Normal-form loops have a preheader, a single backedge, and all of their
192   // exits have all their predecessors inside the loop.
193   return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
194 }
195 
196 // Routines that reform the loop CFG and split edges often fail on indirectbr.
197 bool Loop::isSafeToClone() const {
198   // Return false if any loop blocks contain indirectbrs, or there are any calls
199   // to noduplicate functions.
200   for (BasicBlock *BB : this->blocks()) {
201     if (isa<IndirectBrInst>(BB->getTerminator()))
202       return false;
203 
204     for (Instruction &I : *BB)
205       if (auto CS = CallSite(&I))
206         if (CS.cannotDuplicate())
207           return false;
208   }
209   return true;
210 }
211 
212 MDNode *Loop::getLoopID() const {
213   MDNode *LoopID = nullptr;
214   if (isLoopSimplifyForm()) {
215     LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop);
216   } else {
217     // Go through each predecessor of the loop header and check the
218     // terminator for the metadata.
219     BasicBlock *H = getHeader();
220     for (BasicBlock *BB : this->blocks()) {
221       TerminatorInst *TI = BB->getTerminator();
222       MDNode *MD = nullptr;
223 
224       // Check if this terminator branches to the loop header.
225       for (BasicBlock *Successor : TI->successors()) {
226         if (Successor == H) {
227           MD = TI->getMetadata(LLVMContext::MD_loop);
228           break;
229         }
230       }
231       if (!MD)
232         return nullptr;
233 
234       if (!LoopID)
235         LoopID = MD;
236       else if (MD != LoopID)
237         return nullptr;
238     }
239   }
240   if (!LoopID || LoopID->getNumOperands() == 0 ||
241       LoopID->getOperand(0) != LoopID)
242     return nullptr;
243   return LoopID;
244 }
245 
246 void Loop::setLoopID(MDNode *LoopID) const {
247   assert(LoopID && "Loop ID should not be null");
248   assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
249   assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
250 
251   if (isLoopSimplifyForm()) {
252     getLoopLatch()->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
253     return;
254   }
255 
256   BasicBlock *H = getHeader();
257   for (BasicBlock *BB : this->blocks()) {
258     TerminatorInst *TI = BB->getTerminator();
259     for (BasicBlock *Successor : TI->successors()) {
260       if (Successor == H)
261         TI->setMetadata(LLVMContext::MD_loop, LoopID);
262     }
263   }
264 }
265 
266 bool Loop::isAnnotatedParallel() const {
267   MDNode *DesiredLoopIdMetadata = getLoopID();
268 
269   if (!DesiredLoopIdMetadata)
270       return false;
271 
272   // The loop branch contains the parallel loop metadata. In order to ensure
273   // that any parallel-loop-unaware optimization pass hasn't added loop-carried
274   // dependencies (thus converted the loop back to a sequential loop), check
275   // that all the memory instructions in the loop contain parallelism metadata
276   // that point to the same unique "loop id metadata" the loop branch does.
277   for (BasicBlock *BB : this->blocks()) {
278     for (Instruction &I : *BB) {
279       if (!I.mayReadOrWriteMemory())
280         continue;
281 
282       // The memory instruction can refer to the loop identifier metadata
283       // directly or indirectly through another list metadata (in case of
284       // nested parallel loops). The loop identifier metadata refers to
285       // itself so we can check both cases with the same routine.
286       MDNode *LoopIdMD =
287           I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
288 
289       if (!LoopIdMD)
290         return false;
291 
292       bool LoopIdMDFound = false;
293       for (const MDOperand &MDOp : LoopIdMD->operands()) {
294         if (MDOp == DesiredLoopIdMetadata) {
295           LoopIdMDFound = true;
296           break;
297         }
298       }
299 
300       if (!LoopIdMDFound)
301         return false;
302     }
303   }
304   return true;
305 }
306 
307 DebugLoc Loop::getStartLoc() const {
308   // If we have a debug location in the loop ID, then use it.
309   if (MDNode *LoopID = getLoopID())
310     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
311       if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i)))
312         return DebugLoc(L);
313 
314   // Try the pre-header first.
315   if (BasicBlock *PHeadBB = getLoopPreheader())
316     if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
317       return DL;
318 
319   // If we have no pre-header or there are no instructions with debug
320   // info in it, try the header.
321   if (BasicBlock *HeadBB = getHeader())
322     return HeadBB->getTerminator()->getDebugLoc();
323 
324   return DebugLoc();
325 }
326 
327 bool Loop::hasDedicatedExits() const {
328   // Each predecessor of each exit block of a normal loop is contained
329   // within the loop.
330   SmallVector<BasicBlock *, 4> ExitBlocks;
331   getExitBlocks(ExitBlocks);
332   for (BasicBlock *BB : ExitBlocks)
333     for (BasicBlock *Predecessor : predecessors(BB))
334       if (!contains(Predecessor))
335         return false;
336   // All the requirements are met.
337   return true;
338 }
339 
340 void
341 Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
342   assert(hasDedicatedExits() &&
343          "getUniqueExitBlocks assumes the loop has canonical form exits!");
344 
345   SmallVector<BasicBlock *, 32> SwitchExitBlocks;
346   for (BasicBlock *BB : this->blocks()) {
347     SwitchExitBlocks.clear();
348     for (BasicBlock *Successor : successors(BB)) {
349       // If block is inside the loop then it is not an exit block.
350       if (contains(Successor))
351         continue;
352 
353       pred_iterator PI = pred_begin(Successor);
354       BasicBlock *FirstPred = *PI;
355 
356       // If current basic block is this exit block's first predecessor
357       // then only insert exit block in to the output ExitBlocks vector.
358       // This ensures that same exit block is not inserted twice into
359       // ExitBlocks vector.
360       if (BB != FirstPred)
361         continue;
362 
363       // If a terminator has more then two successors, for example SwitchInst,
364       // then it is possible that there are multiple edges from current block
365       // to one exit block.
366       if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
367         ExitBlocks.push_back(Successor);
368         continue;
369       }
370 
371       // In case of multiple edges from current block to exit block, collect
372       // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
373       // duplicate edges.
374       if (!is_contained(SwitchExitBlocks, Successor)) {
375         SwitchExitBlocks.push_back(Successor);
376         ExitBlocks.push_back(Successor);
377       }
378     }
379   }
380 }
381 
382 BasicBlock *Loop::getUniqueExitBlock() const {
383   SmallVector<BasicBlock *, 8> UniqueExitBlocks;
384   getUniqueExitBlocks(UniqueExitBlocks);
385   if (UniqueExitBlocks.size() == 1)
386     return UniqueExitBlocks[0];
387   return nullptr;
388 }
389 
390 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
391 LLVM_DUMP_METHOD void Loop::dump() const {
392   print(dbgs());
393 }
394 
395 LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
396   print(dbgs(), /*Depth=*/ 0, /*Verbose=*/ true);
397 }
398 #endif
399 
400 //===----------------------------------------------------------------------===//
401 // UnloopUpdater implementation
402 //
403 
404 namespace {
405 /// Find the new parent loop for all blocks within the "unloop" whose last
406 /// backedges has just been removed.
407 class UnloopUpdater {
408   Loop &Unloop;
409   LoopInfo *LI;
410 
411   LoopBlocksDFS DFS;
412 
413   // Map unloop's immediate subloops to their nearest reachable parents. Nested
414   // loops within these subloops will not change parents. However, an immediate
415   // subloop's new parent will be the nearest loop reachable from either its own
416   // exits *or* any of its nested loop's exits.
417   DenseMap<Loop*, Loop*> SubloopParents;
418 
419   // Flag the presence of an irreducible backedge whose destination is a block
420   // directly contained by the original unloop.
421   bool FoundIB;
422 
423 public:
424   UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
425     Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
426 
427   void updateBlockParents();
428 
429   void removeBlocksFromAncestors();
430 
431   void updateSubloopParents();
432 
433 protected:
434   Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
435 };
436 } // end anonymous namespace
437 
438 /// Update the parent loop for all blocks that are directly contained within the
439 /// original "unloop".
440 void UnloopUpdater::updateBlockParents() {
441   if (Unloop.getNumBlocks()) {
442     // Perform a post order CFG traversal of all blocks within this loop,
443     // propagating the nearest loop from sucessors to predecessors.
444     LoopBlocksTraversal Traversal(DFS, LI);
445     for (BasicBlock *POI : Traversal) {
446 
447       Loop *L = LI->getLoopFor(POI);
448       Loop *NL = getNearestLoop(POI, L);
449 
450       if (NL != L) {
451         // For reducible loops, NL is now an ancestor of Unloop.
452         assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
453                "uninitialized successor");
454         LI->changeLoopFor(POI, NL);
455       }
456       else {
457         // Or the current block is part of a subloop, in which case its parent
458         // is unchanged.
459         assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
460       }
461     }
462   }
463   // Each irreducible loop within the unloop induces a round of iteration using
464   // the DFS result cached by Traversal.
465   bool Changed = FoundIB;
466   for (unsigned NIters = 0; Changed; ++NIters) {
467     assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
468 
469     // Iterate over the postorder list of blocks, propagating the nearest loop
470     // from successors to predecessors as before.
471     Changed = false;
472     for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
473            POE = DFS.endPostorder(); POI != POE; ++POI) {
474 
475       Loop *L = LI->getLoopFor(*POI);
476       Loop *NL = getNearestLoop(*POI, L);
477       if (NL != L) {
478         assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
479                "uninitialized successor");
480         LI->changeLoopFor(*POI, NL);
481         Changed = true;
482       }
483     }
484   }
485 }
486 
487 /// Remove unloop's blocks from all ancestors below their new parents.
488 void UnloopUpdater::removeBlocksFromAncestors() {
489   // Remove all unloop's blocks (including those in nested subloops) from
490   // ancestors below the new parent loop.
491   for (Loop::block_iterator BI = Unloop.block_begin(),
492          BE = Unloop.block_end(); BI != BE; ++BI) {
493     Loop *OuterParent = LI->getLoopFor(*BI);
494     if (Unloop.contains(OuterParent)) {
495       while (OuterParent->getParentLoop() != &Unloop)
496         OuterParent = OuterParent->getParentLoop();
497       OuterParent = SubloopParents[OuterParent];
498     }
499     // Remove blocks from former Ancestors except Unloop itself which will be
500     // deleted.
501     for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
502          OldParent = OldParent->getParentLoop()) {
503       assert(OldParent && "new loop is not an ancestor of the original");
504       OldParent->removeBlockFromLoop(*BI);
505     }
506   }
507 }
508 
509 /// Update the parent loop for all subloops directly nested within unloop.
510 void UnloopUpdater::updateSubloopParents() {
511   while (!Unloop.empty()) {
512     Loop *Subloop = *std::prev(Unloop.end());
513     Unloop.removeChildLoop(std::prev(Unloop.end()));
514 
515     assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
516     if (Loop *Parent = SubloopParents[Subloop])
517       Parent->addChildLoop(Subloop);
518     else
519       LI->addTopLevelLoop(Subloop);
520   }
521 }
522 
523 /// Return the nearest parent loop among this block's successors. If a successor
524 /// is a subloop header, consider its parent to be the nearest parent of the
525 /// subloop's exits.
526 ///
527 /// For subloop blocks, simply update SubloopParents and return NULL.
528 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
529 
530   // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
531   // is considered uninitialized.
532   Loop *NearLoop = BBLoop;
533 
534   Loop *Subloop = nullptr;
535   if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
536     Subloop = NearLoop;
537     // Find the subloop ancestor that is directly contained within Unloop.
538     while (Subloop->getParentLoop() != &Unloop) {
539       Subloop = Subloop->getParentLoop();
540       assert(Subloop && "subloop is not an ancestor of the original loop");
541     }
542     // Get the current nearest parent of the Subloop exits, initially Unloop.
543     NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
544   }
545 
546   succ_iterator I = succ_begin(BB), E = succ_end(BB);
547   if (I == E) {
548     assert(!Subloop && "subloop blocks must have a successor");
549     NearLoop = nullptr; // unloop blocks may now exit the function.
550   }
551   for (; I != E; ++I) {
552     if (*I == BB)
553       continue; // self loops are uninteresting
554 
555     Loop *L = LI->getLoopFor(*I);
556     if (L == &Unloop) {
557       // This successor has not been processed. This path must lead to an
558       // irreducible backedge.
559       assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
560       FoundIB = true;
561     }
562     if (L != &Unloop && Unloop.contains(L)) {
563       // Successor is in a subloop.
564       if (Subloop)
565         continue; // Branching within subloops. Ignore it.
566 
567       // BB branches from the original into a subloop header.
568       assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
569 
570       // Get the current nearest parent of the Subloop's exits.
571       L = SubloopParents[L];
572       // L could be Unloop if the only exit was an irreducible backedge.
573     }
574     if (L == &Unloop) {
575       continue;
576     }
577     // Handle critical edges from Unloop into a sibling loop.
578     if (L && !L->contains(&Unloop)) {
579       L = L->getParentLoop();
580     }
581     // Remember the nearest parent loop among successors or subloop exits.
582     if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
583       NearLoop = L;
584   }
585   if (Subloop) {
586     SubloopParents[Subloop] = NearLoop;
587     return BBLoop;
588   }
589   return NearLoop;
590 }
591 
592 LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) {
593   analyze(DomTree);
594 }
595 
596 void LoopInfo::markAsRemoved(Loop *Unloop) {
597   assert(!Unloop->isInvalid() && "Loop has already been removed");
598   Unloop->invalidate();
599   RemovedLoops.push_back(Unloop);
600 
601   // First handle the special case of no parent loop to simplify the algorithm.
602   if (!Unloop->getParentLoop()) {
603     // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
604     for (Loop::block_iterator I = Unloop->block_begin(),
605                               E = Unloop->block_end();
606          I != E; ++I) {
607 
608       // Don't reparent blocks in subloops.
609       if (getLoopFor(*I) != Unloop)
610         continue;
611 
612       // Blocks no longer have a parent but are still referenced by Unloop until
613       // the Unloop object is deleted.
614       changeLoopFor(*I, nullptr);
615     }
616 
617     // Remove the loop from the top-level LoopInfo object.
618     for (iterator I = begin();; ++I) {
619       assert(I != end() && "Couldn't find loop");
620       if (*I == Unloop) {
621         removeLoop(I);
622         break;
623       }
624     }
625 
626     // Move all of the subloops to the top-level.
627     while (!Unloop->empty())
628       addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
629 
630     return;
631   }
632 
633   // Update the parent loop for all blocks within the loop. Blocks within
634   // subloops will not change parents.
635   UnloopUpdater Updater(Unloop, this);
636   Updater.updateBlockParents();
637 
638   // Remove blocks from former ancestor loops.
639   Updater.removeBlocksFromAncestors();
640 
641   // Add direct subloops as children in their new parent loop.
642   Updater.updateSubloopParents();
643 
644   // Remove unloop from its parent loop.
645   Loop *ParentLoop = Unloop->getParentLoop();
646   for (Loop::iterator I = ParentLoop->begin();; ++I) {
647     assert(I != ParentLoop->end() && "Couldn't find loop");
648     if (*I == Unloop) {
649       ParentLoop->removeChildLoop(I);
650       break;
651     }
652   }
653 }
654 
655 char LoopAnalysis::PassID;
656 
657 LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
658   // FIXME: Currently we create a LoopInfo from scratch for every function.
659   // This may prove to be too wasteful due to deallocating and re-allocating
660   // memory each time for the underlying map and vector datastructures. At some
661   // point it may prove worthwhile to use a freelist and recycle LoopInfo
662   // objects. I don't want to add that kind of complexity until the scope of
663   // the problem is better understood.
664   LoopInfo LI;
665   LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
666   return LI;
667 }
668 
669 PreservedAnalyses LoopPrinterPass::run(Function &F,
670                                        FunctionAnalysisManager &AM) {
671   AM.getResult<LoopAnalysis>(F).print(OS);
672   return PreservedAnalyses::all();
673 }
674 
675 PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
676 PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
677     : OS(OS), Banner(Banner) {}
678 
679 PreservedAnalyses PrintLoopPass::run(Loop &L, AnalysisManager<Loop> &) {
680   OS << Banner;
681   for (auto *Block : L.blocks())
682     if (Block)
683       Block->print(OS);
684     else
685       OS << "Printing <null> block";
686   return PreservedAnalyses::all();
687 }
688 
689 //===----------------------------------------------------------------------===//
690 // LoopInfo implementation
691 //
692 
693 char LoopInfoWrapperPass::ID = 0;
694 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
695                       true, true)
696 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
697 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
698                     true, true)
699 
700 bool LoopInfoWrapperPass::runOnFunction(Function &) {
701   releaseMemory();
702   LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
703   return false;
704 }
705 
706 void LoopInfoWrapperPass::verifyAnalysis() const {
707   // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
708   // function each time verifyAnalysis is called is very expensive. The
709   // -verify-loop-info option can enable this. In order to perform some
710   // checking by default, LoopPass has been taught to call verifyLoop manually
711   // during loop pass sequences.
712   if (VerifyLoopInfo) {
713     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
714     LI.verify(DT);
715   }
716 }
717 
718 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
719   AU.setPreservesAll();
720   AU.addRequired<DominatorTreeWrapperPass>();
721 }
722 
723 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
724   LI.print(OS);
725 }
726 
727 PreservedAnalyses LoopVerifierPass::run(Function &F,
728                                         FunctionAnalysisManager &AM) {
729   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
730   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
731   LI.verify(DT);
732   return PreservedAnalyses::all();
733 }
734 
735 //===----------------------------------------------------------------------===//
736 // LoopBlocksDFS implementation
737 //
738 
739 /// Traverse the loop blocks and store the DFS result.
740 /// Useful for clients that just want the final DFS result and don't need to
741 /// visit blocks during the initial traversal.
742 void LoopBlocksDFS::perform(LoopInfo *LI) {
743   LoopBlocksTraversal Traversal(*this, LI);
744   for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
745          POE = Traversal.end(); POI != POE; ++POI) ;
746 }
747