fde56135a962356903f667b0c5196bb8358722a8
[oota-llvm.git] / include / llvm / Support / GenericDomTree.h
1 //===- GenericDomTree.h - Generic dominator trees for graphs ----*- 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 /// \file
10 ///
11 /// This file defines a set of templates that efficiently compute a dominator
12 /// tree over a generic graph. This is used typically in LLVM for fast
13 /// dominance queries on the CFG, but is fully generic w.r.t. the underlying
14 /// graph types.
15 ///
16 //===----------------------------------------------------------------------===//
17
18 #ifndef LLVM_SUPPORT_GENERICDOMTREE_H
19 #define LLVM_SUPPORT_GENERICDOMTREE_H
20
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DepthFirstIterator.h"
23 #include "llvm/ADT/GraphTraits.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29
30 namespace llvm {
31
32 /// \brief Base class that other, more interesting dominator analyses
33 /// inherit from.
34 template <class NodeT> class DominatorBase {
35 protected:
36   std::vector<NodeT *> Roots;
37   bool IsPostDominators;
38   explicit DominatorBase(bool isPostDom)
39       : Roots(), IsPostDominators(isPostDom) {}
40   DominatorBase(DominatorBase &&Arg)
41       : Roots(std::move(Arg.Roots)),
42         IsPostDominators(std::move(Arg.IsPostDominators)) {
43     Arg.Roots.clear();
44   }
45   DominatorBase &operator=(DominatorBase &&RHS) {
46     Roots = std::move(RHS.Roots);
47     IsPostDominators = std::move(RHS.IsPostDominators);
48     RHS.Roots.clear();
49     return *this;
50   }
51
52 public:
53   /// getRoots - Return the root blocks of the current CFG.  This may include
54   /// multiple blocks if we are computing post dominators.  For forward
55   /// dominators, this will always be a single block (the entry node).
56   ///
57   const std::vector<NodeT *> &getRoots() const { return Roots; }
58
59   /// isPostDominator - Returns true if analysis based of postdoms
60   ///
61   bool isPostDominator() const { return IsPostDominators; }
62 };
63
64 template <class NodeT> class DominatorTreeBase;
65 struct PostDominatorTree;
66
67 /// \brief Base class for the actual dominator tree node.
68 template <class NodeT> class DomTreeNodeBase {
69   NodeT *TheBB;
70   DomTreeNodeBase<NodeT> *IDom;
71   std::vector<DomTreeNodeBase<NodeT> *> Children;
72   mutable int DFSNumIn, DFSNumOut;
73
74   template <class N> friend class DominatorTreeBase;
75   friend struct PostDominatorTree;
76
77 public:
78   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
79   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
80       const_iterator;
81
82   iterator begin() { return Children.begin(); }
83   iterator end() { return Children.end(); }
84   const_iterator begin() const { return Children.begin(); }
85   const_iterator end() const { return Children.end(); }
86
87   NodeT *getBlock() const { return TheBB; }
88   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
89   const std::vector<DomTreeNodeBase<NodeT> *> &getChildren() const {
90     return Children;
91   }
92
93   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
94       : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) {}
95
96   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
97     Children.push_back(C);
98     return C;
99   }
100
101   size_t getNumChildren() const { return Children.size(); }
102
103   void clearAllChildren() { Children.clear(); }
104
105   bool compare(const DomTreeNodeBase<NodeT> *Other) const {
106     if (getNumChildren() != Other->getNumChildren())
107       return true;
108
109     SmallPtrSet<const NodeT *, 4> OtherChildren;
110     for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
111       const NodeT *Nd = (*I)->getBlock();
112       OtherChildren.insert(Nd);
113     }
114
115     for (const_iterator I = begin(), E = end(); I != E; ++I) {
116       const NodeT *N = (*I)->getBlock();
117       if (OtherChildren.count(N) == 0)
118         return true;
119     }
120     return false;
121   }
122
123   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
124     assert(IDom && "No immediate dominator?");
125     if (IDom != NewIDom) {
126       typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
127           std::find(IDom->Children.begin(), IDom->Children.end(), this);
128       assert(I != IDom->Children.end() &&
129              "Not in immediate dominator children set!");
130       // I am no longer your child...
131       IDom->Children.erase(I);
132
133       // Switch to new dominator
134       IDom = NewIDom;
135       IDom->Children.push_back(this);
136     }
137   }
138
139   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
140   /// not call them.
141   unsigned getDFSNumIn() const { return DFSNumIn; }
142   unsigned getDFSNumOut() const { return DFSNumOut; }
143
144 private:
145   // Return true if this node is dominated by other. Use this only if DFS info
146   // is valid.
147   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
148     return this->DFSNumIn >= other->DFSNumIn &&
149            this->DFSNumOut <= other->DFSNumOut;
150   }
151 };
152
153 template <class NodeT>
154 raw_ostream &operator<<(raw_ostream &o, const DomTreeNodeBase<NodeT> *Node) {
155   if (Node->getBlock())
156     Node->getBlock()->printAsOperand(o, false);
157   else
158     o << " <<exit node>>";
159
160   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
161
162   return o << "\n";
163 }
164
165 template <class NodeT>
166 void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
167                   unsigned Lev) {
168   o.indent(2 * Lev) << "[" << Lev << "] " << N;
169   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
170                                                        E = N->end();
171        I != E; ++I)
172     PrintDomTree<NodeT>(*I, o, Lev + 1);
173 }
174
175 // The calculate routine is provided in a separate header but referenced here.
176 template <class FuncT, class N>
177 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT,
178                FuncT &F);
179
180 /// \brief Core dominator tree base class.
181 ///
182 /// This class is a generic template over graph nodes. It is instantiated for
183 /// various graphs in the LLVM IR or in the code generator.
184 template <class NodeT> class DominatorTreeBase : public DominatorBase<NodeT> {
185   DominatorTreeBase(const DominatorTreeBase &) LLVM_DELETED_FUNCTION;
186   DominatorTreeBase &operator=(const DominatorTreeBase &) LLVM_DELETED_FUNCTION;
187
188   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
189                                const DomTreeNodeBase<NodeT> *B) const {
190     assert(A != B);
191     assert(isReachableFromEntry(B));
192     assert(isReachableFromEntry(A));
193
194     const DomTreeNodeBase<NodeT> *IDom;
195     while ((IDom = B->getIDom()) != nullptr && IDom != A && IDom != B)
196       B = IDom; // Walk up the tree
197     return IDom != nullptr;
198   }
199
200   /// \brief Wipe this tree's state without releasing any resources.
201   ///
202   /// This is essentially a post-move helper only. It leaves the object in an
203   /// assignable and destroyable state, but otherwise invalid.
204   void wipe() {
205     DomTreeNodes.clear();
206     IDoms.clear();
207     Vertex.clear();
208     Info.clear();
209     RootNode = nullptr;
210   }
211
212 protected:
213   typedef DenseMap<NodeT *, DomTreeNodeBase<NodeT> *> DomTreeNodeMapType;
214   DomTreeNodeMapType DomTreeNodes;
215   DomTreeNodeBase<NodeT> *RootNode;
216
217   mutable bool DFSInfoValid;
218   mutable unsigned int SlowQueries;
219   // Information record used during immediate dominators computation.
220   struct InfoRec {
221     unsigned DFSNum;
222     unsigned Parent;
223     unsigned Semi;
224     NodeT *Label;
225
226     InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(nullptr) {}
227   };
228
229   DenseMap<NodeT *, NodeT *> IDoms;
230
231   // Vertex - Map the DFS number to the NodeT*
232   std::vector<NodeT *> Vertex;
233
234   // Info - Collection of information used during the computation of idoms.
235   DenseMap<NodeT *, InfoRec> Info;
236
237   void reset() {
238     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
239                                                E = DomTreeNodes.end();
240          I != E; ++I)
241       delete I->second;
242     DomTreeNodes.clear();
243     IDoms.clear();
244     this->Roots.clear();
245     Vertex.clear();
246     RootNode = nullptr;
247   }
248
249   // NewBB is split and now it has one successor. Update dominator tree to
250   // reflect this change.
251   template <class N, class GraphT>
252   void Split(DominatorTreeBase<typename GraphT::NodeType> &DT,
253              typename GraphT::NodeType *NewBB) {
254     assert(std::distance(GraphT::child_begin(NewBB),
255                          GraphT::child_end(NewBB)) == 1 &&
256            "NewBB should have a single successor!");
257     typename GraphT::NodeType *NewBBSucc = *GraphT::child_begin(NewBB);
258
259     std::vector<typename GraphT::NodeType *> PredBlocks;
260     typedef GraphTraits<Inverse<N>> InvTraits;
261     for (typename InvTraits::ChildIteratorType
262              PI = InvTraits::child_begin(NewBB),
263              PE = InvTraits::child_end(NewBB);
264          PI != PE; ++PI)
265       PredBlocks.push_back(*PI);
266
267     assert(!PredBlocks.empty() && "No predblocks?");
268
269     bool NewBBDominatesNewBBSucc = true;
270     for (typename InvTraits::ChildIteratorType
271              PI = InvTraits::child_begin(NewBBSucc),
272              E = InvTraits::child_end(NewBBSucc);
273          PI != E; ++PI) {
274       typename InvTraits::NodeType *ND = *PI;
275       if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
276           DT.isReachableFromEntry(ND)) {
277         NewBBDominatesNewBBSucc = false;
278         break;
279       }
280     }
281
282     // Find NewBB's immediate dominator and create new dominator tree node for
283     // NewBB.
284     NodeT *NewBBIDom = nullptr;
285     unsigned i = 0;
286     for (i = 0; i < PredBlocks.size(); ++i)
287       if (DT.isReachableFromEntry(PredBlocks[i])) {
288         NewBBIDom = PredBlocks[i];
289         break;
290       }
291
292     // It's possible that none of the predecessors of NewBB are reachable;
293     // in that case, NewBB itself is unreachable, so nothing needs to be
294     // changed.
295     if (!NewBBIDom)
296       return;
297
298     for (i = i + 1; i < PredBlocks.size(); ++i) {
299       if (DT.isReachableFromEntry(PredBlocks[i]))
300         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
301     }
302
303     // Create the new dominator tree node... and set the idom of NewBB.
304     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
305
306     // If NewBB strictly dominates other blocks, then it is now the immediate
307     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
308     if (NewBBDominatesNewBBSucc) {
309       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
310       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
311     }
312   }
313
314 public:
315   explicit DominatorTreeBase(bool isPostDom)
316       : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
317   ~DominatorTreeBase() { reset(); }
318
319   DominatorTreeBase(DominatorTreeBase &&Arg)
320       : DominatorBase<NodeT>(
321             std::move(static_cast<DominatorBase<NodeT> &>(Arg))),
322         DomTreeNodes(std::move(Arg.DomTreeNodes)),
323         RootNode(std::move(Arg.RootNode)),
324         DFSInfoValid(std::move(Arg.DFSInfoValid)),
325         SlowQueries(std::move(Arg.SlowQueries)), IDoms(std::move(Arg.IDoms)),
326         Vertex(std::move(Arg.Vertex)), Info(std::move(Arg.Info)) {
327     Arg.wipe();
328   }
329   DominatorTreeBase &operator=(DominatorTreeBase &&RHS) {
330     DominatorBase<NodeT>::operator=(
331         std::move(static_cast<DominatorBase<NodeT> &>(RHS)));
332     DomTreeNodes = std::move(RHS.DomTreeNodes);
333     RootNode = std::move(RHS.RootNode);
334     DFSInfoValid = std::move(RHS.DFSInfoValid);
335     SlowQueries = std::move(RHS.SlowQueries);
336     IDoms = std::move(RHS.IDoms);
337     Vertex = std::move(RHS.Vertex);
338     Info = std::move(RHS.Info);
339     RHS.wipe();
340     return *this;
341   }
342
343   /// compare - Return false if the other dominator tree base matches this
344   /// dominator tree base. Otherwise return true.
345   bool compare(const DominatorTreeBase &Other) const {
346
347     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
348     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
349       return true;
350
351     for (typename DomTreeNodeMapType::const_iterator
352              I = this->DomTreeNodes.begin(),
353              E = this->DomTreeNodes.end();
354          I != E; ++I) {
355       NodeT *BB = I->first;
356       typename DomTreeNodeMapType::const_iterator OI =
357           OtherDomTreeNodes.find(BB);
358       if (OI == OtherDomTreeNodes.end())
359         return true;
360
361       DomTreeNodeBase<NodeT> *MyNd = I->second;
362       DomTreeNodeBase<NodeT> *OtherNd = OI->second;
363
364       if (MyNd->compare(OtherNd))
365         return true;
366     }
367
368     return false;
369   }
370
371   void releaseMemory() { reset(); }
372
373   /// getNode - return the (Post)DominatorTree node for the specified basic
374   /// block.  This is the same as using operator[] on this class.
375   ///
376   DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
377     return DomTreeNodes.lookup(BB);
378   }
379
380   DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const { return getNode(BB); }
381
382   /// getRootNode - This returns the entry node for the CFG of the function.  If
383   /// this tree represents the post-dominance relations for a function, however,
384   /// this root may be a node with the block == NULL.  This is the case when
385   /// there are multiple exit nodes from a particular function.  Consumers of
386   /// post-dominance information must be capable of dealing with this
387   /// possibility.
388   ///
389   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
390   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
391
392   /// Get all nodes dominated by R, including R itself.
393   void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
394     Result.clear();
395     const DomTreeNodeBase<NodeT> *RN = getNode(R);
396     if (!RN)
397       return; // If R is unreachable, it will not be present in the DOM tree.
398     SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
399     WL.push_back(RN);
400
401     while (!WL.empty()) {
402       const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
403       Result.push_back(N->getBlock());
404       WL.append(N->begin(), N->end());
405     }
406   }
407
408   /// properlyDominates - Returns true iff A dominates B and A != B.
409   /// Note that this is not a constant time operation!
410   ///
411   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
412                          const DomTreeNodeBase<NodeT> *B) const {
413     if (!A || !B)
414       return false;
415     if (A == B)
416       return false;
417     return dominates(A, B);
418   }
419
420   bool properlyDominates(const NodeT *A, const NodeT *B) const;
421
422   /// isReachableFromEntry - Return true if A is dominated by the entry
423   /// block of the function containing it.
424   bool isReachableFromEntry(const NodeT *A) const {
425     assert(!this->isPostDominator() &&
426            "This is not implemented for post dominators");
427     return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
428   }
429
430   bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
431
432   /// dominates - Returns true iff A dominates B.  Note that this is not a
433   /// constant time operation!
434   ///
435   bool dominates(const DomTreeNodeBase<NodeT> *A,
436                  const DomTreeNodeBase<NodeT> *B) const {
437     // A node trivially dominates itself.
438     if (B == A)
439       return true;
440
441     // An unreachable node is dominated by anything.
442     if (!isReachableFromEntry(B))
443       return true;
444
445     // And dominates nothing.
446     if (!isReachableFromEntry(A))
447       return false;
448
449     // Compare the result of the tree walk and the dfs numbers, if expensive
450     // checks are enabled.
451 #ifdef XDEBUG
452     assert((!DFSInfoValid ||
453             (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
454            "Tree walk disagrees with dfs numbers!");
455 #endif
456
457     if (DFSInfoValid)
458       return B->DominatedBy(A);
459
460     // If we end up with too many slow queries, just update the
461     // DFS numbers on the theory that we are going to keep querying.
462     SlowQueries++;
463     if (SlowQueries > 32) {
464       updateDFSNumbers();
465       return B->DominatedBy(A);
466     }
467
468     return dominatedBySlowTreeWalk(A, B);
469   }
470
471   bool dominates(const NodeT *A, const NodeT *B) const;
472
473   NodeT *getRoot() const {
474     assert(this->Roots.size() == 1 && "Should always have entry node!");
475     return this->Roots[0];
476   }
477
478   /// findNearestCommonDominator - Find nearest common dominator basic block
479   /// for basic block A and B. If there is no such block then return NULL.
480   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
481     assert(A->getParent() == B->getParent() &&
482            "Two blocks are not in same function");
483
484     // If either A or B is a entry block then it is nearest common dominator
485     // (for forward-dominators).
486     if (!this->isPostDominator()) {
487       NodeT &Entry = A->getParent()->front();
488       if (A == &Entry || B == &Entry)
489         return &Entry;
490     }
491
492     // If B dominates A then B is nearest common dominator.
493     if (dominates(B, A))
494       return B;
495
496     // If A dominates B then A is nearest common dominator.
497     if (dominates(A, B))
498       return A;
499
500     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
501     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
502
503     // If we have DFS info, then we can avoid all allocations by just querying
504     // it from each IDom. Note that because we call 'dominates' twice above, we
505     // expect to call through this code at most 16 times in a row without
506     // building valid DFS information. This is important as below is a *very*
507     // slow tree walk.
508     if (DFSInfoValid) {
509       DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
510       while (IDomA) {
511         if (NodeB->DominatedBy(IDomA))
512           return IDomA->getBlock();
513         IDomA = IDomA->getIDom();
514       }
515       return nullptr;
516     }
517
518     // Collect NodeA dominators set.
519     SmallPtrSet<DomTreeNodeBase<NodeT> *, 16> NodeADoms;
520     NodeADoms.insert(NodeA);
521     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
522     while (IDomA) {
523       NodeADoms.insert(IDomA);
524       IDomA = IDomA->getIDom();
525     }
526
527     // Walk NodeB immediate dominators chain and find common dominator node.
528     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
529     while (IDomB) {
530       if (NodeADoms.count(IDomB) != 0)
531         return IDomB->getBlock();
532
533       IDomB = IDomB->getIDom();
534     }
535
536     return nullptr;
537   }
538
539   const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
540     // Cast away the const qualifiers here. This is ok since
541     // const is re-introduced on the return type.
542     return findNearestCommonDominator(const_cast<NodeT *>(A),
543                                       const_cast<NodeT *>(B));
544   }
545
546   //===--------------------------------------------------------------------===//
547   // API to update (Post)DominatorTree information based on modifications to
548   // the CFG...
549
550   /// addNewBlock - Add a new node to the dominator tree information.  This
551   /// creates a new node as a child of DomBB dominator node,linking it into
552   /// the children list of the immediate dominator.
553   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
554     assert(getNode(BB) == nullptr && "Block already in dominator tree!");
555     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
556     assert(IDomNode && "Not immediate dominator specified for block!");
557     DFSInfoValid = false;
558     return DomTreeNodes[BB] =
559                IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
560   }
561
562   /// changeImmediateDominator - This method is used to update the dominator
563   /// tree information when a node's immediate dominator changes.
564   ///
565   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
566                                 DomTreeNodeBase<NodeT> *NewIDom) {
567     assert(N && NewIDom && "Cannot change null node pointers!");
568     DFSInfoValid = false;
569     N->setIDom(NewIDom);
570   }
571
572   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
573     changeImmediateDominator(getNode(BB), getNode(NewBB));
574   }
575
576   /// eraseNode - Removes a node from the dominator tree. Block must not
577   /// dominate any other blocks. Removes node from its immediate dominator's
578   /// children list. Deletes dominator node associated with basic block BB.
579   void eraseNode(NodeT *BB) {
580     DomTreeNodeBase<NodeT> *Node = getNode(BB);
581     assert(Node && "Removing node that isn't in dominator tree.");
582     assert(Node->getChildren().empty() && "Node is not a leaf node.");
583
584     // Remove node from immediate dominator's children list.
585     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
586     if (IDom) {
587       typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
588           std::find(IDom->Children.begin(), IDom->Children.end(), Node);
589       assert(I != IDom->Children.end() &&
590              "Not in immediate dominator children set!");
591       // I am no longer your child...
592       IDom->Children.erase(I);
593     }
594
595     DomTreeNodes.erase(BB);
596     delete Node;
597   }
598
599   /// removeNode - Removes a node from the dominator tree.  Block must not
600   /// dominate any other blocks.  Invalidates any node pointing to removed
601   /// block.
602   void removeNode(NodeT *BB) {
603     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
604     DomTreeNodes.erase(BB);
605   }
606
607   /// splitBlock - BB is split and now it has one successor. Update dominator
608   /// tree to reflect this change.
609   void splitBlock(NodeT *NewBB) {
610     if (this->IsPostDominators)
611       this->Split<Inverse<NodeT *>, GraphTraits<Inverse<NodeT *>>>(*this,
612                                                                    NewBB);
613     else
614       this->Split<NodeT *, GraphTraits<NodeT *>>(*this, NewBB);
615   }
616
617   /// print - Convert to human readable form
618   ///
619   void print(raw_ostream &o) const {
620     o << "=============================--------------------------------\n";
621     if (this->isPostDominator())
622       o << "Inorder PostDominator Tree: ";
623     else
624       o << "Inorder Dominator Tree: ";
625     if (!this->DFSInfoValid)
626       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
627     o << "\n";
628
629     // The postdom tree can have a null root if there are no returns.
630     if (getRootNode())
631       PrintDomTree<NodeT>(getRootNode(), o, 1);
632   }
633
634 protected:
635   template <class GraphT>
636   friend typename GraphT::NodeType *
637   Eval(DominatorTreeBase<typename GraphT::NodeType> &DT,
638        typename GraphT::NodeType *V, unsigned LastLinked);
639
640   template <class GraphT>
641   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType> &DT,
642                           typename GraphT::NodeType *V, unsigned N);
643
644   template <class FuncT, class N>
645   friend void
646   Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT, FuncT &F);
647
648   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
649   /// dominator tree in dfs order.
650   void updateDFSNumbers() const {
651     unsigned DFSNum = 0;
652
653     SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
654                           typename DomTreeNodeBase<NodeT>::const_iterator>,
655                 32> WorkStack;
656
657     const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
658
659     if (!ThisRoot)
660       return;
661
662     // Even in the case of multiple exits that form the post dominator root
663     // nodes, do not iterate over all exits, but start from the virtual root
664     // node. Otherwise bbs, that are not post dominated by any exit but by the
665     // virtual root node, will never be assigned a DFS number.
666     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
667     ThisRoot->DFSNumIn = DFSNum++;
668
669     while (!WorkStack.empty()) {
670       const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
671       typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
672           WorkStack.back().second;
673
674       // If we visited all of the children of this node, "recurse" back up the
675       // stack setting the DFOutNum.
676       if (ChildIt == Node->end()) {
677         Node->DFSNumOut = DFSNum++;
678         WorkStack.pop_back();
679       } else {
680         // Otherwise, recursively visit this child.
681         const DomTreeNodeBase<NodeT> *Child = *ChildIt;
682         ++WorkStack.back().second;
683
684         WorkStack.push_back(std::make_pair(Child, Child->begin()));
685         Child->DFSNumIn = DFSNum++;
686       }
687     }
688
689     SlowQueries = 0;
690     DFSInfoValid = true;
691   }
692
693   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
694     if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
695       return Node;
696
697     // Haven't calculated this node yet?  Get or calculate the node for the
698     // immediate dominator.
699     NodeT *IDom = getIDom(BB);
700
701     assert(IDom || this->DomTreeNodes[nullptr]);
702     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
703
704     // Add a new tree node for this NodeT, and link it as a child of
705     // IDomNode
706     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
707     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
708   }
709
710   NodeT *getIDom(NodeT *BB) const { return IDoms.lookup(BB); }
711
712   void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
713
714 public:
715   /// recalculate - compute a dominator tree for the given function
716   template <class FT> void recalculate(FT &F) {
717     typedef GraphTraits<FT *> TraitsTy;
718     reset();
719     this->Vertex.push_back(nullptr);
720
721     if (!this->IsPostDominators) {
722       // Initialize root
723       NodeT *entry = TraitsTy::getEntryNode(&F);
724       this->Roots.push_back(entry);
725       this->IDoms[entry] = nullptr;
726       this->DomTreeNodes[entry] = nullptr;
727
728       Calculate<FT, NodeT *>(*this, F);
729     } else {
730       // Initialize the roots list
731       for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
732                                              E = TraitsTy::nodes_end(&F);
733            I != E; ++I) {
734         if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
735           addRoot(I);
736
737         // Prepopulate maps so that we don't get iterator invalidation issues
738         // later.
739         this->IDoms[I] = nullptr;
740         this->DomTreeNodes[I] = nullptr;
741       }
742
743       Calculate<FT, Inverse<NodeT *>>(*this, F);
744     }
745   }
746 };
747
748 // These two functions are declared out of line as a workaround for building
749 // with old (< r147295) versions of clang because of pr11642.
750 template <class NodeT>
751 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) const {
752   if (A == B)
753     return true;
754
755   // Cast away the const qualifiers here. This is ok since
756   // this function doesn't actually return the values returned
757   // from getNode.
758   return dominates(getNode(const_cast<NodeT *>(A)),
759                    getNode(const_cast<NodeT *>(B)));
760 }
761 template <class NodeT>
762 bool DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A,
763                                                  const NodeT *B) const {
764   if (A == B)
765     return false;
766
767   // Cast away the const qualifiers here. This is ok since
768   // this function doesn't actually return the values returned
769   // from getNode.
770   return dominates(getNode(const_cast<NodeT *>(A)),
771                    getNode(const_cast<NodeT *>(B)));
772 }
773
774 }
775
776 #endif