LLVM API Documentation

GenericDomTree.h
Go to the documentation of this file.
00001 //===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 ///
00011 /// This file defines a set of templates that efficiently compute a dominator
00012 /// tree over a generic graph. This is used typically in LLVM for fast
00013 /// dominance queries on the CFG, but is fully generic w.r.t. the underlying
00014 /// graph types.
00015 ///
00016 //===----------------------------------------------------------------------===//
00017 
00018 #ifndef LLVM_SUPPORT_GENERICDOMTREE_H
00019 #define LLVM_SUPPORT_GENERICDOMTREE_H
00020 
00021 #include "llvm/ADT/DenseMap.h"
00022 #include "llvm/ADT/DepthFirstIterator.h"
00023 #include "llvm/ADT/GraphTraits.h"
00024 #include "llvm/ADT/SmallPtrSet.h"
00025 #include "llvm/ADT/SmallVector.h"
00026 #include "llvm/Support/Compiler.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include <algorithm>
00029 
00030 namespace llvm {
00031 
00032 //===----------------------------------------------------------------------===//
00033 /// DominatorBase - Base class that other, more interesting dominator analyses
00034 /// inherit from.
00035 ///
00036 template <class NodeT>
00037 class DominatorBase {
00038 protected:
00039   std::vector<NodeT*> Roots;
00040   const bool IsPostDominators;
00041   inline explicit DominatorBase(bool isPostDom) :
00042     Roots(), IsPostDominators(isPostDom) {}
00043 public:
00044 
00045   /// getRoots - Return the root blocks of the current CFG.  This may include
00046   /// multiple blocks if we are computing post dominators.  For forward
00047   /// dominators, this will always be a single block (the entry node).
00048   ///
00049   inline const std::vector<NodeT*> &getRoots() const { return Roots; }
00050 
00051   /// isPostDominator - Returns true if analysis based of postdoms
00052   ///
00053   bool isPostDominator() const { return IsPostDominators; }
00054 };
00055 
00056 
00057 //===----------------------------------------------------------------------===//
00058 // DomTreeNodeBase - Dominator Tree Node
00059 template<class NodeT> class DominatorTreeBase;
00060 struct PostDominatorTree;
00061 
00062 template <class NodeT>
00063 class DomTreeNodeBase {
00064   NodeT *TheBB;
00065   DomTreeNodeBase<NodeT> *IDom;
00066   std::vector<DomTreeNodeBase<NodeT> *> Children;
00067   mutable int DFSNumIn, DFSNumOut;
00068 
00069   template<class N> friend class DominatorTreeBase;
00070   friend struct PostDominatorTree;
00071 public:
00072   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
00073   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
00074                    const_iterator;
00075 
00076   iterator begin()             { return Children.begin(); }
00077   iterator end()               { return Children.end(); }
00078   const_iterator begin() const { return Children.begin(); }
00079   const_iterator end()   const { return Children.end(); }
00080 
00081   NodeT *getBlock() const { return TheBB; }
00082   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
00083   const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
00084     return Children;
00085   }
00086 
00087   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
00088     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
00089 
00090   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
00091     Children.push_back(C);
00092     return C;
00093   }
00094 
00095   size_t getNumChildren() const {
00096     return Children.size();
00097   }
00098 
00099   void clearAllChildren() {
00100     Children.clear();
00101   }
00102 
00103   bool compare(const DomTreeNodeBase<NodeT> *Other) const {
00104     if (getNumChildren() != Other->getNumChildren())
00105       return true;
00106 
00107     SmallPtrSet<const NodeT *, 4> OtherChildren;
00108     for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
00109       const NodeT *Nd = (*I)->getBlock();
00110       OtherChildren.insert(Nd);
00111     }
00112 
00113     for (const_iterator I = begin(), E = end(); I != E; ++I) {
00114       const NodeT *N = (*I)->getBlock();
00115       if (OtherChildren.count(N) == 0)
00116         return true;
00117     }
00118     return false;
00119   }
00120 
00121   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
00122     assert(IDom && "No immediate dominator?");
00123     if (IDom != NewIDom) {
00124       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
00125                   std::find(IDom->Children.begin(), IDom->Children.end(), this);
00126       assert(I != IDom->Children.end() &&
00127              "Not in immediate dominator children set!");
00128       // I am no longer your child...
00129       IDom->Children.erase(I);
00130 
00131       // Switch to new dominator
00132       IDom = NewIDom;
00133       IDom->Children.push_back(this);
00134     }
00135   }
00136 
00137   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
00138   /// not call them.
00139   unsigned getDFSNumIn() const { return DFSNumIn; }
00140   unsigned getDFSNumOut() const { return DFSNumOut; }
00141 private:
00142   // Return true if this node is dominated by other. Use this only if DFS info
00143   // is valid.
00144   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
00145     return this->DFSNumIn >= other->DFSNumIn &&
00146       this->DFSNumOut <= other->DFSNumOut;
00147   }
00148 };
00149 
00150 template<class NodeT>
00151 inline raw_ostream &operator<<(raw_ostream &o,
00152                                const DomTreeNodeBase<NodeT> *Node) {
00153   if (Node->getBlock())
00154     Node->getBlock()->printAsOperand(o, false);
00155   else
00156     o << " <<exit node>>";
00157 
00158   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
00159 
00160   return o << "\n";
00161 }
00162 
00163 template<class NodeT>
00164 inline void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
00165                          unsigned Lev) {
00166   o.indent(2*Lev) << "[" << Lev << "] " << N;
00167   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
00168        E = N->end(); I != E; ++I)
00169     PrintDomTree<NodeT>(*I, o, Lev+1);
00170 }
00171 
00172 //===----------------------------------------------------------------------===//
00173 /// DominatorTree - Calculate the immediate dominator tree for a function.
00174 ///
00175 
00176 template<class FuncT, class N>
00177 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
00178                FuncT& F);
00179 
00180 template<class NodeT>
00181 class DominatorTreeBase : public DominatorBase<NodeT> {
00182   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
00183                                const DomTreeNodeBase<NodeT> *B) const {
00184     assert(A != B);
00185     assert(isReachableFromEntry(B));
00186     assert(isReachableFromEntry(A));
00187 
00188     const DomTreeNodeBase<NodeT> *IDom;
00189     while ((IDom = B->getIDom()) != nullptr && IDom != A && IDom != B)
00190       B = IDom;   // Walk up the tree
00191     return IDom != nullptr;
00192   }
00193 
00194 protected:
00195   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
00196   DomTreeNodeMapType DomTreeNodes;
00197   DomTreeNodeBase<NodeT> *RootNode;
00198 
00199   mutable bool DFSInfoValid;
00200   mutable unsigned int SlowQueries;
00201   // Information record used during immediate dominators computation.
00202   struct InfoRec {
00203     unsigned DFSNum;
00204     unsigned Parent;
00205     unsigned Semi;
00206     NodeT *Label;
00207 
00208     InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(nullptr) {}
00209   };
00210 
00211   DenseMap<NodeT*, NodeT*> IDoms;
00212 
00213   // Vertex - Map the DFS number to the NodeT*
00214   std::vector<NodeT*> Vertex;
00215 
00216   // Info - Collection of information used during the computation of idoms.
00217   DenseMap<NodeT*, InfoRec> Info;
00218 
00219   void reset() {
00220     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
00221            E = DomTreeNodes.end(); I != E; ++I)
00222       delete I->second;
00223     DomTreeNodes.clear();
00224     IDoms.clear();
00225     this->Roots.clear();
00226     Vertex.clear();
00227     RootNode = nullptr;
00228   }
00229 
00230   // NewBB is split and now it has one successor. Update dominator tree to
00231   // reflect this change.
00232   template<class N, class GraphT>
00233   void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
00234              typename GraphT::NodeType* NewBB) {
00235     assert(std::distance(GraphT::child_begin(NewBB),
00236                          GraphT::child_end(NewBB)) == 1 &&
00237            "NewBB should have a single successor!");
00238     typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
00239 
00240     std::vector<typename GraphT::NodeType*> PredBlocks;
00241     typedef GraphTraits<Inverse<N> > InvTraits;
00242     for (typename InvTraits::ChildIteratorType PI =
00243          InvTraits::child_begin(NewBB),
00244          PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
00245       PredBlocks.push_back(*PI);
00246 
00247     assert(!PredBlocks.empty() && "No predblocks?");
00248 
00249     bool NewBBDominatesNewBBSucc = true;
00250     for (typename InvTraits::ChildIteratorType PI =
00251          InvTraits::child_begin(NewBBSucc),
00252          E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
00253       typename InvTraits::NodeType *ND = *PI;
00254       if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
00255           DT.isReachableFromEntry(ND)) {
00256         NewBBDominatesNewBBSucc = false;
00257         break;
00258       }
00259     }
00260 
00261     // Find NewBB's immediate dominator and create new dominator tree node for
00262     // NewBB.
00263     NodeT *NewBBIDom = nullptr;
00264     unsigned i = 0;
00265     for (i = 0; i < PredBlocks.size(); ++i)
00266       if (DT.isReachableFromEntry(PredBlocks[i])) {
00267         NewBBIDom = PredBlocks[i];
00268         break;
00269       }
00270 
00271     // It's possible that none of the predecessors of NewBB are reachable;
00272     // in that case, NewBB itself is unreachable, so nothing needs to be
00273     // changed.
00274     if (!NewBBIDom)
00275       return;
00276 
00277     for (i = i + 1; i < PredBlocks.size(); ++i) {
00278       if (DT.isReachableFromEntry(PredBlocks[i]))
00279         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
00280     }
00281 
00282     // Create the new dominator tree node... and set the idom of NewBB.
00283     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
00284 
00285     // If NewBB strictly dominates other blocks, then it is now the immediate
00286     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
00287     if (NewBBDominatesNewBBSucc) {
00288       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
00289       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
00290     }
00291   }
00292 
00293 public:
00294   explicit DominatorTreeBase(bool isPostDom)
00295     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
00296   virtual ~DominatorTreeBase() { reset(); }
00297 
00298   /// compare - Return false if the other dominator tree base matches this
00299   /// dominator tree base. Otherwise return true.
00300   bool compare(const DominatorTreeBase &Other) const {
00301 
00302     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
00303     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
00304       return true;
00305 
00306     for (typename DomTreeNodeMapType::const_iterator
00307            I = this->DomTreeNodes.begin(),
00308            E = this->DomTreeNodes.end(); I != E; ++I) {
00309       NodeT *BB = I->first;
00310       typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
00311       if (OI == OtherDomTreeNodes.end())
00312         return true;
00313 
00314       DomTreeNodeBase<NodeT>* MyNd = I->second;
00315       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
00316 
00317       if (MyNd->compare(OtherNd))
00318         return true;
00319     }
00320 
00321     return false;
00322   }
00323 
00324   virtual void releaseMemory() { reset(); }
00325 
00326   /// getNode - return the (Post)DominatorTree node for the specified basic
00327   /// block.  This is the same as using operator[] on this class.
00328   ///
00329   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
00330     return DomTreeNodes.lookup(BB);
00331   }
00332 
00333   inline DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const {
00334     return getNode(BB);
00335   }
00336 
00337   /// getRootNode - This returns the entry node for the CFG of the function.  If
00338   /// this tree represents the post-dominance relations for a function, however,
00339   /// this root may be a node with the block == NULL.  This is the case when
00340   /// there are multiple exit nodes from a particular function.  Consumers of
00341   /// post-dominance information must be capable of dealing with this
00342   /// possibility.
00343   ///
00344   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
00345   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
00346 
00347   /// Get all nodes dominated by R, including R itself.
00348   void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
00349     Result.clear();
00350     const DomTreeNodeBase<NodeT> *RN = getNode(R);
00351     if (!RN)
00352       return; // If R is unreachable, it will not be present in the DOM tree.
00353     SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
00354     WL.push_back(RN);
00355 
00356     while (!WL.empty()) {
00357       const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
00358       Result.push_back(N->getBlock());
00359       WL.append(N->begin(), N->end());
00360     }
00361   }
00362 
00363   /// properlyDominates - Returns true iff A dominates B and A != B.
00364   /// Note that this is not a constant time operation!
00365   ///
00366   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
00367                          const DomTreeNodeBase<NodeT> *B) const {
00368     if (!A || !B)
00369       return false;
00370     if (A == B)
00371       return false;
00372     return dominates(A, B);
00373   }
00374 
00375   bool properlyDominates(const NodeT *A, const NodeT *B) const;
00376 
00377   /// isReachableFromEntry - Return true if A is dominated by the entry
00378   /// block of the function containing it.
00379   bool isReachableFromEntry(const NodeT* A) const {
00380     assert(!this->isPostDominator() &&
00381            "This is not implemented for post dominators");
00382     return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
00383   }
00384 
00385   inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
00386     return A;
00387   }
00388 
00389   /// dominates - Returns true iff A dominates B.  Note that this is not a
00390   /// constant time operation!
00391   ///
00392   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
00393                         const DomTreeNodeBase<NodeT> *B) const {
00394     // A node trivially dominates itself.
00395     if (B == A)
00396       return true;
00397 
00398     // An unreachable node is dominated by anything.
00399     if (!isReachableFromEntry(B))
00400       return true;
00401 
00402     // And dominates nothing.
00403     if (!isReachableFromEntry(A))
00404       return false;
00405 
00406     // Compare the result of the tree walk and the dfs numbers, if expensive
00407     // checks are enabled.
00408 #ifdef XDEBUG
00409     assert((!DFSInfoValid ||
00410             (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
00411            "Tree walk disagrees with dfs numbers!");
00412 #endif
00413 
00414     if (DFSInfoValid)
00415       return B->DominatedBy(A);
00416 
00417     // If we end up with too many slow queries, just update the
00418     // DFS numbers on the theory that we are going to keep querying.
00419     SlowQueries++;
00420     if (SlowQueries > 32) {
00421       updateDFSNumbers();
00422       return B->DominatedBy(A);
00423     }
00424 
00425     return dominatedBySlowTreeWalk(A, B);
00426   }
00427 
00428   bool dominates(const NodeT *A, const NodeT *B) const;
00429 
00430   NodeT *getRoot() const {
00431     assert(this->Roots.size() == 1 && "Should always have entry node!");
00432     return this->Roots[0];
00433   }
00434 
00435   /// findNearestCommonDominator - Find nearest common dominator basic block
00436   /// for basic block A and B. If there is no such block then return NULL.
00437   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
00438     assert(A->getParent() == B->getParent() &&
00439            "Two blocks are not in same function");
00440 
00441     // If either A or B is a entry block then it is nearest common dominator
00442     // (for forward-dominators).
00443     if (!this->isPostDominator()) {
00444       NodeT &Entry = A->getParent()->front();
00445       if (A == &Entry || B == &Entry)
00446         return &Entry;
00447     }
00448 
00449     // If B dominates A then B is nearest common dominator.
00450     if (dominates(B, A))
00451       return B;
00452 
00453     // If A dominates B then A is nearest common dominator.
00454     if (dominates(A, B))
00455       return A;
00456 
00457     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
00458     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
00459 
00460     // If we have DFS info, then we can avoid all allocations by just querying
00461     // it from each IDom. Note that because we call 'dominates' twice above, we
00462     // expect to call through this code at most 16 times in a row without
00463     // building valid DFS information. This is important as below is a *very*
00464     // slow tree walk.
00465     if (DFSInfoValid) {
00466       DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
00467       while (IDomA) {
00468         if (NodeB->DominatedBy(IDomA))
00469           return IDomA->getBlock();
00470         IDomA = IDomA->getIDom();
00471       }
00472       return nullptr;
00473     }
00474 
00475     // Collect NodeA dominators set.
00476     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
00477     NodeADoms.insert(NodeA);
00478     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
00479     while (IDomA) {
00480       NodeADoms.insert(IDomA);
00481       IDomA = IDomA->getIDom();
00482     }
00483 
00484     // Walk NodeB immediate dominators chain and find common dominator node.
00485     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
00486     while (IDomB) {
00487       if (NodeADoms.count(IDomB) != 0)
00488         return IDomB->getBlock();
00489 
00490       IDomB = IDomB->getIDom();
00491     }
00492 
00493     return nullptr;
00494   }
00495 
00496   const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
00497     // Cast away the const qualifiers here. This is ok since
00498     // const is re-introduced on the return type.
00499     return findNearestCommonDominator(const_cast<NodeT *>(A),
00500                                       const_cast<NodeT *>(B));
00501   }
00502 
00503   //===--------------------------------------------------------------------===//
00504   // API to update (Post)DominatorTree information based on modifications to
00505   // the CFG...
00506 
00507   /// addNewBlock - Add a new node to the dominator tree information.  This
00508   /// creates a new node as a child of DomBB dominator node,linking it into
00509   /// the children list of the immediate dominator.
00510   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
00511     assert(getNode(BB) == nullptr && "Block already in dominator tree!");
00512     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
00513     assert(IDomNode && "Not immediate dominator specified for block!");
00514     DFSInfoValid = false;
00515     return DomTreeNodes[BB] =
00516       IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
00517   }
00518 
00519   /// changeImmediateDominator - This method is used to update the dominator
00520   /// tree information when a node's immediate dominator changes.
00521   ///
00522   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
00523                                 DomTreeNodeBase<NodeT> *NewIDom) {
00524     assert(N && NewIDom && "Cannot change null node pointers!");
00525     DFSInfoValid = false;
00526     N->setIDom(NewIDom);
00527   }
00528 
00529   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
00530     changeImmediateDominator(getNode(BB), getNode(NewBB));
00531   }
00532 
00533   /// eraseNode - Removes a node from the dominator tree. Block must not
00534   /// dominate any other blocks. Removes node from its immediate dominator's
00535   /// children list. Deletes dominator node associated with basic block BB.
00536   void eraseNode(NodeT *BB) {
00537     DomTreeNodeBase<NodeT> *Node = getNode(BB);
00538     assert(Node && "Removing node that isn't in dominator tree.");
00539     assert(Node->getChildren().empty() && "Node is not a leaf node.");
00540 
00541       // Remove node from immediate dominator's children list.
00542     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
00543     if (IDom) {
00544       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
00545         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
00546       assert(I != IDom->Children.end() &&
00547              "Not in immediate dominator children set!");
00548       // I am no longer your child...
00549       IDom->Children.erase(I);
00550     }
00551 
00552     DomTreeNodes.erase(BB);
00553     delete Node;
00554   }
00555 
00556   /// removeNode - Removes a node from the dominator tree.  Block must not
00557   /// dominate any other blocks.  Invalidates any node pointing to removed
00558   /// block.
00559   void removeNode(NodeT *BB) {
00560     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
00561     DomTreeNodes.erase(BB);
00562   }
00563 
00564   /// splitBlock - BB is split and now it has one successor. Update dominator
00565   /// tree to reflect this change.
00566   void splitBlock(NodeT* NewBB) {
00567     if (this->IsPostDominators)
00568       this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
00569     else
00570       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
00571   }
00572 
00573   /// print - Convert to human readable form
00574   ///
00575   void print(raw_ostream &o) const {
00576     o << "=============================--------------------------------\n";
00577     if (this->isPostDominator())
00578       o << "Inorder PostDominator Tree: ";
00579     else
00580       o << "Inorder Dominator Tree: ";
00581     if (!this->DFSInfoValid)
00582       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
00583     o << "\n";
00584 
00585     // The postdom tree can have a null root if there are no returns.
00586     if (getRootNode())
00587       PrintDomTree<NodeT>(getRootNode(), o, 1);
00588   }
00589 
00590 protected:
00591   template<class GraphT>
00592   friend typename GraphT::NodeType* Eval(
00593                                DominatorTreeBase<typename GraphT::NodeType>& DT,
00594                                          typename GraphT::NodeType* V,
00595                                          unsigned LastLinked);
00596 
00597   template<class GraphT>
00598   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
00599                           typename GraphT::NodeType* V,
00600                           unsigned N);
00601 
00602   template<class FuncT, class N>
00603   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
00604                         FuncT& F);
00605 
00606   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
00607   /// dominator tree in dfs order.
00608   void updateDFSNumbers() const {
00609     unsigned DFSNum = 0;
00610 
00611     SmallVector<std::pair<const DomTreeNodeBase<NodeT>*,
00612                 typename DomTreeNodeBase<NodeT>::const_iterator>, 32> WorkStack;
00613 
00614     const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
00615 
00616     if (!ThisRoot)
00617       return;
00618 
00619     // Even in the case of multiple exits that form the post dominator root
00620     // nodes, do not iterate over all exits, but start from the virtual root
00621     // node. Otherwise bbs, that are not post dominated by any exit but by the
00622     // virtual root node, will never be assigned a DFS number.
00623     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
00624     ThisRoot->DFSNumIn = DFSNum++;
00625 
00626     while (!WorkStack.empty()) {
00627       const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
00628       typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
00629         WorkStack.back().second;
00630 
00631       // If we visited all of the children of this node, "recurse" back up the
00632       // stack setting the DFOutNum.
00633       if (ChildIt == Node->end()) {
00634         Node->DFSNumOut = DFSNum++;
00635         WorkStack.pop_back();
00636       } else {
00637         // Otherwise, recursively visit this child.
00638         const DomTreeNodeBase<NodeT> *Child = *ChildIt;
00639         ++WorkStack.back().second;
00640 
00641         WorkStack.push_back(std::make_pair(Child, Child->begin()));
00642         Child->DFSNumIn = DFSNum++;
00643       }
00644     }
00645 
00646     SlowQueries = 0;
00647     DFSInfoValid = true;
00648   }
00649 
00650   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
00651     if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
00652       return Node;
00653 
00654     // Haven't calculated this node yet?  Get or calculate the node for the
00655     // immediate dominator.
00656     NodeT *IDom = getIDom(BB);
00657 
00658     assert(IDom || this->DomTreeNodes[nullptr]);
00659     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
00660 
00661     // Add a new tree node for this NodeT, and link it as a child of
00662     // IDomNode
00663     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
00664     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
00665   }
00666 
00667   inline NodeT *getIDom(NodeT *BB) const {
00668     return IDoms.lookup(BB);
00669   }
00670 
00671   inline void addRoot(NodeT* BB) {
00672     this->Roots.push_back(BB);
00673   }
00674 
00675 public:
00676   /// recalculate - compute a dominator tree for the given function
00677   template<class FT>
00678   void recalculate(FT& F) {
00679     typedef GraphTraits<FT*> TraitsTy;
00680     reset();
00681     this->Vertex.push_back(nullptr);
00682 
00683     if (!this->IsPostDominators) {
00684       // Initialize root
00685       NodeT *entry = TraitsTy::getEntryNode(&F);
00686       this->Roots.push_back(entry);
00687       this->IDoms[entry] = nullptr;
00688       this->DomTreeNodes[entry] = nullptr;
00689 
00690       Calculate<FT, NodeT*>(*this, F);
00691     } else {
00692       // Initialize the roots list
00693       for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
00694                                         E = TraitsTy::nodes_end(&F); I != E; ++I) {
00695         if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
00696           addRoot(I);
00697 
00698         // Prepopulate maps so that we don't get iterator invalidation issues later.
00699         this->IDoms[I] = nullptr;
00700         this->DomTreeNodes[I] = nullptr;
00701       }
00702 
00703       Calculate<FT, Inverse<NodeT*> >(*this, F);
00704     }
00705   }
00706 };
00707 
00708 // These two functions are declared out of line as a workaround for building
00709 // with old (< r147295) versions of clang because of pr11642.
00710 template<class NodeT>
00711 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) const {
00712   if (A == B)
00713     return true;
00714 
00715   // Cast away the const qualifiers here. This is ok since
00716   // this function doesn't actually return the values returned
00717   // from getNode.
00718   return dominates(getNode(const_cast<NodeT *>(A)),
00719                    getNode(const_cast<NodeT *>(B)));
00720 }
00721 template<class NodeT>
00722 bool
00723 DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B) const {
00724   if (A == B)
00725     return false;
00726 
00727   // Cast away the const qualifiers here. This is ok since
00728   // this function doesn't actually return the values returned
00729   // from getNode.
00730   return dominates(getNode(const_cast<NodeT *>(A)),
00731                    getNode(const_cast<NodeT *>(B)));
00732 }
00733 
00734 }
00735 
00736 #endif