]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/LoopInfoImpl.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Analysis / LoopInfoImpl.h
1 //===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
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 is the generic implementation of LoopInfo used for both Loops and
11 // MachineLoops.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
16 #define LLVM_ANALYSIS_LOOPINFOIMPL_H
17
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/Dominators.h"
24
25 namespace llvm {
26
27 //===----------------------------------------------------------------------===//
28 // APIs for simple analysis of the loop. See header notes.
29
30 /// getExitingBlocks - Return all blocks inside the loop that have successors
31 /// outside of the loop.  These are the blocks _inside of the current loop_
32 /// which branch out.  The returned list is always unique.
33 ///
34 template<class BlockT, class LoopT>
35 void LoopBase<BlockT, LoopT>::
36 getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
37   for (const auto BB : blocks())
38     for (const auto &Succ : children<BlockT*>(BB))
39       if (!contains(Succ)) {
40         // Not in current loop? It must be an exit block.
41         ExitingBlocks.push_back(BB);
42         break;
43       }
44 }
45
46 /// getExitingBlock - If getExitingBlocks would return exactly one block,
47 /// return that block. Otherwise return null.
48 template<class BlockT, class LoopT>
49 BlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
50   SmallVector<BlockT*, 8> ExitingBlocks;
51   getExitingBlocks(ExitingBlocks);
52   if (ExitingBlocks.size() == 1)
53     return ExitingBlocks[0];
54   return nullptr;
55 }
56
57 /// getExitBlocks - Return all of the successor blocks of this loop.  These
58 /// are the blocks _outside of the current loop_ which are branched to.
59 ///
60 template<class BlockT, class LoopT>
61 void LoopBase<BlockT, LoopT>::
62 getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
63   for (const auto BB : blocks())
64     for (const auto &Succ : children<BlockT*>(BB))
65       if (!contains(Succ))
66         // Not in current loop? It must be an exit block.
67         ExitBlocks.push_back(Succ);
68 }
69
70 /// getExitBlock - If getExitBlocks would return exactly one block,
71 /// return that block. Otherwise return null.
72 template<class BlockT, class LoopT>
73 BlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
74   SmallVector<BlockT*, 8> ExitBlocks;
75   getExitBlocks(ExitBlocks);
76   if (ExitBlocks.size() == 1)
77     return ExitBlocks[0];
78   return nullptr;
79 }
80
81 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
82 template<class BlockT, class LoopT>
83 void LoopBase<BlockT, LoopT>::
84 getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
85   for (const auto BB : blocks())
86     for (const auto &Succ : children<BlockT*>(BB))
87       if (!contains(Succ))
88         // Not in current loop? It must be an exit block.
89         ExitEdges.emplace_back(BB, Succ);
90 }
91
92 /// getLoopPreheader - If there is a preheader for this loop, return it.  A
93 /// loop has a preheader if there is only one edge to the header of the loop
94 /// from outside of the loop and it is legal to hoist instructions into the
95 /// predecessor. If this is the case, the block branching to the header of the
96 /// loop is the preheader node.
97 ///
98 /// This method returns null if there is no preheader for the loop.
99 ///
100 template<class BlockT, class LoopT>
101 BlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
102   // Keep track of nodes outside the loop branching to the header...
103   BlockT *Out = getLoopPredecessor();
104   if (!Out) return nullptr;
105
106   // Make sure we are allowed to hoist instructions into the predecessor.
107   if (!Out->isLegalToHoistInto())
108     return nullptr;
109
110   // Make sure there is only one exit out of the preheader.
111   typedef GraphTraits<BlockT*> BlockTraits;
112   typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
113   ++SI;
114   if (SI != BlockTraits::child_end(Out))
115     return nullptr;  // Multiple exits from the block, must not be a preheader.
116
117   // The predecessor has exactly one successor, so it is a preheader.
118   return Out;
119 }
120
121 /// getLoopPredecessor - If the given loop's header has exactly one unique
122 /// predecessor outside the loop, return it. Otherwise return null.
123 /// This is less strict that the loop "preheader" concept, which requires
124 /// the predecessor to have exactly one successor.
125 ///
126 template<class BlockT, class LoopT>
127 BlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
128   // Keep track of nodes outside the loop branching to the header...
129   BlockT *Out = nullptr;
130
131   // Loop over the predecessors of the header node...
132   BlockT *Header = getHeader();
133   for (const auto Pred : children<Inverse<BlockT*>>(Header)) {
134     if (!contains(Pred)) {     // If the block is not in the loop...
135       if (Out && Out != Pred)
136         return nullptr;     // Multiple predecessors outside the loop
137       Out = Pred;
138     }
139   }
140
141   // Make sure there is only one exit out of the preheader.
142   assert(Out && "Header of loop has no predecessors from outside loop?");
143   return Out;
144 }
145
146 /// getLoopLatch - If there is a single latch block for this loop, return it.
147 /// A latch block is a block that contains a branch back to the header.
148 template<class BlockT, class LoopT>
149 BlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
150   BlockT *Header = getHeader();
151   BlockT *Latch = nullptr;
152   for (const auto Pred : children<Inverse<BlockT*>>(Header)) {
153     if (contains(Pred)) {
154       if (Latch) return nullptr;
155       Latch = Pred;
156     }
157   }
158
159   return Latch;
160 }
161
162 //===----------------------------------------------------------------------===//
163 // APIs for updating loop information after changing the CFG
164 //
165
166 /// addBasicBlockToLoop - This method is used by other analyses to update loop
167 /// information.  NewBB is set to be a new member of the current loop.
168 /// Because of this, it is added as a member of all parent loops, and is added
169 /// to the specified LoopInfo object as being in the current basic block.  It
170 /// is not valid to replace the loop header with this method.
171 ///
172 template<class BlockT, class LoopT>
173 void LoopBase<BlockT, LoopT>::
174 addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
175 #ifndef NDEBUG
176   if (!Blocks.empty()) {
177     auto SameHeader = LIB[getHeader()];
178     assert(contains(SameHeader) && getHeader() == SameHeader->getHeader()
179            && "Incorrect LI specified for this loop!");
180   }
181 #endif
182   assert(NewBB && "Cannot add a null basic block to the loop!");
183   assert(!LIB[NewBB] && "BasicBlock already in the loop!");
184
185   LoopT *L = static_cast<LoopT *>(this);
186
187   // Add the loop mapping to the LoopInfo object...
188   LIB.BBMap[NewBB] = L;
189
190   // Add the basic block to this loop and all parent loops...
191   while (L) {
192     L->addBlockEntry(NewBB);
193     L = L->getParentLoop();
194   }
195 }
196
197 /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
198 /// the OldChild entry in our children list with NewChild, and updates the
199 /// parent pointer of OldChild to be null and the NewChild to be this loop.
200 /// This updates the loop depth of the new child.
201 template<class BlockT, class LoopT>
202 void LoopBase<BlockT, LoopT>::
203 replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild) {
204   assert(OldChild->ParentLoop == this && "This loop is already broken!");
205   assert(!NewChild->ParentLoop && "NewChild already has a parent!");
206   typename std::vector<LoopT *>::iterator I = find(SubLoops, OldChild);
207   assert(I != SubLoops.end() && "OldChild not in loop!");
208   *I = NewChild;
209   OldChild->ParentLoop = nullptr;
210   NewChild->ParentLoop = static_cast<LoopT *>(this);
211 }
212
213 /// verifyLoop - Verify loop structure
214 template<class BlockT, class LoopT>
215 void LoopBase<BlockT, LoopT>::verifyLoop() const {
216 #ifndef NDEBUG
217   assert(!Blocks.empty() && "Loop header is missing");
218
219   // Setup for using a depth-first iterator to visit every block in the loop.
220   SmallVector<BlockT*, 8> ExitBBs;
221   getExitBlocks(ExitBBs);
222   df_iterator_default_set<BlockT*> VisitSet;
223   VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
224   df_ext_iterator<BlockT*, df_iterator_default_set<BlockT*>>
225     BI = df_ext_begin(getHeader(), VisitSet),
226     BE = df_ext_end(getHeader(), VisitSet);
227
228   // Keep track of the BBs visited.
229   SmallPtrSet<BlockT*, 8> VisitedBBs;
230
231   // Check the individual blocks.
232   for ( ; BI != BE; ++BI) {
233     BlockT *BB = *BI;
234
235     assert(std::any_of(GraphTraits<BlockT*>::child_begin(BB),
236                        GraphTraits<BlockT*>::child_end(BB),
237                        [&](BlockT *B){return contains(B);}) &&
238            "Loop block has no in-loop successors!");
239
240     assert(std::any_of(GraphTraits<Inverse<BlockT*> >::child_begin(BB),
241                        GraphTraits<Inverse<BlockT*> >::child_end(BB),
242                        [&](BlockT *B){return contains(B);}) &&
243            "Loop block has no in-loop predecessors!");
244
245     SmallVector<BlockT *, 2> OutsideLoopPreds;
246     std::for_each(GraphTraits<Inverse<BlockT*> >::child_begin(BB),
247                   GraphTraits<Inverse<BlockT*> >::child_end(BB),
248                   [&](BlockT *B){if (!contains(B))
249                       OutsideLoopPreds.push_back(B);
250                   });
251
252     if (BB == getHeader()) {
253         assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
254     } else if (!OutsideLoopPreds.empty()) {
255       // A non-header loop shouldn't be reachable from outside the loop,
256       // though it is permitted if the predecessor is not itself actually
257       // reachable.
258       BlockT *EntryBB = &BB->getParent()->front();
259       for (BlockT *CB : depth_first(EntryBB))
260         for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
261           assert(CB != OutsideLoopPreds[i] &&
262                  "Loop has multiple entry points!");
263     }
264     assert(BB != &getHeader()->getParent()->front() &&
265            "Loop contains function entry block!");
266
267     VisitedBBs.insert(BB);
268   }
269
270   if (VisitedBBs.size() != getNumBlocks()) {
271     dbgs() << "The following blocks are unreachable in the loop: ";
272     for (auto BB : Blocks) {
273       if (!VisitedBBs.count(BB)) {
274         dbgs() << *BB << "\n";
275       }
276     }
277     assert(false && "Unreachable block in loop");
278   }
279
280   // Check the subloops.
281   for (iterator I = begin(), E = end(); I != E; ++I)
282     // Each block in each subloop should be contained within this loop.
283     for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
284          BI != BE; ++BI) {
285         assert(contains(*BI) &&
286                "Loop does not contain all the blocks of a subloop!");
287     }
288
289   // Check the parent loop pointer.
290   if (ParentLoop) {
291     assert(is_contained(*ParentLoop, this) &&
292            "Loop is not a subloop of its parent!");
293   }
294 #endif
295 }
296
297 /// verifyLoop - Verify loop structure of this loop and all nested loops.
298 template<class BlockT, class LoopT>
299 void LoopBase<BlockT, LoopT>::verifyLoopNest(
300   DenseSet<const LoopT*> *Loops) const {
301   Loops->insert(static_cast<const LoopT *>(this));
302   // Verify this loop.
303   verifyLoop();
304   // Verify the subloops.
305   for (iterator I = begin(), E = end(); I != E; ++I)
306     (*I)->verifyLoopNest(Loops);
307 }
308
309 template<class BlockT, class LoopT>
310 void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth,
311                                     bool Verbose) const {
312   OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
313        << " containing: ";
314
315   BlockT *H = getHeader();
316   for (unsigned i = 0; i < getBlocks().size(); ++i) {
317     BlockT *BB = getBlocks()[i];
318     if (!Verbose) {
319       if (i) OS << ",";
320       BB->printAsOperand(OS, false);
321     } else OS << "\n";
322
323     if (BB == H) OS << "<header>";
324     if (isLoopLatch(BB)) OS << "<latch>";
325     if (isLoopExiting(BB)) OS << "<exiting>";
326     if (Verbose)
327       BB->print(OS);
328   }
329   OS << "\n";
330
331   for (iterator I = begin(), E = end(); I != E; ++I)
332     (*I)->print(OS, Depth+2);
333 }
334
335 //===----------------------------------------------------------------------===//
336 /// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
337 /// result does / not depend on use list (block predecessor) order.
338 ///
339
340 /// Discover a subloop with the specified backedges such that: All blocks within
341 /// this loop are mapped to this loop or a subloop. And all subloops within this
342 /// loop have their parent loop set to this loop or a subloop.
343 template<class BlockT, class LoopT>
344 static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT*> Backedges,
345                                   LoopInfoBase<BlockT, LoopT> *LI,
346                                   const DominatorTreeBase<BlockT> &DomTree) {
347   typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
348
349   unsigned NumBlocks = 0;
350   unsigned NumSubloops = 0;
351
352   // Perform a backward CFG traversal using a worklist.
353   std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
354   while (!ReverseCFGWorklist.empty()) {
355     BlockT *PredBB = ReverseCFGWorklist.back();
356     ReverseCFGWorklist.pop_back();
357
358     LoopT *Subloop = LI->getLoopFor(PredBB);
359     if (!Subloop) {
360       if (!DomTree.isReachableFromEntry(PredBB))
361         continue;
362
363       // This is an undiscovered block. Map it to the current loop.
364       LI->changeLoopFor(PredBB, L);
365       ++NumBlocks;
366       if (PredBB == L->getHeader())
367           continue;
368       // Push all block predecessors on the worklist.
369       ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
370                                 InvBlockTraits::child_begin(PredBB),
371                                 InvBlockTraits::child_end(PredBB));
372     }
373     else {
374       // This is a discovered block. Find its outermost discovered loop.
375       while (LoopT *Parent = Subloop->getParentLoop())
376         Subloop = Parent;
377
378       // If it is already discovered to be a subloop of this loop, continue.
379       if (Subloop == L)
380         continue;
381
382       // Discover a subloop of this loop.
383       Subloop->setParentLoop(L);
384       ++NumSubloops;
385       NumBlocks += Subloop->getBlocks().capacity();
386       PredBB = Subloop->getHeader();
387       // Continue traversal along predecessors that are not loop-back edges from
388       // within this subloop tree itself. Note that a predecessor may directly
389       // reach another subloop that is not yet discovered to be a subloop of
390       // this loop, which we must traverse.
391       for (const auto Pred : children<Inverse<BlockT*>>(PredBB)) {
392         if (LI->getLoopFor(Pred) != Subloop)
393           ReverseCFGWorklist.push_back(Pred);
394       }
395     }
396   }
397   L->getSubLoopsVector().reserve(NumSubloops);
398   L->reserveBlocks(NumBlocks);
399 }
400
401 /// Populate all loop data in a stable order during a single forward DFS.
402 template<class BlockT, class LoopT>
403 class PopulateLoopsDFS {
404   typedef GraphTraits<BlockT*> BlockTraits;
405   typedef typename BlockTraits::ChildIteratorType SuccIterTy;
406
407   LoopInfoBase<BlockT, LoopT> *LI;
408 public:
409   PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
410     LI(li) {}
411
412   void traverse(BlockT *EntryBlock);
413
414 protected:
415   void insertIntoLoop(BlockT *Block);
416 };
417
418 /// Top-level driver for the forward DFS within the loop.
419 template<class BlockT, class LoopT>
420 void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
421   for (BlockT *BB : post_order(EntryBlock))
422     insertIntoLoop(BB);
423 }
424
425 /// Add a single Block to its ancestor loops in PostOrder. If the block is a
426 /// subloop header, add the subloop to its parent in PostOrder, then reverse the
427 /// Block and Subloop vectors of the now complete subloop to achieve RPO.
428 template<class BlockT, class LoopT>
429 void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
430   LoopT *Subloop = LI->getLoopFor(Block);
431   if (Subloop && Block == Subloop->getHeader()) {
432     // We reach this point once per subloop after processing all the blocks in
433     // the subloop.
434     if (Subloop->getParentLoop())
435       Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
436     else
437       LI->addTopLevelLoop(Subloop);
438
439     // For convenience, Blocks and Subloops are inserted in postorder. Reverse
440     // the lists, except for the loop header, which is always at the beginning.
441     Subloop->reverseBlock(1);
442     std::reverse(Subloop->getSubLoopsVector().begin(),
443                  Subloop->getSubLoopsVector().end());
444
445     Subloop = Subloop->getParentLoop();
446   }
447   for (; Subloop; Subloop = Subloop->getParentLoop())
448     Subloop->addBlockEntry(Block);
449 }
450
451 /// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
452 /// interleaved with backward CFG traversals within each subloop
453 /// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
454 /// this part of the algorithm is linear in the number of CFG edges. Subloop and
455 /// Block vectors are then populated during a single forward CFG traversal
456 /// (PopulateLoopDFS).
457 ///
458 /// During the two CFG traversals each block is seen three times:
459 /// 1) Discovered and mapped by a reverse CFG traversal.
460 /// 2) Visited during a forward DFS CFG traversal.
461 /// 3) Reverse-inserted in the loop in postorder following forward DFS.
462 ///
463 /// The Block vectors are inclusive, so step 3 requires loop-depth number of
464 /// insertions per block.
465 template<class BlockT, class LoopT>
466 void LoopInfoBase<BlockT, LoopT>::
467 analyze(const DominatorTreeBase<BlockT> &DomTree) {
468
469   // Postorder traversal of the dominator tree.
470   const DomTreeNodeBase<BlockT> *DomRoot = DomTree.getRootNode();
471   for (auto DomNode : post_order(DomRoot)) {
472
473     BlockT *Header = DomNode->getBlock();
474     SmallVector<BlockT *, 4> Backedges;
475
476     // Check each predecessor of the potential loop header.
477     for (const auto Backedge : children<Inverse<BlockT*>>(Header)) {
478       // If Header dominates predBB, this is a new loop. Collect the backedges.
479       if (DomTree.dominates(Header, Backedge)
480           && DomTree.isReachableFromEntry(Backedge)) {
481         Backedges.push_back(Backedge);
482       }
483     }
484     // Perform a backward CFG traversal to discover and map blocks in this loop.
485     if (!Backedges.empty()) {
486       LoopT *L = new LoopT(Header);
487       discoverAndMapSubloop(L, ArrayRef<BlockT*>(Backedges), this, DomTree);
488     }
489   }
490   // Perform a single forward CFG traversal to populate block and subloop
491   // vectors for all loops.
492   PopulateLoopsDFS<BlockT, LoopT> DFS(this);
493   DFS.traverse(DomRoot->getBlock());
494 }
495
496 template <class BlockT, class LoopT>
497 SmallVector<LoopT *, 4> LoopInfoBase<BlockT, LoopT>::getLoopsInPreorder() {
498   SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
499   // The outer-most loop actually goes into the result in the same relative
500   // order as we walk it. But LoopInfo stores the top level loops in reverse
501   // program order so for here we reverse it to get forward program order.
502   // FIXME: If we change the order of LoopInfo we will want to remove the
503   // reverse here.
504   for (LoopT *RootL : reverse(*this)) {
505     assert(PreOrderWorklist.empty() &&
506            "Must start with an empty preorder walk worklist.");
507     PreOrderWorklist.push_back(RootL);
508     do {
509       LoopT *L = PreOrderWorklist.pop_back_val();
510       // Sub-loops are stored in forward program order, but will process the
511       // worklist backwards so append them in reverse order.
512       PreOrderWorklist.append(L->rbegin(), L->rend());
513       PreOrderLoops.push_back(L);
514     } while (!PreOrderWorklist.empty());
515   }
516
517   return PreOrderLoops;
518 }
519
520 template <class BlockT, class LoopT>
521 SmallVector<LoopT *, 4>
522 LoopInfoBase<BlockT, LoopT>::getLoopsInReverseSiblingPreorder() {
523   SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
524   // The outer-most loop actually goes into the result in the same relative
525   // order as we walk it. LoopInfo stores the top level loops in reverse
526   // program order so we walk in order here.
527   // FIXME: If we change the order of LoopInfo we will want to add a reverse
528   // here.
529   for (LoopT *RootL : *this) {
530     assert(PreOrderWorklist.empty() &&
531            "Must start with an empty preorder walk worklist.");
532     PreOrderWorklist.push_back(RootL);
533     do {
534       LoopT *L = PreOrderWorklist.pop_back_val();
535       // Sub-loops are stored in forward program order, but will process the
536       // worklist backwards so we can just append them in order.
537       PreOrderWorklist.append(L->begin(), L->end());
538       PreOrderLoops.push_back(L);
539     } while (!PreOrderWorklist.empty());
540   }
541
542   return PreOrderLoops;
543 }
544
545 // Debugging
546 template<class BlockT, class LoopT>
547 void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
548   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
549     TopLevelLoops[i]->print(OS);
550 #if 0
551   for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
552          E = BBMap.end(); I != E; ++I)
553     OS << "BB '" << I->first->getName() << "' level = "
554        << I->second->getLoopDepth() << "\n";
555 #endif
556 }
557
558 template <typename T>
559 bool compareVectors(std::vector<T> &BB1, std::vector<T> &BB2) {
560   std::sort(BB1.begin(), BB1.end());
561   std::sort(BB2.begin(), BB2.end());
562   return BB1 == BB2;
563 }
564
565 template <class BlockT, class LoopT>
566 void addInnerLoopsToHeadersMap(DenseMap<BlockT *, const LoopT *> &LoopHeaders,
567                                const LoopInfoBase<BlockT, LoopT> &LI,
568                                const LoopT &L) {
569   LoopHeaders[L.getHeader()] = &L;
570   for (LoopT *SL : L)
571     addInnerLoopsToHeadersMap(LoopHeaders, LI, *SL);
572 }
573
574 #ifndef NDEBUG
575 template <class BlockT, class LoopT>
576 static void compareLoops(const LoopT *L, const LoopT *OtherL,
577                          DenseMap<BlockT *, const LoopT *> &OtherLoopHeaders) {
578   BlockT *H = L->getHeader();
579   BlockT *OtherH = OtherL->getHeader();
580   assert(H == OtherH &&
581          "Mismatched headers even though found in the same map entry!");
582
583   assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
584          "Mismatched loop depth!");
585   const LoopT *ParentL = L, *OtherParentL = OtherL;
586   do {
587     assert(ParentL->getHeader() == OtherParentL->getHeader() &&
588            "Mismatched parent loop headers!");
589     ParentL = ParentL->getParentLoop();
590     OtherParentL = OtherParentL->getParentLoop();
591   } while (ParentL);
592
593   for (const LoopT *SubL : *L) {
594     BlockT *SubH = SubL->getHeader();
595     const LoopT *OtherSubL = OtherLoopHeaders.lookup(SubH);
596     assert(OtherSubL && "Inner loop is missing in computed loop info!");
597     OtherLoopHeaders.erase(SubH);
598     compareLoops(SubL, OtherSubL, OtherLoopHeaders);
599   }
600
601   std::vector<BlockT *> BBs = L->getBlocks();
602   std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
603   assert(compareVectors(BBs, OtherBBs) &&
604          "Mismatched basic blocks in the loops!");
605 }
606 #endif
607
608 template <class BlockT, class LoopT>
609 void LoopInfoBase<BlockT, LoopT>::verify(
610     const DominatorTreeBase<BlockT> &DomTree) const {
611   DenseSet<const LoopT*> Loops;
612   for (iterator I = begin(), E = end(); I != E; ++I) {
613     assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
614     (*I)->verifyLoopNest(&Loops);
615   }
616
617   // Verify that blocks are mapped to valid loops.
618 #ifndef NDEBUG
619   for (auto &Entry : BBMap) {
620     const BlockT *BB = Entry.first;
621     LoopT *L = Entry.second;
622     assert(Loops.count(L) && "orphaned loop");
623     assert(L->contains(BB) && "orphaned block");
624   }
625
626   // Recompute LoopInfo to verify loops structure.
627   LoopInfoBase<BlockT, LoopT> OtherLI;
628   OtherLI.analyze(DomTree);
629
630   // Build a map we can use to move from our LI to the computed one. This
631   // allows us to ignore the particular order in any layer of the loop forest
632   // while still comparing the structure.
633   DenseMap<BlockT *, const LoopT *> OtherLoopHeaders;
634   for (LoopT *L : OtherLI)
635     addInnerLoopsToHeadersMap(OtherLoopHeaders, OtherLI, *L);
636
637   // Walk the top level loops and ensure there is a corresponding top-level
638   // loop in the computed version and then recursively compare those loop
639   // nests.
640   for (LoopT *L : *this) {
641     BlockT *Header = L->getHeader();
642     const LoopT *OtherL = OtherLoopHeaders.lookup(Header);
643     assert(OtherL && "Top level loop is missing in computed loop info!");
644     // Now that we've matched this loop, erase its header from the map.
645     OtherLoopHeaders.erase(Header);
646     // And recursively compare these loops.
647     compareLoops(L, OtherL, OtherLoopHeaders);
648   }
649
650   // Any remaining entries in the map are loops which were found when computing
651   // a fresh LoopInfo but not present in the current one.
652   if (!OtherLoopHeaders.empty()) {
653     for (const auto &HeaderAndLoop : OtherLoopHeaders)
654       dbgs() << "Found new loop: " << *HeaderAndLoop.second << "\n";
655     llvm_unreachable("Found new loops when recomputing LoopInfo!");
656   }
657 #endif
658 }
659
660 } // End llvm namespace
661
662 #endif