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