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