1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ANALYSIS_DOMINATORS_H
22 #define LLVM_ANALYSIS_DOMINATORS_H
24 #include "llvm/Pass.h"
25 #include "llvm/BasicBlock.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instruction.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/GraphTraits.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/Assembly/Writer.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Compiler.h"
41 //===----------------------------------------------------------------------===//
42 /// DominatorBase - Base class that other, more interesting dominator analyses
45 template <class NodeT>
48 std::vector<NodeT*> Roots;
49 const bool IsPostDominators;
50 inline DominatorBase(bool isPostDom) :
51 Roots(), IsPostDominators(isPostDom) {}
54 /// getRoots - Return the root blocks of the current CFG. This may include
55 /// multiple blocks if we are computing post dominators. For forward
56 /// dominators, this will always be a single block (the entry node).
58 inline const std::vector<NodeT*> &getRoots() const { return Roots; }
60 /// isPostDominator - Returns true if analysis based of postdoms
62 bool isPostDominator() const { return IsPostDominators; }
66 //===----------------------------------------------------------------------===//
67 // DomTreeNode - Dominator Tree Node
68 template<class NodeT> class DominatorTreeBase;
69 struct PostDominatorTree;
70 class MachineBasicBlock;
72 template <class NodeT>
73 class DomTreeNodeBase {
75 DomTreeNodeBase<NodeT> *IDom;
76 std::vector<DomTreeNodeBase<NodeT> *> Children;
77 int DFSNumIn, DFSNumOut;
79 template<class N> friend class DominatorTreeBase;
80 friend struct PostDominatorTree;
82 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
83 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
86 iterator begin() { return Children.begin(); }
87 iterator end() { return Children.end(); }
88 const_iterator begin() const { return Children.begin(); }
89 const_iterator end() const { return Children.end(); }
91 NodeT *getBlock() const { return TheBB; }
92 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
93 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
97 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
98 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
100 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
101 Children.push_back(C);
105 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
106 assert(IDom && "No immediate dominator?");
107 if (IDom != NewIDom) {
108 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
109 std::find(IDom->Children.begin(), IDom->Children.end(), this);
110 assert(I != IDom->Children.end() &&
111 "Not in immediate dominator children set!");
112 // I am no longer your child...
113 IDom->Children.erase(I);
115 // Switch to new dominator
117 IDom->Children.push_back(this);
121 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
123 unsigned getDFSNumIn() const { return DFSNumIn; }
124 unsigned getDFSNumOut() const { return DFSNumOut; }
126 // Return true if this node is dominated by other. Use this only if DFS info
128 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
129 return this->DFSNumIn >= other->DFSNumIn &&
130 this->DFSNumOut <= other->DFSNumOut;
134 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
135 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
137 template<class NodeT>
138 static std::ostream &operator<<(std::ostream &o,
139 const DomTreeNodeBase<NodeT> *Node) {
140 if (Node->getBlock())
141 WriteAsOperand(o, Node->getBlock(), false);
143 o << " <<exit node>>";
145 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
150 template<class NodeT>
151 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, std::ostream &o,
153 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
154 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
155 E = N->end(); I != E; ++I)
156 PrintDomTree<NodeT>(*I, o, Lev+1);
159 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
161 //===----------------------------------------------------------------------===//
162 /// DominatorTree - Calculate the immediate dominator tree for a function.
165 template<class FuncT, class N>
166 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
169 template<class NodeT>
170 class DominatorTreeBase : public DominatorBase<NodeT> {
172 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
173 DomTreeNodeMapType DomTreeNodes;
174 DomTreeNodeBase<NodeT> *RootNode;
177 unsigned int SlowQueries;
178 // Information record used during immediate dominators computation.
182 NodeT *Label, *Parent, *Child, *Ancestor;
184 std::vector<NodeT*> Bucket;
186 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0) {}
189 DenseMap<NodeT*, NodeT*> IDoms;
191 // Vertex - Map the DFS number to the BasicBlock*
192 std::vector<NodeT*> Vertex;
194 // Info - Collection of information used during the computation of idoms.
195 DenseMap<NodeT*, InfoRec> Info;
198 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
199 E = DomTreeNodes.end(); I != E; ++I)
201 DomTreeNodes.clear();
208 // NewBB is split and now it has one successor. Update dominator tree to
209 // reflect this change.
210 template<class N, class GraphT>
211 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
212 typename GraphT::NodeType* NewBB) {
213 assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
214 && "NewBB should have a single successor!");
215 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
217 std::vector<typename GraphT::NodeType*> PredBlocks;
218 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
219 GraphTraits<Inverse<N> >::child_begin(NewBB),
220 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
221 PredBlocks.push_back(*PI);
223 assert(!PredBlocks.empty() && "No predblocks??");
225 // The newly inserted basic block will dominate existing basic blocks iff the
226 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
227 // the non-pred blocks, then they all must be the same block!
229 bool NewBBDominatesNewBBSucc = true;
231 typename GraphT::NodeType* OnePred = PredBlocks[0];
232 unsigned i = 1, e = PredBlocks.size();
233 for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
234 assert(i != e && "Didn't find reachable pred?");
235 OnePred = PredBlocks[i];
239 if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
240 NewBBDominatesNewBBSucc = false;
244 if (NewBBDominatesNewBBSucc)
245 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
246 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
247 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
248 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
249 NewBBDominatesNewBBSucc = false;
254 // The other scenario where the new block can dominate its successors are when
255 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
257 if (!NewBBDominatesNewBBSucc) {
258 NewBBDominatesNewBBSucc = true;
259 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
260 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
261 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
262 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
263 NewBBDominatesNewBBSucc = false;
268 // Find NewBB's immediate dominator and create new dominator tree node for
270 NodeT *NewBBIDom = 0;
272 for (i = 0; i < PredBlocks.size(); ++i)
273 if (DT.isReachableFromEntry(PredBlocks[i])) {
274 NewBBIDom = PredBlocks[i];
277 assert(i != PredBlocks.size() && "No reachable preds?");
278 for (i = i + 1; i < PredBlocks.size(); ++i) {
279 if (DT.isReachableFromEntry(PredBlocks[i]))
280 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
282 assert(NewBBIDom && "No immediate dominator found??");
284 // Create the new dominator tree node... and set the idom of NewBB.
285 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
287 // If NewBB strictly dominates other blocks, then it is now the immediate
288 // dominator of NewBBSucc. Update the dominator tree as appropriate.
289 if (NewBBDominatesNewBBSucc) {
290 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
291 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
296 DominatorTreeBase(bool isPostDom)
297 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
298 virtual ~DominatorTreeBase() { reset(); }
300 // FIXME: Should remove this
301 virtual bool runOnFunction(Function &F) { return false; }
303 virtual void releaseMemory() { reset(); }
305 /// getNode - return the (Post)DominatorTree node for the specified basic
306 /// block. This is the same as using operator[] on this class.
308 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
309 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
310 return I != DomTreeNodes.end() ? I->second : 0;
313 /// getRootNode - This returns the entry node for the CFG of the function. If
314 /// this tree represents the post-dominance relations for a function, however,
315 /// this root may be a node with the block == NULL. This is the case when
316 /// there are multiple exit nodes from a particular function. Consumers of
317 /// post-dominance information must be capable of dealing with this
320 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
321 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
323 /// properlyDominates - Returns true iff this dominates N and this != N.
324 /// Note that this is not a constant time operation!
326 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
327 DomTreeNodeBase<NodeT> *B) const {
328 if (A == 0 || B == 0) return false;
329 return dominatedBySlowTreeWalk(A, B);
332 inline bool properlyDominates(NodeT *A, NodeT *B) {
333 return properlyDominates(getNode(A), getNode(B));
336 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
337 const DomTreeNodeBase<NodeT> *B) const {
338 const DomTreeNodeBase<NodeT> *IDom;
339 if (A == 0 || B == 0) return false;
340 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
341 B = IDom; // Walk up the tree
346 /// isReachableFromEntry - Return true if A is dominated by the entry
347 /// block of the function containing it.
348 bool isReachableFromEntry(NodeT* A) {
349 assert (!this->isPostDominator()
350 && "This is not implemented for post dominators");
351 return dominates(&A->getParent()->front(), A);
354 /// dominates - Returns true iff A dominates B. Note that this is not a
355 /// constant time operation!
357 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
358 DomTreeNodeBase<NodeT> *B) {
360 return true; // A node trivially dominates itself.
362 if (A == 0 || B == 0)
366 return B->DominatedBy(A);
368 // If we end up with too many slow queries, just update the
369 // DFS numbers on the theory that we are going to keep querying.
371 if (SlowQueries > 32) {
373 return B->DominatedBy(A);
376 return dominatedBySlowTreeWalk(A, B);
379 inline bool dominates(NodeT *A, NodeT *B) {
383 return dominates(getNode(A), getNode(B));
386 NodeT *getRoot() const {
387 assert(this->Roots.size() == 1 && "Should always have entry node!");
388 return this->Roots[0];
391 /// findNearestCommonDominator - Find nearest common dominator basic block
392 /// for basic block A and B. If there is no such block then return NULL.
393 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
395 assert (!this->isPostDominator()
396 && "This is not implemented for post dominators");
397 assert (A->getParent() == B->getParent()
398 && "Two blocks are not in same function");
400 // If either A or B is a entry block then it is nearest common dominator.
401 NodeT &Entry = A->getParent()->front();
402 if (A == &Entry || B == &Entry)
405 // If B dominates A then B is nearest common dominator.
409 // If A dominates B then A is nearest common dominator.
413 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
414 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
416 // Collect NodeA dominators set.
417 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
418 NodeADoms.insert(NodeA);
419 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
421 NodeADoms.insert(IDomA);
422 IDomA = IDomA->getIDom();
425 // Walk NodeB immediate dominators chain and find common dominator node.
426 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
428 if (NodeADoms.count(IDomB) != 0)
429 return IDomB->getBlock();
431 IDomB = IDomB->getIDom();
437 //===--------------------------------------------------------------------===//
438 // API to update (Post)DominatorTree information based on modifications to
441 /// addNewBlock - Add a new node to the dominator tree information. This
442 /// creates a new node as a child of DomBB dominator node,linking it into
443 /// the children list of the immediate dominator.
444 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
445 assert(getNode(BB) == 0 && "Block already in dominator tree!");
446 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
447 assert(IDomNode && "Not immediate dominator specified for block!");
448 DFSInfoValid = false;
449 return DomTreeNodes[BB] =
450 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
453 /// changeImmediateDominator - This method is used to update the dominator
454 /// tree information when a node's immediate dominator changes.
456 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
457 DomTreeNodeBase<NodeT> *NewIDom) {
458 assert(N && NewIDom && "Cannot change null node pointers!");
459 DFSInfoValid = false;
463 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
464 changeImmediateDominator(getNode(BB), getNode(NewBB));
467 /// eraseNode - Removes a node from the dominator tree. Block must not
468 /// domiante any other blocks. Removes node from its immediate dominator's
469 /// children list. Deletes dominator node associated with basic block BB.
470 void eraseNode(NodeT *BB) {
471 DomTreeNodeBase<NodeT> *Node = getNode(BB);
472 assert (Node && "Removing node that isn't in dominator tree.");
473 assert (Node->getChildren().empty() && "Node is not a leaf node.");
475 // Remove node from immediate dominator's children list.
476 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
478 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
479 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
480 assert(I != IDom->Children.end() &&
481 "Not in immediate dominator children set!");
482 // I am no longer your child...
483 IDom->Children.erase(I);
486 DomTreeNodes.erase(BB);
490 /// removeNode - Removes a node from the dominator tree. Block must not
491 /// dominate any other blocks. Invalidates any node pointing to removed
493 void removeNode(NodeT *BB) {
494 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
495 DomTreeNodes.erase(BB);
498 /// splitBlock - BB is split and now it has one successor. Update dominator
499 /// tree to reflect this change.
500 void splitBlock(NodeT* NewBB) {
501 if (this->IsPostDominators)
502 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
504 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
507 /// print - Convert to human readable form
509 virtual void print(std::ostream &o, const Module* ) const {
510 o << "=============================--------------------------------\n";
511 o << "Inorder Dominator Tree: ";
512 if (this->DFSInfoValid)
513 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
516 PrintDomTree<NodeT>(getRootNode(), o, 1);
519 void print(std::ostream *OS, const Module* M = 0) const {
520 if (OS) print(*OS, M);
523 virtual void dump() {
528 template<class GraphT>
529 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
530 typename GraphT::NodeType* VIn);
532 template<class GraphT>
533 friend typename GraphT::NodeType* Eval(
534 DominatorTreeBase<typename GraphT::NodeType>& DT,
535 typename GraphT::NodeType* V);
537 template<class GraphT>
538 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
539 typename GraphT::NodeType* V,
540 typename GraphT::NodeType* W,
541 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
543 template<class GraphT>
544 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
545 typename GraphT::NodeType* V,
548 template<class FuncT, class N>
549 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
552 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
553 /// dominator tree in dfs order.
554 void updateDFSNumbers() {
557 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
558 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
560 for (unsigned i = 0, e = this->Roots.size(); i != e; ++i) {
561 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
562 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
563 ThisRoot->DFSNumIn = DFSNum++;
565 while (!WorkStack.empty()) {
566 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
567 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
568 WorkStack.back().second;
570 // If we visited all of the children of this node, "recurse" back up the
571 // stack setting the DFOutNum.
572 if (ChildIt == Node->end()) {
573 Node->DFSNumOut = DFSNum++;
574 WorkStack.pop_back();
576 // Otherwise, recursively visit this child.
577 DomTreeNodeBase<NodeT> *Child = *ChildIt;
578 ++WorkStack.back().second;
580 WorkStack.push_back(std::make_pair(Child, Child->begin()));
581 Child->DFSNumIn = DFSNum++;
590 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
591 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
594 // Haven't calculated this node yet? Get or calculate the node for the
595 // immediate dominator.
596 NodeT *IDom = getIDom(BB);
597 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
599 // Add a new tree node for this BasicBlock, and link it as a child of
601 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
602 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
605 inline NodeT *getIDom(NodeT *BB) const {
606 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
607 return I != IDoms.end() ? I->second : 0;
610 inline void addRoot(NodeT* BB) {
611 // Unreachable block is not a root node.
612 if (!isa<UnreachableInst>(&BB->back()))
613 this->Roots.push_back(BB);
617 /// recalculate - compute a dominator tree for the given function
619 void recalculate(FT& F) {
620 if (!this->IsPostDominators) {
624 this->Roots.push_back(&F.front());
625 this->IDoms[&F.front()] = 0;
626 this->DomTreeNodes[&F.front()] = 0;
627 this->Vertex.push_back(0);
629 Calculate<FT, NodeT*>(*this, F);
633 reset(); // Reset from the last time we were run...
635 // Initialize the roots list
636 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
637 if (std::distance(GraphTraits<FT*>::child_begin(I),
638 GraphTraits<FT*>::child_end(I)) == 0)
641 // Prepopulate maps so that we don't get iterator invalidation issues later.
643 this->DomTreeNodes[I] = 0;
646 this->Vertex.push_back(0);
648 Calculate<FT, Inverse<NodeT*> >(*this, F);
653 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
655 //===-------------------------------------
656 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
657 /// compute a normal dominator tree.
659 class DominatorTree : public FunctionPass {
661 static char ID; // Pass ID, replacement for typeid
662 DominatorTreeBase<BasicBlock>* DT;
664 DominatorTree() : FunctionPass(intptr_t(&ID)) {
665 DT = new DominatorTreeBase<BasicBlock>(false);
673 /// getRoots - Return the root blocks of the current CFG. This may include
674 /// multiple blocks if we are computing post dominators. For forward
675 /// dominators, this will always be a single block (the entry node).
677 inline const std::vector<BasicBlock*> &getRoots() const {
678 return DT->getRoots();
681 inline BasicBlock *getRoot() const {
682 return DT->getRoot();
685 inline DomTreeNode *getRootNode() const {
686 return DT->getRootNode();
689 virtual bool runOnFunction(Function &F);
691 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
692 AU.setPreservesAll();
695 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
696 return DT->dominates(A, B);
699 inline bool dominates(BasicBlock* A, BasicBlock* B) const {
700 return DT->dominates(A, B);
703 // dominates - Return true if A dominates B. This performs the
704 // special checks necessary if A and B are in the same basic block.
705 bool dominates(Instruction *A, Instruction *B) const {
706 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
707 if (BBA != BBB) return DT->dominates(BBA, BBB);
709 // It is not possible to determine dominance between two PHI nodes
710 // based on their ordering.
711 if (isa<PHINode>(A) && isa<PHINode>(B))
714 // Loop through the basic block until we find A or B.
715 BasicBlock::iterator I = BBA->begin();
716 for (; &*I != A && &*I != B; ++I) /*empty*/;
718 //if(!DT.IsPostDominators) {
719 // A dominates B if it is found first in the basic block.
722 // // A post-dominates B if B is found first in the basic block.
727 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
728 return DT->properlyDominates(A, B);
731 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
732 return DT->properlyDominates(A, B);
735 /// findNearestCommonDominator - Find nearest common dominator basic block
736 /// for basic block A and B. If there is no such block then return NULL.
737 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
738 return DT->findNearestCommonDominator(A, B);
741 inline DomTreeNode *operator[](BasicBlock *BB) const {
742 return DT->getNode(BB);
745 /// getNode - return the (Post)DominatorTree node for the specified basic
746 /// block. This is the same as using operator[] on this class.
748 inline DomTreeNode *getNode(BasicBlock *BB) const {
749 return DT->getNode(BB);
752 /// addNewBlock - Add a new node to the dominator tree information. This
753 /// creates a new node as a child of DomBB dominator node,linking it into
754 /// the children list of the immediate dominator.
755 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
756 return DT->addNewBlock(BB, DomBB);
759 /// changeImmediateDominator - This method is used to update the dominator
760 /// tree information when a node's immediate dominator changes.
762 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
763 DT->changeImmediateDominator(N, NewIDom);
766 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
767 DT->changeImmediateDominator(N, NewIDom);
770 /// eraseNode - Removes a node from the dominator tree. Block must not
771 /// domiante any other blocks. Removes node from its immediate dominator's
772 /// children list. Deletes dominator node associated with basic block BB.
773 inline void eraseNode(BasicBlock *BB) {
777 /// splitBlock - BB is split and now it has one successor. Update dominator
778 /// tree to reflect this change.
779 inline void splitBlock(BasicBlock* NewBB) {
780 DT->splitBlock(NewBB);
784 virtual void releaseMemory() {
788 virtual void print(std::ostream &OS, const Module* M= 0) const {
793 //===-------------------------------------
794 /// DominatorTree GraphTraits specialization so the DominatorTree can be
795 /// iterable by generic graph iterators.
797 template <> struct GraphTraits<DomTreeNode *> {
798 typedef DomTreeNode NodeType;
799 typedef NodeType::iterator ChildIteratorType;
801 static NodeType *getEntryNode(NodeType *N) {
804 static inline ChildIteratorType child_begin(NodeType* N) {
807 static inline ChildIteratorType child_end(NodeType* N) {
812 template <> struct GraphTraits<DominatorTree*>
813 : public GraphTraits<DomTreeNode *> {
814 static NodeType *getEntryNode(DominatorTree *DT) {
815 return DT->getRootNode();
820 //===----------------------------------------------------------------------===//
821 /// DominanceFrontierBase - Common base class for computing forward and inverse
822 /// dominance frontiers for a function.
824 class DominanceFrontierBase : public FunctionPass {
826 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
827 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
829 DomSetMapType Frontiers;
830 std::vector<BasicBlock*> Roots;
831 const bool IsPostDominators;
834 DominanceFrontierBase(intptr_t ID, bool isPostDom)
835 : FunctionPass(ID), IsPostDominators(isPostDom) {}
837 /// getRoots - Return the root blocks of the current CFG. This may include
838 /// multiple blocks if we are computing post dominators. For forward
839 /// dominators, this will always be a single block (the entry node).
841 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
843 /// isPostDominator - Returns true if analysis based of postdoms
845 bool isPostDominator() const { return IsPostDominators; }
847 virtual void releaseMemory() { Frontiers.clear(); }
849 // Accessor interface:
850 typedef DomSetMapType::iterator iterator;
851 typedef DomSetMapType::const_iterator const_iterator;
852 iterator begin() { return Frontiers.begin(); }
853 const_iterator begin() const { return Frontiers.begin(); }
854 iterator end() { return Frontiers.end(); }
855 const_iterator end() const { return Frontiers.end(); }
856 iterator find(BasicBlock *B) { return Frontiers.find(B); }
857 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
859 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
860 assert(find(BB) == end() && "Block already in DominanceFrontier!");
861 Frontiers.insert(std::make_pair(BB, frontier));
864 /// removeBlock - Remove basic block BB's frontier.
865 void removeBlock(BasicBlock *BB) {
866 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
867 for (iterator I = begin(), E = end(); I != E; ++I)
872 void addToFrontier(iterator I, BasicBlock *Node) {
873 assert(I != end() && "BB is not in DominanceFrontier!");
874 I->second.insert(Node);
877 void removeFromFrontier(iterator I, BasicBlock *Node) {
878 assert(I != end() && "BB is not in DominanceFrontier!");
879 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
880 I->second.erase(Node);
883 /// print - Convert to human readable form
885 virtual void print(std::ostream &OS, const Module* = 0) const;
886 void print(std::ostream *OS, const Module* M = 0) const {
887 if (OS) print(*OS, M);
893 //===-------------------------------------
894 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
895 /// used to compute a forward dominator frontiers.
897 class DominanceFrontier : public DominanceFrontierBase {
899 static char ID; // Pass ID, replacement for typeid
900 DominanceFrontier() :
901 DominanceFrontierBase(intptr_t(&ID), false) {}
903 BasicBlock *getRoot() const {
904 assert(Roots.size() == 1 && "Should always have entry node!");
908 virtual bool runOnFunction(Function &) {
910 DominatorTree &DT = getAnalysis<DominatorTree>();
911 Roots = DT.getRoots();
912 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
913 calculate(DT, DT[Roots[0]]);
917 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
918 AU.setPreservesAll();
919 AU.addRequired<DominatorTree>();
922 /// splitBlock - BB is split and now it has one successor. Update dominance
923 /// frontier to reflect this change.
924 void splitBlock(BasicBlock *BB);
926 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
927 /// to reflect this change.
928 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
930 // NewBB is now dominating BB. Which means BB's dominance
931 // frontier is now part of NewBB's dominance frontier. However, BB
932 // itself is not member of NewBB's dominance frontier.
933 DominanceFrontier::iterator NewDFI = find(NewBB);
934 DominanceFrontier::iterator DFI = find(BB);
935 DominanceFrontier::DomSetType BBSet = DFI->second;
936 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
937 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
938 BasicBlock *DFMember = *BBSetI;
939 // Insert only if NewBB dominates DFMember.
940 if (!DT->dominates(NewBB, DFMember))
941 NewDFI->second.insert(DFMember);
943 NewDFI->second.erase(BB);
947 const DomSetType &calculate(const DominatorTree &DT,
948 const DomTreeNode *Node);
952 } // End llvm namespace