1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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"
42 //===----------------------------------------------------------------------===//
43 /// DominatorBase - Base class that other, more interesting dominator analyses
46 template <class NodeT>
49 std::vector<NodeT*> Roots;
50 const bool IsPostDominators;
51 inline explicit DominatorBase(bool isPostDom) :
52 Roots(), IsPostDominators(isPostDom) {}
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).
59 inline const std::vector<NodeT*> &getRoots() const { return Roots; }
61 /// isPostDominator - Returns true if analysis based of postdoms
63 bool isPostDominator() const { return IsPostDominators; }
67 //===----------------------------------------------------------------------===//
68 // DomTreeNode - Dominator Tree Node
69 template<class NodeT> class DominatorTreeBase;
70 struct PostDominatorTree;
71 class MachineBasicBlock;
73 template <class NodeT>
74 class DomTreeNodeBase {
76 DomTreeNodeBase<NodeT> *IDom;
77 std::vector<DomTreeNodeBase<NodeT> *> Children;
78 int DFSNumIn, DFSNumOut;
80 template<class N> friend class DominatorTreeBase;
81 friend struct PostDominatorTree;
83 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
84 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
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(); }
92 NodeT *getBlock() const { return TheBB; }
93 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
94 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
98 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
99 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
101 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
102 Children.push_back(C);
106 size_t getNumChildren() const {
107 return Children.size();
110 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
111 assert(IDom && "No immediate dominator?");
112 if (IDom != NewIDom) {
113 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
114 std::find(IDom->Children.begin(), IDom->Children.end(), this);
115 assert(I != IDom->Children.end() &&
116 "Not in immediate dominator children set!");
117 // I am no longer your child...
118 IDom->Children.erase(I);
120 // Switch to new dominator
122 IDom->Children.push_back(this);
126 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
128 unsigned getDFSNumIn() const { return DFSNumIn; }
129 unsigned getDFSNumOut() const { return DFSNumOut; }
131 // Return true if this node is dominated by other. Use this only if DFS info
133 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
134 return this->DFSNumIn >= other->DFSNumIn &&
135 this->DFSNumOut <= other->DFSNumOut;
139 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
140 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
142 template<class NodeT>
143 static std::ostream &operator<<(std::ostream &o,
144 const DomTreeNodeBase<NodeT> *Node) {
145 if (Node->getBlock())
146 WriteAsOperand(o, Node->getBlock(), false);
148 o << " <<exit node>>";
150 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
155 template<class NodeT>
156 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, std::ostream &o,
158 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
159 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
160 E = N->end(); I != E; ++I)
161 PrintDomTree<NodeT>(*I, o, Lev+1);
164 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
166 //===----------------------------------------------------------------------===//
167 /// DominatorTree - Calculate the immediate dominator tree for a function.
170 template<class FuncT, class N>
171 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
174 template<class NodeT>
175 class DominatorTreeBase : public DominatorBase<NodeT> {
177 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
178 DomTreeNodeMapType DomTreeNodes;
179 DomTreeNodeBase<NodeT> *RootNode;
182 unsigned int SlowQueries;
183 // Information record used during immediate dominators computation.
188 NodeT *Label, *Child;
189 unsigned Parent, Ancestor;
191 std::vector<NodeT*> Bucket;
193 InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
197 DenseMap<NodeT*, NodeT*> IDoms;
199 // Vertex - Map the DFS number to the BasicBlock*
200 std::vector<NodeT*> Vertex;
202 // Info - Collection of information used during the computation of idoms.
203 DenseMap<NodeT*, InfoRec> Info;
206 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
207 E = DomTreeNodes.end(); I != E; ++I)
209 DomTreeNodes.clear();
216 // NewBB is split and now it has one successor. Update dominator tree to
217 // reflect this change.
218 template<class N, class GraphT>
219 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
220 typename GraphT::NodeType* NewBB) {
221 assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
222 && "NewBB should have a single successor!");
223 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
225 std::vector<typename GraphT::NodeType*> PredBlocks;
226 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
227 GraphTraits<Inverse<N> >::child_begin(NewBB),
228 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
229 PredBlocks.push_back(*PI);
231 assert(!PredBlocks.empty() && "No predblocks??");
233 // The newly inserted basic block will dominate existing basic blocks iff the
234 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
235 // the non-pred blocks, then they all must be the same block!
237 bool NewBBDominatesNewBBSucc = true;
239 typename GraphT::NodeType* OnePred = PredBlocks[0];
240 size_t i = 1, e = PredBlocks.size();
241 for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
242 assert(i != e && "Didn't find reachable pred?");
243 OnePred = PredBlocks[i];
247 if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
248 NewBBDominatesNewBBSucc = false;
252 if (NewBBDominatesNewBBSucc)
253 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
254 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
255 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
256 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
257 NewBBDominatesNewBBSucc = false;
262 // The other scenario where the new block can dominate its successors are when
263 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
265 if (!NewBBDominatesNewBBSucc) {
266 NewBBDominatesNewBBSucc = true;
267 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
268 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
269 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
270 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
271 NewBBDominatesNewBBSucc = false;
276 // Find NewBB's immediate dominator and create new dominator tree node for
278 NodeT *NewBBIDom = 0;
280 for (i = 0; i < PredBlocks.size(); ++i)
281 if (DT.isReachableFromEntry(PredBlocks[i])) {
282 NewBBIDom = PredBlocks[i];
285 assert(i != PredBlocks.size() && "No reachable preds?");
286 for (i = i + 1; i < PredBlocks.size(); ++i) {
287 if (DT.isReachableFromEntry(PredBlocks[i]))
288 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
290 assert(NewBBIDom && "No immediate dominator found??");
292 // Create the new dominator tree node... and set the idom of NewBB.
293 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
295 // If NewBB strictly dominates other blocks, then it is now the immediate
296 // dominator of NewBBSucc. Update the dominator tree as appropriate.
297 if (NewBBDominatesNewBBSucc) {
298 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
299 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
304 explicit DominatorTreeBase(bool isPostDom)
305 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
306 virtual ~DominatorTreeBase() { reset(); }
308 // FIXME: Should remove this
309 virtual bool runOnFunction(Function &F) { return false; }
311 virtual void releaseMemory() { reset(); }
313 /// getNode - return the (Post)DominatorTree node for the specified basic
314 /// block. This is the same as using operator[] on this class.
316 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
317 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
318 return I != DomTreeNodes.end() ? I->second : 0;
321 /// getRootNode - This returns the entry node for the CFG of the function. If
322 /// this tree represents the post-dominance relations for a function, however,
323 /// this root may be a node with the block == NULL. This is the case when
324 /// there are multiple exit nodes from a particular function. Consumers of
325 /// post-dominance information must be capable of dealing with this
328 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
329 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
331 /// properlyDominates - Returns true iff this dominates N and this != N.
332 /// Note that this is not a constant time operation!
334 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
335 DomTreeNodeBase<NodeT> *B) const {
336 if (A == 0 || B == 0) return false;
337 return dominatedBySlowTreeWalk(A, B);
340 inline bool properlyDominates(NodeT *A, NodeT *B) {
341 return properlyDominates(getNode(A), getNode(B));
344 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
345 const DomTreeNodeBase<NodeT> *B) const {
346 const DomTreeNodeBase<NodeT> *IDom;
347 if (A == 0 || B == 0) return false;
348 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
349 B = IDom; // Walk up the tree
354 /// isReachableFromEntry - Return true if A is dominated by the entry
355 /// block of the function containing it.
356 bool isReachableFromEntry(NodeT* A) {
357 assert (!this->isPostDominator()
358 && "This is not implemented for post dominators");
359 return dominates(&A->getParent()->front(), A);
362 /// dominates - Returns true iff A dominates B. Note that this is not a
363 /// constant time operation!
365 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
366 DomTreeNodeBase<NodeT> *B) {
368 return true; // A node trivially dominates itself.
370 if (A == 0 || B == 0)
374 return B->DominatedBy(A);
376 // If we end up with too many slow queries, just update the
377 // DFS numbers on the theory that we are going to keep querying.
379 if (SlowQueries > 32) {
381 return B->DominatedBy(A);
384 return dominatedBySlowTreeWalk(A, B);
387 inline bool dominates(NodeT *A, NodeT *B) {
391 return dominates(getNode(A), getNode(B));
394 NodeT *getRoot() const {
395 assert(this->Roots.size() == 1 && "Should always have entry node!");
396 return this->Roots[0];
399 /// findNearestCommonDominator - Find nearest common dominator basic block
400 /// for basic block A and B. If there is no such block then return NULL.
401 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
403 assert (!this->isPostDominator()
404 && "This is not implemented for post dominators");
405 assert (A->getParent() == B->getParent()
406 && "Two blocks are not in same function");
408 // If either A or B is a entry block then it is nearest common dominator.
409 NodeT &Entry = A->getParent()->front();
410 if (A == &Entry || B == &Entry)
413 // If B dominates A then B is nearest common dominator.
417 // If A dominates B then A is nearest common dominator.
421 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
422 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
424 // Collect NodeA dominators set.
425 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
426 NodeADoms.insert(NodeA);
427 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
429 NodeADoms.insert(IDomA);
430 IDomA = IDomA->getIDom();
433 // Walk NodeB immediate dominators chain and find common dominator node.
434 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
436 if (NodeADoms.count(IDomB) != 0)
437 return IDomB->getBlock();
439 IDomB = IDomB->getIDom();
445 //===--------------------------------------------------------------------===//
446 // API to update (Post)DominatorTree information based on modifications to
449 /// addNewBlock - Add a new node to the dominator tree information. This
450 /// creates a new node as a child of DomBB dominator node,linking it into
451 /// the children list of the immediate dominator.
452 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
453 assert(getNode(BB) == 0 && "Block already in dominator tree!");
454 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
455 assert(IDomNode && "Not immediate dominator specified for block!");
456 DFSInfoValid = false;
457 return DomTreeNodes[BB] =
458 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
461 /// changeImmediateDominator - This method is used to update the dominator
462 /// tree information when a node's immediate dominator changes.
464 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
465 DomTreeNodeBase<NodeT> *NewIDom) {
466 assert(N && NewIDom && "Cannot change null node pointers!");
467 DFSInfoValid = false;
471 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
472 changeImmediateDominator(getNode(BB), getNode(NewBB));
475 /// eraseNode - Removes a node from the dominator tree. Block must not
476 /// domiante any other blocks. Removes node from its immediate dominator's
477 /// children list. Deletes dominator node associated with basic block BB.
478 void eraseNode(NodeT *BB) {
479 DomTreeNodeBase<NodeT> *Node = getNode(BB);
480 assert (Node && "Removing node that isn't in dominator tree.");
481 assert (Node->getChildren().empty() && "Node is not a leaf node.");
483 // Remove node from immediate dominator's children list.
484 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
486 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
487 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
488 assert(I != IDom->Children.end() &&
489 "Not in immediate dominator children set!");
490 // I am no longer your child...
491 IDom->Children.erase(I);
494 DomTreeNodes.erase(BB);
498 /// removeNode - Removes a node from the dominator tree. Block must not
499 /// dominate any other blocks. Invalidates any node pointing to removed
501 void removeNode(NodeT *BB) {
502 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
503 DomTreeNodes.erase(BB);
506 /// splitBlock - BB is split and now it has one successor. Update dominator
507 /// tree to reflect this change.
508 void splitBlock(NodeT* NewBB) {
509 if (this->IsPostDominators)
510 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
512 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
515 /// print - Convert to human readable form
517 virtual void print(std::ostream &o, const Module* ) const {
518 o << "=============================--------------------------------\n";
519 if (this->isPostDominator())
520 o << "Inorder PostDominator Tree: ";
522 o << "Inorder Dominator Tree: ";
523 if (this->DFSInfoValid)
524 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
527 PrintDomTree<NodeT>(getRootNode(), o, 1);
530 void print(std::ostream *OS, const Module* M = 0) const {
531 if (OS) print(*OS, M);
534 virtual void dump() {
539 template<class GraphT>
540 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
541 typename GraphT::NodeType* VIn);
543 template<class GraphT>
544 friend typename GraphT::NodeType* Eval(
545 DominatorTreeBase<typename GraphT::NodeType>& DT,
546 typename GraphT::NodeType* V);
548 template<class GraphT>
549 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
550 unsigned DFSNumV, typename GraphT::NodeType* W,
551 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
553 template<class GraphT>
554 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
555 typename GraphT::NodeType* V,
558 template<class FuncT, class N>
559 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
562 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
563 /// dominator tree in dfs order.
564 void updateDFSNumbers() {
567 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
568 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
570 for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
571 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
572 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
573 ThisRoot->DFSNumIn = DFSNum++;
575 while (!WorkStack.empty()) {
576 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
577 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
578 WorkStack.back().second;
580 // If we visited all of the children of this node, "recurse" back up the
581 // stack setting the DFOutNum.
582 if (ChildIt == Node->end()) {
583 Node->DFSNumOut = DFSNum++;
584 WorkStack.pop_back();
586 // Otherwise, recursively visit this child.
587 DomTreeNodeBase<NodeT> *Child = *ChildIt;
588 ++WorkStack.back().second;
590 WorkStack.push_back(std::make_pair(Child, Child->begin()));
591 Child->DFSNumIn = DFSNum++;
600 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
601 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
604 // Haven't calculated this node yet? Get or calculate the node for the
605 // immediate dominator.
606 NodeT *IDom = getIDom(BB);
608 assert(IDom || this->DomTreeNodes[NULL]);
609 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
611 // Add a new tree node for this BasicBlock, and link it as a child of
613 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
614 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
617 inline NodeT *getIDom(NodeT *BB) const {
618 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
619 return I != IDoms.end() ? I->second : 0;
622 inline void addRoot(NodeT* BB) {
623 this->Roots.push_back(BB);
627 /// recalculate - compute a dominator tree for the given function
629 void recalculate(FT& F) {
630 if (!this->IsPostDominators) {
634 this->Roots.push_back(&F.front());
635 this->IDoms[&F.front()] = 0;
636 this->DomTreeNodes[&F.front()] = 0;
637 this->Vertex.push_back(0);
639 Calculate<FT, NodeT*>(*this, F);
643 reset(); // Reset from the last time we were run...
645 // Initialize the roots list
646 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
647 if (std::distance(GraphTraits<FT*>::child_begin(I),
648 GraphTraits<FT*>::child_end(I)) == 0)
651 // Prepopulate maps so that we don't get iterator invalidation issues later.
653 this->DomTreeNodes[I] = 0;
656 this->Vertex.push_back(0);
658 Calculate<FT, Inverse<NodeT*> >(*this, F);
663 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
665 //===-------------------------------------
666 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
667 /// compute a normal dominator tree.
669 class DominatorTree : public FunctionPass {
671 static char ID; // Pass ID, replacement for typeid
672 DominatorTreeBase<BasicBlock>* DT;
674 DominatorTree() : FunctionPass(intptr_t(&ID)) {
675 DT = new DominatorTreeBase<BasicBlock>(false);
683 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
685 /// getRoots - Return the root blocks of the current CFG. This may include
686 /// multiple blocks if we are computing post dominators. For forward
687 /// dominators, this will always be a single block (the entry node).
689 inline const std::vector<BasicBlock*> &getRoots() const {
690 return DT->getRoots();
693 inline BasicBlock *getRoot() const {
694 return DT->getRoot();
697 inline DomTreeNode *getRootNode() const {
698 return DT->getRootNode();
701 virtual bool runOnFunction(Function &F);
703 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
704 AU.setPreservesAll();
707 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
708 return DT->dominates(A, B);
711 inline bool dominates(BasicBlock* A, BasicBlock* B) const {
712 return DT->dominates(A, B);
715 // dominates - Return true if A dominates B. This performs the
716 // special checks necessary if A and B are in the same basic block.
717 bool dominates(Instruction *A, Instruction *B) const {
718 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
719 if (BBA != BBB) return DT->dominates(BBA, BBB);
721 // It is not possible to determine dominance between two PHI nodes
722 // based on their ordering.
723 if (isa<PHINode>(A) && isa<PHINode>(B))
726 // Loop through the basic block until we find A or B.
727 BasicBlock::iterator I = BBA->begin();
728 for (; &*I != A && &*I != B; ++I) /*empty*/;
730 //if(!DT.IsPostDominators) {
731 // A dominates B if it is found first in the basic block.
734 // // A post-dominates B if B is found first in the basic block.
739 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
740 return DT->properlyDominates(A, B);
743 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
744 return DT->properlyDominates(A, B);
747 /// findNearestCommonDominator - Find nearest common dominator basic block
748 /// for basic block A and B. If there is no such block then return NULL.
749 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
750 return DT->findNearestCommonDominator(A, B);
753 inline DomTreeNode *operator[](BasicBlock *BB) const {
754 return DT->getNode(BB);
757 /// getNode - return the (Post)DominatorTree node for the specified basic
758 /// block. This is the same as using operator[] on this class.
760 inline DomTreeNode *getNode(BasicBlock *BB) const {
761 return DT->getNode(BB);
764 /// addNewBlock - Add a new node to the dominator tree information. This
765 /// creates a new node as a child of DomBB dominator node,linking it into
766 /// the children list of the immediate dominator.
767 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
768 return DT->addNewBlock(BB, DomBB);
771 /// changeImmediateDominator - This method is used to update the dominator
772 /// tree information when a node's immediate dominator changes.
774 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
775 DT->changeImmediateDominator(N, NewIDom);
778 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
779 DT->changeImmediateDominator(N, NewIDom);
782 /// eraseNode - Removes a node from the dominator tree. Block must not
783 /// domiante any other blocks. Removes node from its immediate dominator's
784 /// children list. Deletes dominator node associated with basic block BB.
785 inline void eraseNode(BasicBlock *BB) {
789 /// splitBlock - BB is split and now it has one successor. Update dominator
790 /// tree to reflect this change.
791 inline void splitBlock(BasicBlock* NewBB) {
792 DT->splitBlock(NewBB);
796 virtual void releaseMemory() {
800 virtual void print(std::ostream &OS, const Module* M= 0) const {
805 //===-------------------------------------
806 /// DominatorTree GraphTraits specialization so the DominatorTree can be
807 /// iterable by generic graph iterators.
809 template <> struct GraphTraits<DomTreeNode *> {
810 typedef DomTreeNode NodeType;
811 typedef NodeType::iterator ChildIteratorType;
813 static NodeType *getEntryNode(NodeType *N) {
816 static inline ChildIteratorType child_begin(NodeType* N) {
819 static inline ChildIteratorType child_end(NodeType* N) {
824 template <> struct GraphTraits<DominatorTree*>
825 : public GraphTraits<DomTreeNode *> {
826 static NodeType *getEntryNode(DominatorTree *DT) {
827 return DT->getRootNode();
832 //===----------------------------------------------------------------------===//
833 /// DominanceFrontierBase - Common base class for computing forward and inverse
834 /// dominance frontiers for a function.
836 class DominanceFrontierBase : public FunctionPass {
838 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
839 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
841 DomSetMapType Frontiers;
842 std::vector<BasicBlock*> Roots;
843 const bool IsPostDominators;
846 DominanceFrontierBase(intptr_t ID, bool isPostDom)
847 : FunctionPass(ID), IsPostDominators(isPostDom) {}
849 /// getRoots - Return the root blocks of the current CFG. This may include
850 /// multiple blocks if we are computing post dominators. For forward
851 /// dominators, this will always be a single block (the entry node).
853 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
855 /// isPostDominator - Returns true if analysis based of postdoms
857 bool isPostDominator() const { return IsPostDominators; }
859 virtual void releaseMemory() { Frontiers.clear(); }
861 // Accessor interface:
862 typedef DomSetMapType::iterator iterator;
863 typedef DomSetMapType::const_iterator const_iterator;
864 iterator begin() { return Frontiers.begin(); }
865 const_iterator begin() const { return Frontiers.begin(); }
866 iterator end() { return Frontiers.end(); }
867 const_iterator end() const { return Frontiers.end(); }
868 iterator find(BasicBlock *B) { return Frontiers.find(B); }
869 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
871 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
872 assert(find(BB) == end() && "Block already in DominanceFrontier!");
873 Frontiers.insert(std::make_pair(BB, frontier));
876 /// removeBlock - Remove basic block BB's frontier.
877 void removeBlock(BasicBlock *BB) {
878 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
879 for (iterator I = begin(), E = end(); I != E; ++I)
884 void addToFrontier(iterator I, BasicBlock *Node) {
885 assert(I != end() && "BB is not in DominanceFrontier!");
886 I->second.insert(Node);
889 void removeFromFrontier(iterator I, BasicBlock *Node) {
890 assert(I != end() && "BB is not in DominanceFrontier!");
891 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
892 I->second.erase(Node);
895 /// print - Convert to human readable form
897 virtual void print(std::ostream &OS, const Module* = 0) const;
898 void print(std::ostream *OS, const Module* M = 0) const {
899 if (OS) print(*OS, M);
905 //===-------------------------------------
906 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
907 /// used to compute a forward dominator frontiers.
909 class DominanceFrontier : public DominanceFrontierBase {
911 static char ID; // Pass ID, replacement for typeid
912 DominanceFrontier() :
913 DominanceFrontierBase(intptr_t(&ID), false) {}
915 BasicBlock *getRoot() const {
916 assert(Roots.size() == 1 && "Should always have entry node!");
920 virtual bool runOnFunction(Function &) {
922 DominatorTree &DT = getAnalysis<DominatorTree>();
923 Roots = DT.getRoots();
924 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
925 calculate(DT, DT[Roots[0]]);
929 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
930 AU.setPreservesAll();
931 AU.addRequired<DominatorTree>();
934 /// splitBlock - BB is split and now it has one successor. Update dominance
935 /// frontier to reflect this change.
936 void splitBlock(BasicBlock *BB);
938 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
939 /// to reflect this change.
940 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
942 // NewBB is now dominating BB. Which means BB's dominance
943 // frontier is now part of NewBB's dominance frontier. However, BB
944 // itself is not member of NewBB's dominance frontier.
945 DominanceFrontier::iterator NewDFI = find(NewBB);
946 DominanceFrontier::iterator DFI = find(BB);
947 // If BB was an entry block then its frontier is empty.
950 DominanceFrontier::DomSetType BBSet = DFI->second;
951 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
952 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
953 BasicBlock *DFMember = *BBSetI;
954 // Insert only if NewBB dominates DFMember.
955 if (!DT->dominates(NewBB, DFMember))
956 NewDFI->second.insert(DFMember);
958 NewDFI->second.erase(BB);
962 const DomSetType &calculate(const DominatorTree &DT,
963 const DomTreeNode *Node);
967 } // End llvm namespace