LLVM API Documentation

Dominators.h
Go to the documentation of this file.
00001 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- 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 //
00010 // This file defines the DominatorTree class, which provides fast and efficient
00011 // dominance queries.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_ANALYSIS_DOMINATORS_H
00016 #define LLVM_ANALYSIS_DOMINATORS_H
00017 
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/DepthFirstIterator.h"
00020 #include "llvm/ADT/GraphTraits.h"
00021 #include "llvm/ADT/SmallPtrSet.h"
00022 #include "llvm/ADT/SmallVector.h"
00023 #include "llvm/IR/Function.h"
00024 #include "llvm/Pass.h"
00025 #include "llvm/Support/CFG.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 // DomTreeNode - Dominator Tree Node
00059 template<class NodeT> class DominatorTreeBase;
00060 struct PostDominatorTree;
00061 class MachineBasicBlock;
00062 
00063 template <class NodeT>
00064 class DomTreeNodeBase {
00065   NodeT *TheBB;
00066   DomTreeNodeBase<NodeT> *IDom;
00067   std::vector<DomTreeNodeBase<NodeT> *> Children;
00068   int DFSNumIn, DFSNumOut;
00069 
00070   template<class N> friend class DominatorTreeBase;
00071   friend struct PostDominatorTree;
00072 public:
00073   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
00074   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
00075                    const_iterator;
00076 
00077   iterator begin()             { return Children.begin(); }
00078   iterator end()               { return Children.end(); }
00079   const_iterator begin() const { return Children.begin(); }
00080   const_iterator end()   const { return Children.end(); }
00081 
00082   NodeT *getBlock() const { return TheBB; }
00083   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
00084   const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
00085     return Children;
00086   }
00087 
00088   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
00089     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
00090 
00091   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
00092     Children.push_back(C);
00093     return C;
00094   }
00095 
00096   size_t getNumChildren() const {
00097     return Children.size();
00098   }
00099 
00100   void clearAllChildren() {
00101     Children.clear();
00102   }
00103 
00104   bool compare(const DomTreeNodeBase<NodeT> *Other) const {
00105     if (getNumChildren() != Other->getNumChildren())
00106       return true;
00107 
00108     SmallPtrSet<const NodeT *, 4> OtherChildren;
00109     for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
00110       const NodeT *Nd = (*I)->getBlock();
00111       OtherChildren.insert(Nd);
00112     }
00113 
00114     for (const_iterator I = begin(), E = end(); I != E; ++I) {
00115       const NodeT *N = (*I)->getBlock();
00116       if (OtherChildren.count(N) == 0)
00117         return true;
00118     }
00119     return false;
00120   }
00121 
00122   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
00123     assert(IDom && "No immediate dominator?");
00124     if (IDom != NewIDom) {
00125       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
00126                   std::find(IDom->Children.begin(), IDom->Children.end(), this);
00127       assert(I != IDom->Children.end() &&
00128              "Not in immediate dominator children set!");
00129       // I am no longer your child...
00130       IDom->Children.erase(I);
00131 
00132       // Switch to new dominator
00133       IDom = NewIDom;
00134       IDom->Children.push_back(this);
00135     }
00136   }
00137 
00138   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
00139   /// not call them.
00140   unsigned getDFSNumIn() const { return DFSNumIn; }
00141   unsigned getDFSNumOut() const { return DFSNumOut; }
00142 private:
00143   // Return true if this node is dominated by other. Use this only if DFS info
00144   // is valid.
00145   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
00146     return this->DFSNumIn >= other->DFSNumIn &&
00147       this->DFSNumOut <= other->DFSNumOut;
00148   }
00149 };
00150 
00151 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
00152 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
00153 
00154 template<class NodeT>
00155 inline raw_ostream &operator<<(raw_ostream &o,
00156                                const DomTreeNodeBase<NodeT> *Node) {
00157   if (Node->getBlock())
00158     WriteAsOperand(o, Node->getBlock(), false);
00159   else
00160     o << " <<exit node>>";
00161 
00162   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
00163 
00164   return o << "\n";
00165 }
00166 
00167 template<class NodeT>
00168 inline void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
00169                          unsigned Lev) {
00170   o.indent(2*Lev) << "[" << Lev << "] " << N;
00171   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
00172        E = N->end(); I != E; ++I)
00173     PrintDomTree<NodeT>(*I, o, Lev+1);
00174 }
00175 
00176 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
00177 
00178 //===----------------------------------------------------------------------===//
00179 /// DominatorTree - Calculate the immediate dominator tree for a function.
00180 ///
00181 
00182 template<class FuncT, class N>
00183 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
00184                FuncT& F);
00185 
00186 template<class NodeT>
00187 class DominatorTreeBase : public DominatorBase<NodeT> {
00188   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
00189                                const DomTreeNodeBase<NodeT> *B) const {
00190     assert(A != B);
00191     assert(isReachableFromEntry(B));
00192     assert(isReachableFromEntry(A));
00193 
00194     const DomTreeNodeBase<NodeT> *IDom;
00195     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
00196       B = IDom;   // Walk up the tree
00197     return IDom != 0;
00198   }
00199 
00200 protected:
00201   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
00202   DomTreeNodeMapType DomTreeNodes;
00203   DomTreeNodeBase<NodeT> *RootNode;
00204 
00205   bool DFSInfoValid;
00206   unsigned int SlowQueries;
00207   // Information record used during immediate dominators computation.
00208   struct InfoRec {
00209     unsigned DFSNum;
00210     unsigned Parent;
00211     unsigned Semi;
00212     NodeT *Label;
00213 
00214     InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(0) {}
00215   };
00216 
00217   DenseMap<NodeT*, NodeT*> IDoms;
00218 
00219   // Vertex - Map the DFS number to the BasicBlock*
00220   std::vector<NodeT*> Vertex;
00221 
00222   // Info - Collection of information used during the computation of idoms.
00223   DenseMap<NodeT*, InfoRec> Info;
00224 
00225   void reset() {
00226     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
00227            E = DomTreeNodes.end(); I != E; ++I)
00228       delete I->second;
00229     DomTreeNodes.clear();
00230     IDoms.clear();
00231     this->Roots.clear();
00232     Vertex.clear();
00233     RootNode = 0;
00234   }
00235 
00236   // NewBB is split and now it has one successor. Update dominator tree to
00237   // reflect this change.
00238   template<class N, class GraphT>
00239   void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
00240              typename GraphT::NodeType* NewBB) {
00241     assert(std::distance(GraphT::child_begin(NewBB),
00242                          GraphT::child_end(NewBB)) == 1 &&
00243            "NewBB should have a single successor!");
00244     typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
00245 
00246     std::vector<typename GraphT::NodeType*> PredBlocks;
00247     typedef GraphTraits<Inverse<N> > InvTraits;
00248     for (typename InvTraits::ChildIteratorType PI =
00249          InvTraits::child_begin(NewBB),
00250          PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
00251       PredBlocks.push_back(*PI);
00252 
00253     assert(!PredBlocks.empty() && "No predblocks?");
00254 
00255     bool NewBBDominatesNewBBSucc = true;
00256     for (typename InvTraits::ChildIteratorType PI =
00257          InvTraits::child_begin(NewBBSucc),
00258          E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
00259       typename InvTraits::NodeType *ND = *PI;
00260       if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
00261           DT.isReachableFromEntry(ND)) {
00262         NewBBDominatesNewBBSucc = false;
00263         break;
00264       }
00265     }
00266 
00267     // Find NewBB's immediate dominator and create new dominator tree node for
00268     // NewBB.
00269     NodeT *NewBBIDom = 0;
00270     unsigned i = 0;
00271     for (i = 0; i < PredBlocks.size(); ++i)
00272       if (DT.isReachableFromEntry(PredBlocks[i])) {
00273         NewBBIDom = PredBlocks[i];
00274         break;
00275       }
00276 
00277     // It's possible that none of the predecessors of NewBB are reachable;
00278     // in that case, NewBB itself is unreachable, so nothing needs to be
00279     // changed.
00280     if (!NewBBIDom)
00281       return;
00282 
00283     for (i = i + 1; i < PredBlocks.size(); ++i) {
00284       if (DT.isReachableFromEntry(PredBlocks[i]))
00285         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
00286     }
00287 
00288     // Create the new dominator tree node... and set the idom of NewBB.
00289     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
00290 
00291     // If NewBB strictly dominates other blocks, then it is now the immediate
00292     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
00293     if (NewBBDominatesNewBBSucc) {
00294       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
00295       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
00296     }
00297   }
00298 
00299 public:
00300   explicit DominatorTreeBase(bool isPostDom)
00301     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
00302   virtual ~DominatorTreeBase() { reset(); }
00303 
00304   /// compare - Return false if the other dominator tree base matches this
00305   /// dominator tree base. Otherwise return true.
00306   bool compare(DominatorTreeBase &Other) const {
00307 
00308     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
00309     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
00310       return true;
00311 
00312     for (typename DomTreeNodeMapType::const_iterator
00313            I = this->DomTreeNodes.begin(),
00314            E = this->DomTreeNodes.end(); I != E; ++I) {
00315       NodeT *BB = I->first;
00316       typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
00317       if (OI == OtherDomTreeNodes.end())
00318         return true;
00319 
00320       DomTreeNodeBase<NodeT>* MyNd = I->second;
00321       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
00322 
00323       if (MyNd->compare(OtherNd))
00324         return true;
00325     }
00326 
00327     return false;
00328   }
00329 
00330   virtual void releaseMemory() { reset(); }
00331 
00332   /// getNode - return the (Post)DominatorTree node for the specified basic
00333   /// block.  This is the same as using operator[] on this class.
00334   ///
00335   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
00336     return DomTreeNodes.lookup(BB);
00337   }
00338 
00339   /// getRootNode - This returns the entry node for the CFG of the function.  If
00340   /// this tree represents the post-dominance relations for a function, however,
00341   /// this root may be a node with the block == NULL.  This is the case when
00342   /// there are multiple exit nodes from a particular function.  Consumers of
00343   /// post-dominance information must be capable of dealing with this
00344   /// possibility.
00345   ///
00346   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
00347   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
00348 
00349   /// properlyDominates - Returns true iff A dominates B and A != B.
00350   /// Note that this is not a constant time operation!
00351   ///
00352   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
00353                          const DomTreeNodeBase<NodeT> *B) {
00354     if (A == 0 || B == 0)
00355       return false;
00356     if (A == B)
00357       return false;
00358     return dominates(A, B);
00359   }
00360 
00361   bool properlyDominates(const NodeT *A, const NodeT *B);
00362 
00363   /// isReachableFromEntry - Return true if A is dominated by the entry
00364   /// block of the function containing it.
00365   bool isReachableFromEntry(const NodeT* A) const {
00366     assert(!this->isPostDominator() &&
00367            "This is not implemented for post dominators");
00368     return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
00369   }
00370 
00371   inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
00372     return A;
00373   }
00374 
00375   /// dominates - Returns true iff A dominates B.  Note that this is not a
00376   /// constant time operation!
00377   ///
00378   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
00379                         const DomTreeNodeBase<NodeT> *B) {
00380     // A node trivially dominates itself.
00381     if (B == A)
00382       return true;
00383 
00384     // An unreachable node is dominated by anything.
00385     if (!isReachableFromEntry(B))
00386       return true;
00387 
00388     // And dominates nothing.
00389     if (!isReachableFromEntry(A))
00390       return false;
00391 
00392     // Compare the result of the tree walk and the dfs numbers, if expensive
00393     // checks are enabled.
00394 #ifdef XDEBUG
00395     assert((!DFSInfoValid ||
00396             (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
00397            "Tree walk disagrees with dfs numbers!");
00398 #endif
00399 
00400     if (DFSInfoValid)
00401       return B->DominatedBy(A);
00402 
00403     // If we end up with too many slow queries, just update the
00404     // DFS numbers on the theory that we are going to keep querying.
00405     SlowQueries++;
00406     if (SlowQueries > 32) {
00407       updateDFSNumbers();
00408       return B->DominatedBy(A);
00409     }
00410 
00411     return dominatedBySlowTreeWalk(A, B);
00412   }
00413 
00414   bool dominates(const NodeT *A, const NodeT *B);
00415 
00416   NodeT *getRoot() const {
00417     assert(this->Roots.size() == 1 && "Should always have entry node!");
00418     return this->Roots[0];
00419   }
00420 
00421   /// findNearestCommonDominator - Find nearest common dominator basic block
00422   /// for basic block A and B. If there is no such block then return NULL.
00423   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
00424     assert(A->getParent() == B->getParent() &&
00425            "Two blocks are not in same function");
00426 
00427     // If either A or B is a entry block then it is nearest common dominator
00428     // (for forward-dominators).
00429     if (!this->isPostDominator()) {
00430       NodeT &Entry = A->getParent()->front();
00431       if (A == &Entry || B == &Entry)
00432         return &Entry;
00433     }
00434 
00435     // If B dominates A then B is nearest common dominator.
00436     if (dominates(B, A))
00437       return B;
00438 
00439     // If A dominates B then A is nearest common dominator.
00440     if (dominates(A, B))
00441       return A;
00442 
00443     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
00444     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
00445 
00446     // Collect NodeA dominators set.
00447     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
00448     NodeADoms.insert(NodeA);
00449     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
00450     while (IDomA) {
00451       NodeADoms.insert(IDomA);
00452       IDomA = IDomA->getIDom();
00453     }
00454 
00455     // Walk NodeB immediate dominators chain and find common dominator node.
00456     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
00457     while (IDomB) {
00458       if (NodeADoms.count(IDomB) != 0)
00459         return IDomB->getBlock();
00460 
00461       IDomB = IDomB->getIDom();
00462     }
00463 
00464     return NULL;
00465   }
00466 
00467   const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
00468     // Cast away the const qualifiers here. This is ok since
00469     // const is re-introduced on the return type.
00470     return findNearestCommonDominator(const_cast<NodeT *>(A),
00471                                       const_cast<NodeT *>(B));
00472   }
00473 
00474   //===--------------------------------------------------------------------===//
00475   // API to update (Post)DominatorTree information based on modifications to
00476   // the CFG...
00477 
00478   /// addNewBlock - Add a new node to the dominator tree information.  This
00479   /// creates a new node as a child of DomBB dominator node,linking it into
00480   /// the children list of the immediate dominator.
00481   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
00482     assert(getNode(BB) == 0 && "Block already in dominator tree!");
00483     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
00484     assert(IDomNode && "Not immediate dominator specified for block!");
00485     DFSInfoValid = false;
00486     return DomTreeNodes[BB] =
00487       IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
00488   }
00489 
00490   /// changeImmediateDominator - This method is used to update the dominator
00491   /// tree information when a node's immediate dominator changes.
00492   ///
00493   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
00494                                 DomTreeNodeBase<NodeT> *NewIDom) {
00495     assert(N && NewIDom && "Cannot change null node pointers!");
00496     DFSInfoValid = false;
00497     N->setIDom(NewIDom);
00498   }
00499 
00500   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
00501     changeImmediateDominator(getNode(BB), getNode(NewBB));
00502   }
00503 
00504   /// eraseNode - Removes a node from the dominator tree. Block must not
00505   /// dominate any other blocks. Removes node from its immediate dominator's
00506   /// children list. Deletes dominator node associated with basic block BB.
00507   void eraseNode(NodeT *BB) {
00508     DomTreeNodeBase<NodeT> *Node = getNode(BB);
00509     assert(Node && "Removing node that isn't in dominator tree.");
00510     assert(Node->getChildren().empty() && "Node is not a leaf node.");
00511 
00512       // Remove node from immediate dominator's children list.
00513     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
00514     if (IDom) {
00515       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
00516         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
00517       assert(I != IDom->Children.end() &&
00518              "Not in immediate dominator children set!");
00519       // I am no longer your child...
00520       IDom->Children.erase(I);
00521     }
00522 
00523     DomTreeNodes.erase(BB);
00524     delete Node;
00525   }
00526 
00527   /// removeNode - Removes a node from the dominator tree.  Block must not
00528   /// dominate any other blocks.  Invalidates any node pointing to removed
00529   /// block.
00530   void removeNode(NodeT *BB) {
00531     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
00532     DomTreeNodes.erase(BB);
00533   }
00534 
00535   /// splitBlock - BB is split and now it has one successor. Update dominator
00536   /// tree to reflect this change.
00537   void splitBlock(NodeT* NewBB) {
00538     if (this->IsPostDominators)
00539       this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
00540     else
00541       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
00542   }
00543 
00544   /// print - Convert to human readable form
00545   ///
00546   void print(raw_ostream &o) const {
00547     o << "=============================--------------------------------\n";
00548     if (this->isPostDominator())
00549       o << "Inorder PostDominator Tree: ";
00550     else
00551       o << "Inorder Dominator Tree: ";
00552     if (!this->DFSInfoValid)
00553       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
00554     o << "\n";
00555 
00556     // The postdom tree can have a null root if there are no returns.
00557     if (getRootNode())
00558       PrintDomTree<NodeT>(getRootNode(), o, 1);
00559   }
00560 
00561 protected:
00562   template<class GraphT>
00563   friend typename GraphT::NodeType* Eval(
00564                                DominatorTreeBase<typename GraphT::NodeType>& DT,
00565                                          typename GraphT::NodeType* V,
00566                                          unsigned LastLinked);
00567 
00568   template<class GraphT>
00569   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
00570                           typename GraphT::NodeType* V,
00571                           unsigned N);
00572 
00573   template<class FuncT, class N>
00574   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
00575                         FuncT& F);
00576 
00577   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
00578   /// dominator tree in dfs order.
00579   void updateDFSNumbers() {
00580     unsigned DFSNum = 0;
00581 
00582     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
00583                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
00584 
00585     DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
00586 
00587     if (!ThisRoot)
00588       return;
00589 
00590     // Even in the case of multiple exits that form the post dominator root
00591     // nodes, do not iterate over all exits, but start from the virtual root
00592     // node. Otherwise bbs, that are not post dominated by any exit but by the
00593     // virtual root node, will never be assigned a DFS number.
00594     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
00595     ThisRoot->DFSNumIn = DFSNum++;
00596 
00597     while (!WorkStack.empty()) {
00598       DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
00599       typename DomTreeNodeBase<NodeT>::iterator ChildIt =
00600         WorkStack.back().second;
00601 
00602       // If we visited all of the children of this node, "recurse" back up the
00603       // stack setting the DFOutNum.
00604       if (ChildIt == Node->end()) {
00605         Node->DFSNumOut = DFSNum++;
00606         WorkStack.pop_back();
00607       } else {
00608         // Otherwise, recursively visit this child.
00609         DomTreeNodeBase<NodeT> *Child = *ChildIt;
00610         ++WorkStack.back().second;
00611 
00612         WorkStack.push_back(std::make_pair(Child, Child->begin()));
00613         Child->DFSNumIn = DFSNum++;
00614       }
00615     }
00616 
00617     SlowQueries = 0;
00618     DFSInfoValid = true;
00619   }
00620 
00621   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
00622     if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
00623       return Node;
00624 
00625     // Haven't calculated this node yet?  Get or calculate the node for the
00626     // immediate dominator.
00627     NodeT *IDom = getIDom(BB);
00628 
00629     assert(IDom || this->DomTreeNodes[NULL]);
00630     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
00631 
00632     // Add a new tree node for this BasicBlock, and link it as a child of
00633     // IDomNode
00634     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
00635     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
00636   }
00637 
00638   inline NodeT *getIDom(NodeT *BB) const {
00639     return IDoms.lookup(BB);
00640   }
00641 
00642   inline void addRoot(NodeT* BB) {
00643     this->Roots.push_back(BB);
00644   }
00645 
00646 public:
00647   /// recalculate - compute a dominator tree for the given function
00648   template<class FT>
00649   void recalculate(FT& F) {
00650     typedef GraphTraits<FT*> TraitsTy;
00651     reset();
00652     this->Vertex.push_back(0);
00653 
00654     if (!this->IsPostDominators) {
00655       // Initialize root
00656       NodeT *entry = TraitsTy::getEntryNode(&F);
00657       this->Roots.push_back(entry);
00658       this->IDoms[entry] = 0;
00659       this->DomTreeNodes[entry] = 0;
00660 
00661       Calculate<FT, NodeT*>(*this, F);
00662     } else {
00663       // Initialize the roots list
00664       for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
00665                                         E = TraitsTy::nodes_end(&F); I != E; ++I) {
00666         if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
00667           addRoot(I);
00668 
00669         // Prepopulate maps so that we don't get iterator invalidation issues later.
00670         this->IDoms[I] = 0;
00671         this->DomTreeNodes[I] = 0;
00672       }
00673 
00674       Calculate<FT, Inverse<NodeT*> >(*this, F);
00675     }
00676   }
00677 };
00678 
00679 // These two functions are declared out of line as a workaround for building
00680 // with old (< r147295) versions of clang because of pr11642.
00681 template<class NodeT>
00682 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) {
00683   if (A == B)
00684     return true;
00685 
00686   // Cast away the const qualifiers here. This is ok since
00687   // this function doesn't actually return the values returned
00688   // from getNode.
00689   return dominates(getNode(const_cast<NodeT *>(A)),
00690                    getNode(const_cast<NodeT *>(B)));
00691 }
00692 template<class NodeT>
00693 bool
00694 DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B) {
00695   if (A == B)
00696     return false;
00697 
00698   // Cast away the const qualifiers here. This is ok since
00699   // this function doesn't actually return the values returned
00700   // from getNode.
00701   return dominates(getNode(const_cast<NodeT *>(A)),
00702                    getNode(const_cast<NodeT *>(B)));
00703 }
00704 
00705 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
00706 
00707 class BasicBlockEdge {
00708   const BasicBlock *Start;
00709   const BasicBlock *End;
00710 public:
00711   BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) :
00712     Start(Start_), End(End_) { }
00713   const BasicBlock *getStart() const {
00714     return Start;
00715   }
00716   const BasicBlock *getEnd() const {
00717     return End;
00718   }
00719   bool isSingleEdge() const;
00720 };
00721 
00722 //===-------------------------------------
00723 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
00724 /// compute a normal dominator tree.
00725 ///
00726 class DominatorTree : public FunctionPass {
00727 public:
00728   static char ID; // Pass ID, replacement for typeid
00729   DominatorTreeBase<BasicBlock>* DT;
00730 
00731   DominatorTree() : FunctionPass(ID) {
00732     initializeDominatorTreePass(*PassRegistry::getPassRegistry());
00733     DT = new DominatorTreeBase<BasicBlock>(false);
00734   }
00735 
00736   ~DominatorTree() {
00737     delete DT;
00738   }
00739 
00740   DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
00741 
00742   /// getRoots - Return the root blocks of the current CFG.  This may include
00743   /// multiple blocks if we are computing post dominators.  For forward
00744   /// dominators, this will always be a single block (the entry node).
00745   ///
00746   inline const std::vector<BasicBlock*> &getRoots() const {
00747     return DT->getRoots();
00748   }
00749 
00750   inline BasicBlock *getRoot() const {
00751     return DT->getRoot();
00752   }
00753 
00754   inline DomTreeNode *getRootNode() const {
00755     return DT->getRootNode();
00756   }
00757 
00758   /// compare - Return false if the other dominator tree matches this
00759   /// dominator tree. Otherwise return true.
00760   inline bool compare(DominatorTree &Other) const {
00761     DomTreeNode *R = getRootNode();
00762     DomTreeNode *OtherR = Other.getRootNode();
00763 
00764     if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
00765       return true;
00766 
00767     if (DT->compare(Other.getBase()))
00768       return true;
00769 
00770     return false;
00771   }
00772 
00773   virtual bool runOnFunction(Function &F);
00774 
00775   virtual void verifyAnalysis() const;
00776 
00777   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00778     AU.setPreservesAll();
00779   }
00780 
00781   inline bool dominates(const DomTreeNode* A, const DomTreeNode* B) const {
00782     return DT->dominates(A, B);
00783   }
00784 
00785   inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
00786     return DT->dominates(A, B);
00787   }
00788 
00789   // dominates - Return true if Def dominates a use in User. This performs
00790   // the special checks necessary if Def and User are in the same basic block.
00791   // Note that Def doesn't dominate a use in Def itself!
00792   bool dominates(const Instruction *Def, const Use &U) const;
00793   bool dominates(const Instruction *Def, const Instruction *User) const;
00794   bool dominates(const Instruction *Def, const BasicBlock *BB) const;
00795   bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
00796   bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
00797 
00798   bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
00799     return DT->properlyDominates(A, B);
00800   }
00801 
00802   bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const {
00803     return DT->properlyDominates(A, B);
00804   }
00805 
00806   /// findNearestCommonDominator - Find nearest common dominator basic block
00807   /// for basic block A and B. If there is no such block then return NULL.
00808   inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
00809     return DT->findNearestCommonDominator(A, B);
00810   }
00811 
00812   inline const BasicBlock *findNearestCommonDominator(const BasicBlock *A,
00813                                                       const BasicBlock *B) {
00814     return DT->findNearestCommonDominator(A, B);
00815   }
00816 
00817   inline DomTreeNode *operator[](BasicBlock *BB) const {
00818     return DT->getNode(BB);
00819   }
00820 
00821   /// getNode - return the (Post)DominatorTree node for the specified basic
00822   /// block.  This is the same as using operator[] on this class.
00823   ///
00824   inline DomTreeNode *getNode(BasicBlock *BB) const {
00825     return DT->getNode(BB);
00826   }
00827 
00828   /// addNewBlock - Add a new node to the dominator tree information.  This
00829   /// creates a new node as a child of DomBB dominator node,linking it into
00830   /// the children list of the immediate dominator.
00831   inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
00832     return DT->addNewBlock(BB, DomBB);
00833   }
00834 
00835   /// changeImmediateDominator - This method is used to update the dominator
00836   /// tree information when a node's immediate dominator changes.
00837   ///
00838   inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
00839     DT->changeImmediateDominator(N, NewIDom);
00840   }
00841 
00842   inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
00843     DT->changeImmediateDominator(N, NewIDom);
00844   }
00845 
00846   /// eraseNode - Removes a node from the dominator tree. Block must not
00847   /// dominate any other blocks. Removes node from its immediate dominator's
00848   /// children list. Deletes dominator node associated with basic block BB.
00849   inline void eraseNode(BasicBlock *BB) {
00850     DT->eraseNode(BB);
00851   }
00852 
00853   /// splitBlock - BB is split and now it has one successor. Update dominator
00854   /// tree to reflect this change.
00855   inline void splitBlock(BasicBlock* NewBB) {
00856     DT->splitBlock(NewBB);
00857   }
00858 
00859   bool isReachableFromEntry(const BasicBlock* A) const {
00860     return DT->isReachableFromEntry(A);
00861   }
00862 
00863   bool isReachableFromEntry(const Use &U) const;
00864 
00865 
00866   virtual void releaseMemory() {
00867     DT->releaseMemory();
00868   }
00869 
00870   virtual void print(raw_ostream &OS, const Module* M= 0) const;
00871 };
00872 
00873 //===-------------------------------------
00874 /// DominatorTree GraphTraits specialization so the DominatorTree can be
00875 /// iterable by generic graph iterators.
00876 ///
00877 template <> struct GraphTraits<DomTreeNode*> {
00878   typedef DomTreeNode NodeType;
00879   typedef NodeType::iterator  ChildIteratorType;
00880 
00881   static NodeType *getEntryNode(NodeType *N) {
00882     return N;
00883   }
00884   static inline ChildIteratorType child_begin(NodeType *N) {
00885     return N->begin();
00886   }
00887   static inline ChildIteratorType child_end(NodeType *N) {
00888     return N->end();
00889   }
00890 
00891   typedef df_iterator<DomTreeNode*> nodes_iterator;
00892 
00893   static nodes_iterator nodes_begin(DomTreeNode *N) {
00894     return df_begin(getEntryNode(N));
00895   }
00896 
00897   static nodes_iterator nodes_end(DomTreeNode *N) {
00898     return df_end(getEntryNode(N));
00899   }
00900 };
00901 
00902 template <> struct GraphTraits<DominatorTree*>
00903   : public GraphTraits<DomTreeNode*> {
00904   static NodeType *getEntryNode(DominatorTree *DT) {
00905     return DT->getRootNode();
00906   }
00907 
00908   static nodes_iterator nodes_begin(DominatorTree *N) {
00909     return df_begin(getEntryNode(N));
00910   }
00911 
00912   static nodes_iterator nodes_end(DominatorTree *N) {
00913     return df_end(getEntryNode(N));
00914   }
00915 };
00916 
00917 
00918 } // End llvm namespace
00919 
00920 #endif