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