LLVM API Documentation
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 following classes: 00011 // 1. DominatorTree: Represent dominators as an explicit tree structure. 00012 // 2. DominanceFrontier: Calculate and hold the dominance frontier for a 00013 // function. 00014 // 00015 // These data structures are listed in increasing order of complexity. It 00016 // takes longer to calculate the dominator frontier, for example, than the 00017 // DominatorTree mapping. 00018 // 00019 //===----------------------------------------------------------------------===// 00020 00021 #ifndef LLVM_ANALYSIS_DOMINATORS_H 00022 #define LLVM_ANALYSIS_DOMINATORS_H 00023 00024 #include "llvm/Pass.h" 00025 #include "llvm/BasicBlock.h" 00026 #include "llvm/Function.h" 00027 #include "llvm/Instructions.h" 00028 #include "llvm/ADT/DenseMap.h" 00029 #include "llvm/ADT/GraphTraits.h" 00030 #include "llvm/ADT/SmallPtrSet.h" 00031 #include "llvm/ADT/SmallVector.h" 00032 #include "llvm/Assembly/Writer.h" 00033 #include "llvm/Support/CFG.h" 00034 #include "llvm/Support/Compiler.h" 00035 #include <algorithm> 00036 #include <map> 00037 #include <set> 00038 00039 namespace llvm { 00040 00041 //===----------------------------------------------------------------------===// 00042 /// DominatorBase - Base class that other, more interesting dominator analyses 00043 /// inherit from. 00044 /// 00045 template <class NodeT> 00046 class DominatorBase { 00047 protected: 00048 std::vector<NodeT*> Roots; 00049 const bool IsPostDominators; 00050 inline explicit DominatorBase(bool isPostDom) : 00051 Roots(), IsPostDominators(isPostDom) {} 00052 public: 00053 00054 /// getRoots - Return the root blocks of the current CFG. This may include 00055 /// multiple blocks if we are computing post dominators. For forward 00056 /// dominators, this will always be a single block (the entry node). 00057 /// 00058 inline const std::vector<NodeT*> &getRoots() const { return Roots; } 00059 00060 /// isPostDominator - Returns true if analysis based of postdoms 00061 /// 00062 bool isPostDominator() const { return IsPostDominators; } 00063 }; 00064 00065 00066 //===----------------------------------------------------------------------===// 00067 // DomTreeNode - Dominator Tree Node 00068 template<class NodeT> class DominatorTreeBase; 00069 struct PostDominatorTree; 00070 class MachineBasicBlock; 00071 00072 template <class NodeT> 00073 class DomTreeNodeBase { 00074 NodeT *TheBB; 00075 DomTreeNodeBase<NodeT> *IDom; 00076 std::vector<DomTreeNodeBase<NodeT> *> Children; 00077 int DFSNumIn, DFSNumOut; 00078 00079 template<class N> friend class DominatorTreeBase; 00080 friend struct PostDominatorTree; 00081 public: 00082 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator; 00083 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator 00084 const_iterator; 00085 00086 iterator begin() { return Children.begin(); } 00087 iterator end() { return Children.end(); } 00088 const_iterator begin() const { return Children.begin(); } 00089 const_iterator end() const { return Children.end(); } 00090 00091 NodeT *getBlock() const { return TheBB; } 00092 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; } 00093 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const { 00094 return Children; 00095 } 00096 00097 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom) 00098 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { } 00099 00100 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) { 00101 Children.push_back(C); 00102 return C; 00103 } 00104 00105 size_t getNumChildren() const { 00106 return Children.size(); 00107 } 00108 00109 void clearAllChildren() { 00110 Children.clear(); 00111 } 00112 00113 bool compare(DomTreeNodeBase<NodeT> *Other) { 00114 if (getNumChildren() != Other->getNumChildren()) 00115 return true; 00116 00117 SmallPtrSet<NodeT *, 4> OtherChildren; 00118 for(iterator I = Other->begin(), E = Other->end(); I != E; ++I) { 00119 NodeT *Nd = (*I)->getBlock(); 00120 OtherChildren.insert(Nd); 00121 } 00122 00123 for(iterator I = begin(), E = end(); I != E; ++I) { 00124 NodeT *N = (*I)->getBlock(); 00125 if (OtherChildren.count(N) == 0) 00126 return true; 00127 } 00128 return false; 00129 } 00130 00131 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) { 00132 assert(IDom && "No immediate dominator?"); 00133 if (IDom != NewIDom) { 00134 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I = 00135 std::find(IDom->Children.begin(), IDom->Children.end(), this); 00136 assert(I != IDom->Children.end() && 00137 "Not in immediate dominator children set!"); 00138 // I am no longer your child... 00139 IDom->Children.erase(I); 00140 00141 // Switch to new dominator 00142 IDom = NewIDom; 00143 IDom->Children.push_back(this); 00144 } 00145 } 00146 00147 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do 00148 /// not call them. 00149 unsigned getDFSNumIn() const { return DFSNumIn; } 00150 unsigned getDFSNumOut() const { return DFSNumOut; } 00151 private: 00152 // Return true if this node is dominated by other. Use this only if DFS info 00153 // is valid. 00154 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const { 00155 return this->DFSNumIn >= other->DFSNumIn && 00156 this->DFSNumOut <= other->DFSNumOut; 00157 } 00158 }; 00159 00160 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>); 00161 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>); 00162 00163 template<class NodeT> 00164 static std::ostream &operator<<(std::ostream &o, 00165 const DomTreeNodeBase<NodeT> *Node) { 00166 if (Node->getBlock()) 00167 WriteAsOperand(o, Node->getBlock(), false); 00168 else 00169 o << " <<exit node>>"; 00170 00171 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}"; 00172 00173 return o << "\n"; 00174 } 00175 00176 template<class NodeT> 00177 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, std::ostream &o, 00178 unsigned Lev) { 00179 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N; 00180 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(), 00181 E = N->end(); I != E; ++I) 00182 PrintDomTree<NodeT>(*I, o, Lev+1); 00183 } 00184 00185 typedef DomTreeNodeBase<BasicBlock> DomTreeNode; 00186 00187 //===----------------------------------------------------------------------===// 00188 /// DominatorTree - Calculate the immediate dominator tree for a function. 00189 /// 00190 00191 template<class FuncT, class N> 00192 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT, 00193 FuncT& F); 00194 00195 template<class NodeT> 00196 class DominatorTreeBase : public DominatorBase<NodeT> { 00197 protected: 00198 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType; 00199 DomTreeNodeMapType DomTreeNodes; 00200 DomTreeNodeBase<NodeT> *RootNode; 00201 00202 bool DFSInfoValid; 00203 unsigned int SlowQueries; 00204 // Information record used during immediate dominators computation. 00205 struct InfoRec { 00206 unsigned DFSNum; 00207 unsigned Semi; 00208 unsigned Size; 00209 NodeT *Label, *Child; 00210 unsigned Parent, Ancestor; 00211 00212 std::vector<NodeT*> Bucket; 00213 00214 InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0), 00215 Ancestor(0) {} 00216 }; 00217 00218 DenseMap<NodeT*, NodeT*> IDoms; 00219 00220 // Vertex - Map the DFS number to the BasicBlock* 00221 std::vector<NodeT*> Vertex; 00222 00223 // Info - Collection of information used during the computation of idoms. 00224 DenseMap<NodeT*, InfoRec> Info; 00225 00226 void reset() { 00227 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(), 00228 E = DomTreeNodes.end(); I != E; ++I) 00229 delete I->second; 00230 DomTreeNodes.clear(); 00231 IDoms.clear(); 00232 this->Roots.clear(); 00233 Vertex.clear(); 00234 RootNode = 0; 00235 } 00236 00237 // NewBB is split and now it has one successor. Update dominator tree to 00238 // reflect this change. 00239 template<class N, class GraphT> 00240 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT, 00241 typename GraphT::NodeType* NewBB) { 00242 assert(std::distance(GraphT::child_begin(NewBB), 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 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI = 00248 GraphTraits<Inverse<N> >::child_begin(NewBB), 00249 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI) 00250 PredBlocks.push_back(*PI); 00251 00252 assert(!PredBlocks.empty() && "No predblocks??"); 00253 00254 // The newly inserted basic block will dominate existing basic blocks iff the 00255 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate 00256 // the non-pred blocks, then they all must be the same block! 00257 // 00258 bool NewBBDominatesNewBBSucc = true; 00259 { 00260 typename GraphT::NodeType* OnePred = PredBlocks[0]; 00261 size_t i = 1, e = PredBlocks.size(); 00262 for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) { 00263 assert(i != e && "Didn't find reachable pred?"); 00264 OnePred = PredBlocks[i]; 00265 } 00266 00267 for (; i != e; ++i) 00268 if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) { 00269 NewBBDominatesNewBBSucc = false; 00270 break; 00271 } 00272 00273 if (NewBBDominatesNewBBSucc) 00274 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI = 00275 GraphTraits<Inverse<N> >::child_begin(NewBBSucc), 00276 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI) 00277 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) { 00278 NewBBDominatesNewBBSucc = false; 00279 break; 00280 } 00281 } 00282 00283 // The other scenario where the new block can dominate its successors are when 00284 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc 00285 // already. 00286 if (!NewBBDominatesNewBBSucc) { 00287 NewBBDominatesNewBBSucc = true; 00288 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI = 00289 GraphTraits<Inverse<N> >::child_begin(NewBBSucc), 00290 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI) 00291 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) { 00292 NewBBDominatesNewBBSucc = false; 00293 break; 00294 } 00295 } 00296 00297 // Find NewBB's immediate dominator and create new dominator tree node for 00298 // NewBB. 00299 NodeT *NewBBIDom = 0; 00300 unsigned i = 0; 00301 for (i = 0; i < PredBlocks.size(); ++i) 00302 if (DT.isReachableFromEntry(PredBlocks[i])) { 00303 NewBBIDom = PredBlocks[i]; 00304 break; 00305 } 00306 assert(i != PredBlocks.size() && "No reachable preds?"); 00307 for (i = i + 1; i < PredBlocks.size(); ++i) { 00308 if (DT.isReachableFromEntry(PredBlocks[i])) 00309 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]); 00310 } 00311 assert(NewBBIDom && "No immediate dominator found??"); 00312 00313 // Create the new dominator tree node... and set the idom of NewBB. 00314 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom); 00315 00316 // If NewBB strictly dominates other blocks, then it is now the immediate 00317 // dominator of NewBBSucc. Update the dominator tree as appropriate. 00318 if (NewBBDominatesNewBBSucc) { 00319 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc); 00320 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode); 00321 } 00322 } 00323 00324 public: 00325 explicit DominatorTreeBase(bool isPostDom) 00326 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {} 00327 virtual ~DominatorTreeBase() { reset(); } 00328 00329 // FIXME: Should remove this 00330 virtual bool runOnFunction(Function &F) { return false; } 00331 00332 /// compare - Return false if the other dominator tree base matches this 00333 /// dominator tree base. Otherwise return true. 00334 bool compare(DominatorTreeBase &Other) const { 00335 00336 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes; 00337 if (DomTreeNodes.size() != OtherDomTreeNodes.size()) 00338 return true; 00339 00340 SmallPtrSet<const NodeT *,4> MyBBs; 00341 for (typename DomTreeNodeMapType::const_iterator 00342 I = this->DomTreeNodes.begin(), 00343 E = this->DomTreeNodes.end(); I != E; ++I) { 00344 NodeT *BB = I->first; 00345 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB); 00346 if (OI == OtherDomTreeNodes.end()) 00347 return true; 00348 00349 DomTreeNodeBase<NodeT>* MyNd = I->second; 00350 DomTreeNodeBase<NodeT>* OtherNd = OI->second; 00351 00352 if (MyNd->compare(OtherNd)) 00353 return true; 00354 } 00355 00356 return false; 00357 } 00358 00359 virtual void releaseMemory() { reset(); } 00360 00361 /// getNode - return the (Post)DominatorTree node for the specified basic 00362 /// block. This is the same as using operator[] on this class. 00363 /// 00364 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const { 00365 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB); 00366 return I != DomTreeNodes.end() ? I->second : 0; 00367 } 00368 00369 /// getRootNode - This returns the entry node for the CFG of the function. If 00370 /// this tree represents the post-dominance relations for a function, however, 00371 /// this root may be a node with the block == NULL. This is the case when 00372 /// there are multiple exit nodes from a particular function. Consumers of 00373 /// post-dominance information must be capable of dealing with this 00374 /// possibility. 00375 /// 00376 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; } 00377 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; } 00378 00379 /// properlyDominates - Returns true iff this dominates N and this != N. 00380 /// Note that this is not a constant time operation! 00381 /// 00382 bool properlyDominates(const DomTreeNodeBase<NodeT> *A, 00383 DomTreeNodeBase<NodeT> *B) const { 00384 if (A == 0 || B == 0) return false; 00385 return dominatedBySlowTreeWalk(A, B); 00386 } 00387 00388 inline bool properlyDominates(NodeT *A, NodeT *B) { 00389 return properlyDominates(getNode(A), getNode(B)); 00390 } 00391 00392 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, 00393 const DomTreeNodeBase<NodeT> *B) const { 00394 const DomTreeNodeBase<NodeT> *IDom; 00395 if (A == 0 || B == 0) return false; 00396 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B) 00397 B = IDom; // Walk up the tree 00398 return IDom != 0; 00399 } 00400 00401 00402 /// isReachableFromEntry - Return true if A is dominated by the entry 00403 /// block of the function containing it. 00404 bool isReachableFromEntry(NodeT* A) { 00405 assert (!this->isPostDominator() 00406 && "This is not implemented for post dominators"); 00407 return dominates(&A->getParent()->front(), A); 00408 } 00409 00410 /// dominates - Returns true iff A dominates B. Note that this is not a 00411 /// constant time operation! 00412 /// 00413 inline bool dominates(const DomTreeNodeBase<NodeT> *A, 00414 DomTreeNodeBase<NodeT> *B) { 00415 if (B == A) 00416 return true; // A node trivially dominates itself. 00417 00418 if (A == 0 || B == 0) 00419 return false; 00420 00421 if (DFSInfoValid) 00422 return B->DominatedBy(A); 00423 00424 // If we end up with too many slow queries, just update the 00425 // DFS numbers on the theory that we are going to keep querying. 00426 SlowQueries++; 00427 if (SlowQueries > 32) { 00428 updateDFSNumbers(); 00429 return B->DominatedBy(A); 00430 } 00431 00432 return dominatedBySlowTreeWalk(A, B); 00433 } 00434 00435 inline bool dominates(NodeT *A, NodeT *B) { 00436 if (A == B) 00437 return true; 00438 00439 return dominates(getNode(A), getNode(B)); 00440 } 00441 00442 NodeT *getRoot() const { 00443 assert(this->Roots.size() == 1 && "Should always have entry node!"); 00444 return this->Roots[0]; 00445 } 00446 00447 /// findNearestCommonDominator - Find nearest common dominator basic block 00448 /// for basic block A and B. If there is no such block then return NULL. 00449 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) { 00450 00451 assert (!this->isPostDominator() 00452 && "This is not implemented for post dominators"); 00453 assert (A->getParent() == B->getParent() 00454 && "Two blocks are not in same function"); 00455 00456 // If either A or B is a entry block then it is nearest common dominator. 00457 NodeT &Entry = A->getParent()->front(); 00458 if (A == &Entry || B == &Entry) 00459 return &Entry; 00460 00461 // If B dominates A then B is nearest common dominator. 00462 if (dominates(B, A)) 00463 return B; 00464 00465 // If A dominates B then A is nearest common dominator. 00466 if (dominates(A, B)) 00467 return A; 00468 00469 DomTreeNodeBase<NodeT> *NodeA = getNode(A); 00470 DomTreeNodeBase<NodeT> *NodeB = getNode(B); 00471 00472 // Collect NodeA dominators set. 00473 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms; 00474 NodeADoms.insert(NodeA); 00475 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom(); 00476 while (IDomA) { 00477 NodeADoms.insert(IDomA); 00478 IDomA = IDomA->getIDom(); 00479 } 00480 00481 // Walk NodeB immediate dominators chain and find common dominator node. 00482 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom(); 00483 while(IDomB) { 00484 if (NodeADoms.count(IDomB) != 0) 00485 return IDomB->getBlock(); 00486 00487 IDomB = IDomB->getIDom(); 00488 } 00489 00490 return NULL; 00491 } 00492 00493 //===--------------------------------------------------------------------===// 00494 // API to update (Post)DominatorTree information based on modifications to 00495 // the CFG... 00496 00497 /// addNewBlock - Add a new node to the dominator tree information. This 00498 /// creates a new node as a child of DomBB dominator node,linking it into 00499 /// the children list of the immediate dominator. 00500 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) { 00501 assert(getNode(BB) == 0 && "Block already in dominator tree!"); 00502 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB); 00503 assert(IDomNode && "Not immediate dominator specified for block!"); 00504 DFSInfoValid = false; 00505 return DomTreeNodes[BB] = 00506 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode)); 00507 } 00508 00509 /// changeImmediateDominator - This method is used to update the dominator 00510 /// tree information when a node's immediate dominator changes. 00511 /// 00512 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N, 00513 DomTreeNodeBase<NodeT> *NewIDom) { 00514 assert(N && NewIDom && "Cannot change null node pointers!"); 00515 DFSInfoValid = false; 00516 N->setIDom(NewIDom); 00517 } 00518 00519 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) { 00520 changeImmediateDominator(getNode(BB), getNode(NewBB)); 00521 } 00522 00523 /// eraseNode - Removes a node from the dominator tree. Block must not 00524 /// domiante any other blocks. Removes node from its immediate dominator's 00525 /// children list. Deletes dominator node associated with basic block BB. 00526 void eraseNode(NodeT *BB) { 00527 DomTreeNodeBase<NodeT> *Node = getNode(BB); 00528 assert (Node && "Removing node that isn't in dominator tree."); 00529 assert (Node->getChildren().empty() && "Node is not a leaf node."); 00530 00531 // Remove node from immediate dominator's children list. 00532 DomTreeNodeBase<NodeT> *IDom = Node->getIDom(); 00533 if (IDom) { 00534 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I = 00535 std::find(IDom->Children.begin(), IDom->Children.end(), Node); 00536 assert(I != IDom->Children.end() && 00537 "Not in immediate dominator children set!"); 00538 // I am no longer your child... 00539 IDom->Children.erase(I); 00540 } 00541 00542 DomTreeNodes.erase(BB); 00543 delete Node; 00544 } 00545 00546 /// removeNode - Removes a node from the dominator tree. Block must not 00547 /// dominate any other blocks. Invalidates any node pointing to removed 00548 /// block. 00549 void removeNode(NodeT *BB) { 00550 assert(getNode(BB) && "Removing node that isn't in dominator tree."); 00551 DomTreeNodes.erase(BB); 00552 } 00553 00554 /// splitBlock - BB is split and now it has one successor. Update dominator 00555 /// tree to reflect this change. 00556 void splitBlock(NodeT* NewBB) { 00557 if (this->IsPostDominators) 00558 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB); 00559 else 00560 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB); 00561 } 00562 00563 /// print - Convert to human readable form 00564 /// 00565 virtual void print(std::ostream &o, const Module* ) const { 00566 o << "=============================--------------------------------\n"; 00567 if (this->isPostDominator()) 00568 o << "Inorder PostDominator Tree: "; 00569 else 00570 o << "Inorder Dominator Tree: "; 00571 if (this->DFSInfoValid) 00572 o << "DFSNumbers invalid: " << SlowQueries << " slow queries."; 00573 o << "\n"; 00574 00575 PrintDomTree<NodeT>(getRootNode(), o, 1); 00576 } 00577 00578 void print(std::ostream *OS, const Module* M = 0) const { 00579 if (OS) print(*OS, M); 00580 } 00581 00582 virtual void dump() { 00583 print(llvm::cerr); 00584 } 00585 00586 protected: 00587 template<class GraphT> 00588 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT, 00589 typename GraphT::NodeType* VIn); 00590 00591 template<class GraphT> 00592 friend typename GraphT::NodeType* Eval( 00593 DominatorTreeBase<typename GraphT::NodeType>& DT, 00594 typename GraphT::NodeType* V); 00595 00596 template<class GraphT> 00597 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT, 00598 unsigned DFSNumV, typename GraphT::NodeType* W, 00599 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo); 00600 00601 template<class GraphT> 00602 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT, 00603 typename GraphT::NodeType* V, 00604 unsigned N); 00605 00606 template<class FuncT, class N> 00607 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT, 00608 FuncT& F); 00609 00610 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking 00611 /// dominator tree in dfs order. 00612 void updateDFSNumbers() { 00613 unsigned DFSNum = 0; 00614 00615 SmallVector<std::pair<DomTreeNodeBase<NodeT>*, 00616 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack; 00617 00618 for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) { 00619 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]); 00620 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin())); 00621 ThisRoot->DFSNumIn = DFSNum++; 00622 00623 while (!WorkStack.empty()) { 00624 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first; 00625 typename DomTreeNodeBase<NodeT>::iterator ChildIt = 00626 WorkStack.back().second; 00627 00628 // If we visited all of the children of this node, "recurse" back up the 00629 // stack setting the DFOutNum. 00630 if (ChildIt == Node->end()) { 00631 Node->DFSNumOut = DFSNum++; 00632 WorkStack.pop_back(); 00633 } else { 00634 // Otherwise, recursively visit this child. 00635 DomTreeNodeBase<NodeT> *Child = *ChildIt; 00636 ++WorkStack.back().second; 00637 00638 WorkStack.push_back(std::make_pair(Child, Child->begin())); 00639 Child->DFSNumIn = DFSNum++; 00640 } 00641 } 00642 } 00643 00644 SlowQueries = 0; 00645 DFSInfoValid = true; 00646 } 00647 00648 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) { 00649 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB]) 00650 return BBNode; 00651 00652 // Haven't calculated this node yet? Get or calculate the node for the 00653 // immediate dominator. 00654 NodeT *IDom = getIDom(BB); 00655 00656 assert(IDom || this->DomTreeNodes[NULL]); 00657 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom); 00658 00659 // Add a new tree node for this BasicBlock, and link it as a child of 00660 // IDomNode 00661 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode); 00662 return this->DomTreeNodes[BB] = IDomNode->addChild(C); 00663 } 00664 00665 inline NodeT *getIDom(NodeT *BB) const { 00666 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB); 00667 return I != IDoms.end() ? I->second : 0; 00668 } 00669 00670 inline void addRoot(NodeT* BB) { 00671 this->Roots.push_back(BB); 00672 } 00673 00674 public: 00675 /// recalculate - compute a dominator tree for the given function 00676 template<class FT> 00677 void recalculate(FT& F) { 00678 if (!this->IsPostDominators) { 00679 reset(); 00680 00681 // Initialize roots 00682 this->Roots.push_back(&F.front()); 00683 this->IDoms[&F.front()] = 0; 00684 this->DomTreeNodes[&F.front()] = 0; 00685 this->Vertex.push_back(0); 00686 00687 Calculate<FT, NodeT*>(*this, F); 00688 00689 updateDFSNumbers(); 00690 } else { 00691 reset(); // Reset from the last time we were run... 00692 00693 // Initialize the roots list 00694 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) { 00695 if (std::distance(GraphTraits<FT*>::child_begin(I), 00696 GraphTraits<FT*>::child_end(I)) == 0) 00697 addRoot(I); 00698 00699 // Prepopulate maps so that we don't get iterator invalidation issues later. 00700 this->IDoms[I] = 0; 00701 this->DomTreeNodes[I] = 0; 00702 } 00703 00704 this->Vertex.push_back(0); 00705 00706 Calculate<FT, Inverse<NodeT*> >(*this, F); 00707 } 00708 } 00709 }; 00710 00711 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>); 00712 00713 //===------------------------------------- 00714 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to 00715 /// compute a normal dominator tree. 00716 /// 00717 class DominatorTree : public FunctionPass { 00718 public: 00719 static char ID; // Pass ID, replacement for typeid 00720 DominatorTreeBase<BasicBlock>* DT; 00721 00722 DominatorTree() : FunctionPass(&ID) { 00723 DT = new DominatorTreeBase<BasicBlock>(false); 00724 } 00725 00726 ~DominatorTree() { 00727 DT->releaseMemory(); 00728 delete DT; 00729 } 00730 00731 DominatorTreeBase<BasicBlock>& getBase() { return *DT; } 00732 00733 /// getRoots - Return the root blocks of the current CFG. This may include 00734 /// multiple blocks if we are computing post dominators. For forward 00735 /// dominators, this will always be a single block (the entry node). 00736 /// 00737 inline const std::vector<BasicBlock*> &getRoots() const { 00738 return DT->getRoots(); 00739 } 00740 00741 inline BasicBlock *getRoot() const { 00742 return DT->getRoot(); 00743 } 00744 00745 inline DomTreeNode *getRootNode() const { 00746 return DT->getRootNode(); 00747 } 00748 00749 /// compare - Return false if the other dominator tree matches this 00750 /// dominator tree. Otherwise return true. 00751 inline bool compare(DominatorTree &Other) const { 00752 DomTreeNode *R = getRootNode(); 00753 DomTreeNode *OtherR = Other.getRootNode(); 00754 00755 if (!R || !OtherR || R->getBlock() != OtherR->getBlock()) 00756 return true; 00757 00758 if (DT->compare(Other.getBase())) 00759 return true; 00760 00761 return false; 00762 } 00763 00764 virtual bool runOnFunction(Function &F); 00765 00766 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00767 AU.setPreservesAll(); 00768 } 00769 00770 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const { 00771 return DT->dominates(A, B); 00772 } 00773 00774 inline bool dominates(BasicBlock* A, BasicBlock* B) const { 00775 return DT->dominates(A, B); 00776 } 00777 00778 // dominates - Return true if A dominates B. This performs the 00779 // special checks necessary if A and B are in the same basic block. 00780 bool dominates(Instruction *A, Instruction *B) const { 00781 BasicBlock *BBA = A->getParent(), *BBB = B->getParent(); 00782 if (BBA != BBB) return DT->dominates(BBA, BBB); 00783 00784 // It is not possible to determine dominance between two PHI nodes 00785 // based on their ordering. 00786 if (isa<PHINode>(A) && isa<PHINode>(B)) 00787 return false; 00788 00789 // Loop through the basic block until we find A or B. 00790 BasicBlock::iterator I = BBA->begin(); 00791 for (; &*I != A && &*I != B; ++I) /*empty*/; 00792 00793 //if(!DT.IsPostDominators) { 00794 // A dominates B if it is found first in the basic block. 00795 return &*I == A; 00796 //} else { 00797 // // A post-dominates B if B is found first in the basic block. 00798 // return &*I == B; 00799 //} 00800 } 00801 00802 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const { 00803 return DT->properlyDominates(A, B); 00804 } 00805 00806 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const { 00807 return DT->properlyDominates(A, B); 00808 } 00809 00810 /// findNearestCommonDominator - Find nearest common dominator basic block 00811 /// for basic block A and B. If there is no such block then return NULL. 00812 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) { 00813 return DT->findNearestCommonDominator(A, B); 00814 } 00815 00816 inline DomTreeNode *operator[](BasicBlock *BB) const { 00817 return DT->getNode(BB); 00818 } 00819 00820 /// getNode - return the (Post)DominatorTree node for the specified basic 00821 /// block. This is the same as using operator[] on this class. 00822 /// 00823 inline DomTreeNode *getNode(BasicBlock *BB) const { 00824 return DT->getNode(BB); 00825 } 00826 00827 /// addNewBlock - Add a new node to the dominator tree information. This 00828 /// creates a new node as a child of DomBB dominator node,linking it into 00829 /// the children list of the immediate dominator. 00830 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) { 00831 return DT->addNewBlock(BB, DomBB); 00832 } 00833 00834 /// changeImmediateDominator - This method is used to update the dominator 00835 /// tree information when a node's immediate dominator changes. 00836 /// 00837 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) { 00838 DT->changeImmediateDominator(N, NewIDom); 00839 } 00840 00841 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) { 00842 DT->changeImmediateDominator(N, NewIDom); 00843 } 00844 00845 /// eraseNode - Removes a node from the dominator tree. Block must not 00846 /// domiante any other blocks. Removes node from its immediate dominator's 00847 /// children list. Deletes dominator node associated with basic block BB. 00848 inline void eraseNode(BasicBlock *BB) { 00849 DT->eraseNode(BB); 00850 } 00851 00852 /// splitBlock - BB is split and now it has one successor. Update dominator 00853 /// tree to reflect this change. 00854 inline void splitBlock(BasicBlock* NewBB) { 00855 DT->splitBlock(NewBB); 00856 } 00857 00858 bool isReachableFromEntry(BasicBlock* A) { 00859 return DT->isReachableFromEntry(A); 00860 } 00861 00862 00863 virtual void releaseMemory() { 00864 DT->releaseMemory(); 00865 } 00866 00867 virtual void print(std::ostream &OS, const Module* M= 0) const { 00868 DT->print(OS, M); 00869 } 00870 }; 00871 00872 //===------------------------------------- 00873 /// DominatorTree GraphTraits specialization so the DominatorTree can be 00874 /// iterable by generic graph iterators. 00875 /// 00876 template <> struct GraphTraits<DomTreeNode *> { 00877 typedef DomTreeNode NodeType; 00878 typedef NodeType::iterator ChildIteratorType; 00879 00880 static NodeType *getEntryNode(NodeType *N) { 00881 return N; 00882 } 00883 static inline ChildIteratorType child_begin(NodeType* N) { 00884 return N->begin(); 00885 } 00886 static inline ChildIteratorType child_end(NodeType* N) { 00887 return N->end(); 00888 } 00889 }; 00890 00891 template <> struct GraphTraits<DominatorTree*> 00892 : public GraphTraits<DomTreeNode *> { 00893 static NodeType *getEntryNode(DominatorTree *DT) { 00894 return DT->getRootNode(); 00895 } 00896 }; 00897 00898 00899 //===----------------------------------------------------------------------===// 00900 /// DominanceFrontierBase - Common base class for computing forward and inverse 00901 /// dominance frontiers for a function. 00902 /// 00903 class DominanceFrontierBase : public FunctionPass { 00904 public: 00905 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb 00906 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map 00907 protected: 00908 DomSetMapType Frontiers; 00909 std::vector<BasicBlock*> Roots; 00910 const bool IsPostDominators; 00911 00912 public: 00913 DominanceFrontierBase(void *ID, bool isPostDom) 00914 : FunctionPass(ID), IsPostDominators(isPostDom) {} 00915 00916 /// getRoots - Return the root blocks of the current CFG. This may include 00917 /// multiple blocks if we are computing post dominators. For forward 00918 /// dominators, this will always be a single block (the entry node). 00919 /// 00920 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; } 00921 00922 /// isPostDominator - Returns true if analysis based of postdoms 00923 /// 00924 bool isPostDominator() const { return IsPostDominators; } 00925 00926 virtual void releaseMemory() { Frontiers.clear(); } 00927 00928 // Accessor interface: 00929 typedef DomSetMapType::iterator iterator; 00930 typedef DomSetMapType::const_iterator const_iterator; 00931 iterator begin() { return Frontiers.begin(); } 00932 const_iterator begin() const { return Frontiers.begin(); } 00933 iterator end() { return Frontiers.end(); } 00934 const_iterator end() const { return Frontiers.end(); } 00935 iterator find(BasicBlock *B) { return Frontiers.find(B); } 00936 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); } 00937 00938 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) { 00939 assert(find(BB) == end() && "Block already in DominanceFrontier!"); 00940 Frontiers.insert(std::make_pair(BB, frontier)); 00941 } 00942 00943 /// removeBlock - Remove basic block BB's frontier. 00944 void removeBlock(BasicBlock *BB) { 00945 assert(find(BB) != end() && "Block is not in DominanceFrontier!"); 00946 for (iterator I = begin(), E = end(); I != E; ++I) 00947 I->second.erase(BB); 00948 Frontiers.erase(BB); 00949 } 00950 00951 void addToFrontier(iterator I, BasicBlock *Node) { 00952 assert(I != end() && "BB is not in DominanceFrontier!"); 00953 I->second.insert(Node); 00954 } 00955 00956 void removeFromFrontier(iterator I, BasicBlock *Node) { 00957 assert(I != end() && "BB is not in DominanceFrontier!"); 00958 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB"); 00959 I->second.erase(Node); 00960 } 00961 00962 /// compareDomSet - Return false if two domsets match. Otherwise 00963 /// return true; 00964 bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const { 00965 std::set<BasicBlock *> tmpSet; 00966 for (DomSetType::const_iterator I = DS2.begin(), 00967 E = DS2.end(); I != E; ++I) 00968 tmpSet.insert(*I); 00969 00970 for (DomSetType::const_iterator I = DS1.begin(), 00971 E = DS1.end(); I != E; ++I) { 00972 BasicBlock *Node = *I; 00973 00974 if (tmpSet.erase(Node) == 0) 00975 // Node is in DS1 but not in DS2. 00976 return true; 00977 } 00978 00979 if(!tmpSet.empty()) 00980 // There are nodes that are in DS2 but not in DS1. 00981 return true; 00982 00983 // DS1 and DS2 matches. 00984 return false; 00985 } 00986 00987 /// compare - Return true if the other dominance frontier base matches 00988 /// this dominance frontier base. Otherwise return false. 00989 bool compare(DominanceFrontierBase &Other) const { 00990 DomSetMapType tmpFrontiers; 00991 for (DomSetMapType::const_iterator I = Other.begin(), 00992 E = Other.end(); I != E; ++I) 00993 tmpFrontiers.insert(std::make_pair(I->first, I->second)); 00994 00995 for (DomSetMapType::iterator I = tmpFrontiers.begin(), 00996 E = tmpFrontiers.end(); I != E; ++I) { 00997 BasicBlock *Node = I->first; 00998 const_iterator DFI = find(Node); 00999 if (DFI == end()) 01000 return true; 01001 01002 if (compareDomSet(I->second, DFI->second)) 01003 return true; 01004 01005 tmpFrontiers.erase(Node); 01006 } 01007 01008 if (!tmpFrontiers.empty()) 01009 return true; 01010 01011 return false; 01012 } 01013 01014 /// print - Convert to human readable form 01015 /// 01016 virtual void print(std::ostream &OS, const Module* = 0) const; 01017 void print(std::ostream *OS, const Module* M = 0) const { 01018 if (OS) print(*OS, M); 01019 } 01020 virtual void dump(); 01021 }; 01022 01023 01024 //===------------------------------------- 01025 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is 01026 /// used to compute a forward dominator frontiers. 01027 /// 01028 class DominanceFrontier : public DominanceFrontierBase { 01029 public: 01030 static char ID; // Pass ID, replacement for typeid 01031 DominanceFrontier() : 01032 DominanceFrontierBase(&ID, false) {} 01033 01034 BasicBlock *getRoot() const { 01035 assert(Roots.size() == 1 && "Should always have entry node!"); 01036 return Roots[0]; 01037 } 01038 01039 virtual bool runOnFunction(Function &) { 01040 Frontiers.clear(); 01041 DominatorTree &DT = getAnalysis<DominatorTree>(); 01042 Roots = DT.getRoots(); 01043 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!"); 01044 calculate(DT, DT[Roots[0]]); 01045 return false; 01046 } 01047 01048 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 01049 AU.setPreservesAll(); 01050 AU.addRequired<DominatorTree>(); 01051 } 01052 01053 /// splitBlock - BB is split and now it has one successor. Update dominance 01054 /// frontier to reflect this change. 01055 void splitBlock(BasicBlock *BB); 01056 01057 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier 01058 /// to reflect this change. 01059 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB, 01060 DominatorTree *DT) { 01061 // NewBB is now dominating BB. Which means BB's dominance 01062 // frontier is now part of NewBB's dominance frontier. However, BB 01063 // itself is not member of NewBB's dominance frontier. 01064 DominanceFrontier::iterator NewDFI = find(NewBB); 01065 DominanceFrontier::iterator DFI = find(BB); 01066 // If BB was an entry block then its frontier is empty. 01067 if (DFI == end()) 01068 return; 01069 DominanceFrontier::DomSetType BBSet = DFI->second; 01070 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(), 01071 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) { 01072 BasicBlock *DFMember = *BBSetI; 01073 // Insert only if NewBB dominates DFMember. 01074 if (!DT->dominates(NewBB, DFMember)) 01075 NewDFI->second.insert(DFMember); 01076 } 01077 NewDFI->second.erase(BB); 01078 } 01079 01080 const DomSetType &calculate(const DominatorTree &DT, 01081 const DomTreeNode *Node); 01082 }; 01083 01084 01085 } // End llvm namespace 01086 01087 #endif