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/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"
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 clearAllChildren() {
114 bool compare(DomTreeNodeBase<NodeT> *Other) {
115 if (getNumChildren() != Other->getNumChildren())
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);
124 for(iterator I = begin(), E = end(); I != E; ++I) {
125 NodeT *N = (*I)->getBlock();
126 if (OtherChildren.count(N) == 0)
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);
142 // Switch to new dominator
144 IDom->Children.push_back(this);
148 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
150 unsigned getDFSNumIn() const { return DFSNumIn; }
151 unsigned getDFSNumOut() const { return DFSNumOut; }
153 // Return true if this node is dominated by other. Use this only if DFS info
155 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
156 return this->DFSNumIn >= other->DFSNumIn &&
157 this->DFSNumOut <= other->DFSNumOut;
161 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
162 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
164 template<class NodeT>
165 static raw_ostream &operator<<(raw_ostream &o,
166 const DomTreeNodeBase<NodeT> *Node) {
167 if (Node->getBlock())
168 WriteAsOperand(o, Node->getBlock(), false);
170 o << " <<exit node>>";
172 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
177 template<class NodeT>
178 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
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);
186 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
188 //===----------------------------------------------------------------------===//
189 /// DominatorTree - Calculate the immediate dominator tree for a function.
192 template<class FuncT, class N>
193 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
196 template<class NodeT>
197 class DominatorTreeBase : public DominatorBase<NodeT> {
199 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
200 DomTreeNodeMapType DomTreeNodes;
201 DomTreeNodeBase<NodeT> *RootNode;
204 unsigned int SlowQueries;
205 // Information record used during immediate dominators computation.
210 NodeT *Label, *Child;
211 unsigned Parent, Ancestor;
213 std::vector<NodeT*> Bucket;
215 InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
219 DenseMap<NodeT*, NodeT*> IDoms;
221 // Vertex - Map the DFS number to the BasicBlock*
222 std::vector<NodeT*> Vertex;
224 // Info - Collection of information used during the computation of idoms.
225 DenseMap<NodeT*, InfoRec> Info;
228 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
229 E = DomTreeNodes.end(); I != E; ++I)
231 DomTreeNodes.clear();
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), GraphT::child_end(NewBB)) == 1
244 && "NewBB should have a single successor!");
245 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
247 std::vector<typename GraphT::NodeType*> PredBlocks;
248 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
249 GraphTraits<Inverse<N> >::child_begin(NewBB),
250 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
251 PredBlocks.push_back(*PI);
253 assert(!PredBlocks.empty() && "No predblocks??");
255 bool NewBBDominatesNewBBSucc = true;
256 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
257 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
258 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
259 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI) &&
260 DT.isReachableFromEntry(*PI)) {
261 NewBBDominatesNewBBSucc = false;
265 // Find NewBB's immediate dominator and create new dominator tree node for
267 NodeT *NewBBIDom = 0;
269 for (i = 0; i < PredBlocks.size(); ++i)
270 if (DT.isReachableFromEntry(PredBlocks[i])) {
271 NewBBIDom = PredBlocks[i];
275 // It's possible that none of the predecessors of NewBB are reachable;
276 // in that case, NewBB itself is unreachable, so nothing needs to be
281 for (i = i + 1; i < PredBlocks.size(); ++i) {
282 if (DT.isReachableFromEntry(PredBlocks[i]))
283 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
286 // Create the new dominator tree node... and set the idom of NewBB.
287 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
289 // If NewBB strictly dominates other blocks, then it is now the immediate
290 // dominator of NewBBSucc. Update the dominator tree as appropriate.
291 if (NewBBDominatesNewBBSucc) {
292 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
293 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
298 explicit DominatorTreeBase(bool isPostDom)
299 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
300 virtual ~DominatorTreeBase() { reset(); }
302 // FIXME: Should remove this
303 virtual bool runOnFunction(Function &F) { return false; }
305 /// compare - Return false if the other dominator tree base matches this
306 /// dominator tree base. Otherwise return true.
307 bool compare(DominatorTreeBase &Other) const {
309 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
310 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
313 SmallPtrSet<const NodeT *,4> MyBBs;
314 for (typename DomTreeNodeMapType::const_iterator
315 I = this->DomTreeNodes.begin(),
316 E = this->DomTreeNodes.end(); I != E; ++I) {
317 NodeT *BB = I->first;
318 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
319 if (OI == OtherDomTreeNodes.end())
322 DomTreeNodeBase<NodeT>* MyNd = I->second;
323 DomTreeNodeBase<NodeT>* OtherNd = OI->second;
325 if (MyNd->compare(OtherNd))
332 virtual void releaseMemory() { reset(); }
334 /// getNode - return the (Post)DominatorTree node for the specified basic
335 /// block. This is the same as using operator[] on this class.
337 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
338 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
339 return I != DomTreeNodes.end() ? I->second : 0;
342 /// getRootNode - This returns the entry node for the CFG of the function. If
343 /// this tree represents the post-dominance relations for a function, however,
344 /// this root may be a node with the block == NULL. This is the case when
345 /// there are multiple exit nodes from a particular function. Consumers of
346 /// post-dominance information must be capable of dealing with this
349 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
350 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
352 /// properlyDominates - Returns true iff this dominates N and this != N.
353 /// Note that this is not a constant time operation!
355 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
356 const DomTreeNodeBase<NodeT> *B) const {
357 if (A == 0 || B == 0) return false;
358 return dominatedBySlowTreeWalk(A, B);
361 inline bool properlyDominates(NodeT *A, NodeT *B) {
362 return properlyDominates(getNode(A), getNode(B));
365 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
366 const DomTreeNodeBase<NodeT> *B) const {
367 const DomTreeNodeBase<NodeT> *IDom;
368 if (A == 0 || B == 0) return false;
369 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
370 B = IDom; // Walk up the tree
375 /// isReachableFromEntry - Return true if A is dominated by the entry
376 /// block of the function containing it.
377 bool isReachableFromEntry(NodeT* A) {
378 assert (!this->isPostDominator()
379 && "This is not implemented for post dominators");
380 return dominates(&A->getParent()->front(), A);
383 /// dominates - Returns true iff A dominates B. Note that this is not a
384 /// constant time operation!
386 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
387 const DomTreeNodeBase<NodeT> *B) {
389 return true; // A node trivially dominates itself.
391 if (A == 0 || B == 0)
395 return B->DominatedBy(A);
397 // If we end up with too many slow queries, just update the
398 // DFS numbers on the theory that we are going to keep querying.
400 if (SlowQueries > 32) {
402 return B->DominatedBy(A);
405 return dominatedBySlowTreeWalk(A, B);
408 inline bool dominates(const NodeT *A, const NodeT *B) {
412 // Cast away the const qualifiers here. This is ok since
413 // this function doesn't actually return the values returned
415 return dominates(getNode(const_cast<NodeT *>(A)),
416 getNode(const_cast<NodeT *>(B)));
419 NodeT *getRoot() const {
420 assert(this->Roots.size() == 1 && "Should always have entry node!");
421 return this->Roots[0];
424 /// findNearestCommonDominator - Find nearest common dominator basic block
425 /// for basic block A and B. If there is no such block then return NULL.
426 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
428 assert (!this->isPostDominator()
429 && "This is not implemented for post dominators");
430 assert (A->getParent() == B->getParent()
431 && "Two blocks are not in same function");
433 // If either A or B is a entry block then it is nearest common dominator.
434 NodeT &Entry = A->getParent()->front();
435 if (A == &Entry || B == &Entry)
438 // If B dominates A then B is nearest common dominator.
442 // If A dominates B then A is nearest common dominator.
446 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
447 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
449 // Collect NodeA dominators set.
450 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
451 NodeADoms.insert(NodeA);
452 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
454 NodeADoms.insert(IDomA);
455 IDomA = IDomA->getIDom();
458 // Walk NodeB immediate dominators chain and find common dominator node.
459 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
461 if (NodeADoms.count(IDomB) != 0)
462 return IDomB->getBlock();
464 IDomB = IDomB->getIDom();
470 //===--------------------------------------------------------------------===//
471 // API to update (Post)DominatorTree information based on modifications to
474 /// addNewBlock - Add a new node to the dominator tree information. This
475 /// creates a new node as a child of DomBB dominator node,linking it into
476 /// the children list of the immediate dominator.
477 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
478 assert(getNode(BB) == 0 && "Block already in dominator tree!");
479 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
480 assert(IDomNode && "Not immediate dominator specified for block!");
481 DFSInfoValid = false;
482 return DomTreeNodes[BB] =
483 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
486 /// changeImmediateDominator - This method is used to update the dominator
487 /// tree information when a node's immediate dominator changes.
489 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
490 DomTreeNodeBase<NodeT> *NewIDom) {
491 assert(N && NewIDom && "Cannot change null node pointers!");
492 DFSInfoValid = false;
496 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
497 changeImmediateDominator(getNode(BB), getNode(NewBB));
500 /// eraseNode - Removes a node from the dominator tree. Block must not
501 /// domiante any other blocks. Removes node from its immediate dominator's
502 /// children list. Deletes dominator node associated with basic block BB.
503 void eraseNode(NodeT *BB) {
504 DomTreeNodeBase<NodeT> *Node = getNode(BB);
505 assert (Node && "Removing node that isn't in dominator tree.");
506 assert (Node->getChildren().empty() && "Node is not a leaf node.");
508 // Remove node from immediate dominator's children list.
509 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
511 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
512 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
513 assert(I != IDom->Children.end() &&
514 "Not in immediate dominator children set!");
515 // I am no longer your child...
516 IDom->Children.erase(I);
519 DomTreeNodes.erase(BB);
523 /// removeNode - Removes a node from the dominator tree. Block must not
524 /// dominate any other blocks. Invalidates any node pointing to removed
526 void removeNode(NodeT *BB) {
527 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
528 DomTreeNodes.erase(BB);
531 /// splitBlock - BB is split and now it has one successor. Update dominator
532 /// tree to reflect this change.
533 void splitBlock(NodeT* NewBB) {
534 if (this->IsPostDominators)
535 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
537 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
540 /// print - Convert to human readable form
542 void print(raw_ostream &o) const {
543 o << "=============================--------------------------------\n";
544 if (this->isPostDominator())
545 o << "Inorder PostDominator Tree: ";
547 o << "Inorder Dominator Tree: ";
548 if (this->DFSInfoValid)
549 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
552 // The postdom tree can have a null root if there are no returns.
554 PrintDomTree<NodeT>(getRootNode(), o, 1);
558 template<class GraphT>
559 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
560 typename GraphT::NodeType* VIn);
562 template<class GraphT>
563 friend typename GraphT::NodeType* Eval(
564 DominatorTreeBase<typename GraphT::NodeType>& DT,
565 typename GraphT::NodeType* V);
567 template<class GraphT>
568 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
569 unsigned DFSNumV, typename GraphT::NodeType* W,
570 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
572 template<class GraphT>
573 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
574 typename GraphT::NodeType* V,
577 template<class FuncT, class N>
578 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
581 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
582 /// dominator tree in dfs order.
583 void updateDFSNumbers() {
586 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
587 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
589 for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
590 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
591 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
592 ThisRoot->DFSNumIn = DFSNum++;
594 while (!WorkStack.empty()) {
595 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
596 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
597 WorkStack.back().second;
599 // If we visited all of the children of this node, "recurse" back up the
600 // stack setting the DFOutNum.
601 if (ChildIt == Node->end()) {
602 Node->DFSNumOut = DFSNum++;
603 WorkStack.pop_back();
605 // Otherwise, recursively visit this child.
606 DomTreeNodeBase<NodeT> *Child = *ChildIt;
607 ++WorkStack.back().second;
609 WorkStack.push_back(std::make_pair(Child, Child->begin()));
610 Child->DFSNumIn = DFSNum++;
619 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
620 typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
621 if (I != this->DomTreeNodes.end() && I->second)
624 // Haven't calculated this node yet? Get or calculate the node for the
625 // immediate dominator.
626 NodeT *IDom = getIDom(BB);
628 assert(IDom || this->DomTreeNodes[NULL]);
629 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
631 // Add a new tree node for this BasicBlock, and link it as a child of
633 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
634 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
637 inline NodeT *getIDom(NodeT *BB) const {
638 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
639 return I != IDoms.end() ? I->second : 0;
642 inline void addRoot(NodeT* BB) {
643 this->Roots.push_back(BB);
647 /// recalculate - compute a dominator tree for the given function
649 void recalculate(FT& F) {
650 if (!this->IsPostDominators) {
654 this->Roots.push_back(&F.front());
655 this->IDoms[&F.front()] = 0;
656 this->DomTreeNodes[&F.front()] = 0;
657 this->Vertex.push_back(0);
659 Calculate<FT, NodeT*>(*this, F);
663 reset(); // Reset from the last time we were run...
665 // Initialize the roots list
666 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
667 if (std::distance(GraphTraits<FT*>::child_begin(I),
668 GraphTraits<FT*>::child_end(I)) == 0)
671 // Prepopulate maps so that we don't get iterator invalidation issues later.
673 this->DomTreeNodes[I] = 0;
676 this->Vertex.push_back(0);
678 Calculate<FT, Inverse<NodeT*> >(*this, F);
683 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
685 //===-------------------------------------
686 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
687 /// compute a normal dominator tree.
689 class DominatorTree : public FunctionPass {
691 static char ID; // Pass ID, replacement for typeid
692 DominatorTreeBase<BasicBlock>* DT;
694 DominatorTree() : FunctionPass(&ID) {
695 DT = new DominatorTreeBase<BasicBlock>(false);
703 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
705 /// getRoots - Return the root blocks of the current CFG. This may include
706 /// multiple blocks if we are computing post dominators. For forward
707 /// dominators, this will always be a single block (the entry node).
709 inline const std::vector<BasicBlock*> &getRoots() const {
710 return DT->getRoots();
713 inline BasicBlock *getRoot() const {
714 return DT->getRoot();
717 inline DomTreeNode *getRootNode() const {
718 return DT->getRootNode();
721 /// compare - Return false if the other dominator tree matches this
722 /// dominator tree. Otherwise return true.
723 inline bool compare(DominatorTree &Other) const {
724 DomTreeNode *R = getRootNode();
725 DomTreeNode *OtherR = Other.getRootNode();
727 if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
730 if (DT->compare(Other.getBase()))
736 virtual bool runOnFunction(Function &F);
738 virtual void verifyAnalysis() const;
740 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
741 AU.setPreservesAll();
744 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
745 return DT->dominates(A, B);
748 inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
749 return DT->dominates(A, B);
752 // dominates - Return true if A dominates B. This performs the
753 // special checks necessary if A and B are in the same basic block.
754 bool dominates(const Instruction *A, const Instruction *B) const;
756 bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
757 return DT->properlyDominates(A, B);
760 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
761 return DT->properlyDominates(A, B);
764 /// findNearestCommonDominator - Find nearest common dominator basic block
765 /// for basic block A and B. If there is no such block then return NULL.
766 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
767 return DT->findNearestCommonDominator(A, B);
770 inline DomTreeNode *operator[](BasicBlock *BB) const {
771 return DT->getNode(BB);
774 /// getNode - return the (Post)DominatorTree node for the specified basic
775 /// block. This is the same as using operator[] on this class.
777 inline DomTreeNode *getNode(BasicBlock *BB) const {
778 return DT->getNode(BB);
781 /// addNewBlock - Add a new node to the dominator tree information. This
782 /// creates a new node as a child of DomBB dominator node,linking it into
783 /// the children list of the immediate dominator.
784 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
785 return DT->addNewBlock(BB, DomBB);
788 /// changeImmediateDominator - This method is used to update the dominator
789 /// tree information when a node's immediate dominator changes.
791 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
792 DT->changeImmediateDominator(N, NewIDom);
795 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
796 DT->changeImmediateDominator(N, NewIDom);
799 /// eraseNode - Removes a node from the dominator tree. Block must not
800 /// domiante any other blocks. Removes node from its immediate dominator's
801 /// children list. Deletes dominator node associated with basic block BB.
802 inline void eraseNode(BasicBlock *BB) {
806 /// splitBlock - BB is split and now it has one successor. Update dominator
807 /// tree to reflect this change.
808 inline void splitBlock(BasicBlock* NewBB) {
809 DT->splitBlock(NewBB);
812 bool isReachableFromEntry(BasicBlock* A) {
813 return DT->isReachableFromEntry(A);
817 virtual void releaseMemory() {
821 virtual void print(raw_ostream &OS, const Module* M= 0) const;
824 //===-------------------------------------
825 /// DominatorTree GraphTraits specialization so the DominatorTree can be
826 /// iterable by generic graph iterators.
828 template <> struct GraphTraits<DomTreeNode*> {
829 typedef DomTreeNode NodeType;
830 typedef NodeType::iterator ChildIteratorType;
832 static NodeType *getEntryNode(NodeType *N) {
835 static inline ChildIteratorType child_begin(NodeType *N) {
838 static inline ChildIteratorType child_end(NodeType *N) {
842 typedef df_iterator<DomTreeNode*> nodes_iterator;
844 static nodes_iterator nodes_begin(DomTreeNode *N) {
845 return df_begin(getEntryNode(N));
848 static nodes_iterator nodes_end(DomTreeNode *N) {
849 return df_end(getEntryNode(N));
853 template <> struct GraphTraits<DominatorTree*>
854 : public GraphTraits<DomTreeNode*> {
855 static NodeType *getEntryNode(DominatorTree *DT) {
856 return DT->getRootNode();
859 static nodes_iterator nodes_begin(DominatorTree *N) {
860 return df_begin(getEntryNode(N));
863 static nodes_iterator nodes_end(DominatorTree *N) {
864 return df_end(getEntryNode(N));
869 //===----------------------------------------------------------------------===//
870 /// DominanceFrontierBase - Common base class for computing forward and inverse
871 /// dominance frontiers for a function.
873 class DominanceFrontierBase : public FunctionPass {
875 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
876 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
878 DomSetMapType Frontiers;
879 std::vector<BasicBlock*> Roots;
880 const bool IsPostDominators;
883 DominanceFrontierBase(void *ID, bool isPostDom)
884 : FunctionPass(ID), IsPostDominators(isPostDom) {}
886 /// getRoots - Return the root blocks of the current CFG. This may include
887 /// multiple blocks if we are computing post dominators. For forward
888 /// dominators, this will always be a single block (the entry node).
890 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
892 /// isPostDominator - Returns true if analysis based of postdoms
894 bool isPostDominator() const { return IsPostDominators; }
896 virtual void releaseMemory() { Frontiers.clear(); }
898 // Accessor interface:
899 typedef DomSetMapType::iterator iterator;
900 typedef DomSetMapType::const_iterator const_iterator;
901 iterator begin() { return Frontiers.begin(); }
902 const_iterator begin() const { return Frontiers.begin(); }
903 iterator end() { return Frontiers.end(); }
904 const_iterator end() const { return Frontiers.end(); }
905 iterator find(BasicBlock *B) { return Frontiers.find(B); }
906 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
908 iterator addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
909 assert(find(BB) == end() && "Block already in DominanceFrontier!");
910 return Frontiers.insert(std::make_pair(BB, frontier)).first;
913 /// removeBlock - Remove basic block BB's frontier.
914 void removeBlock(BasicBlock *BB) {
915 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
916 for (iterator I = begin(), E = end(); I != E; ++I)
921 void addToFrontier(iterator I, BasicBlock *Node) {
922 assert(I != end() && "BB is not in DominanceFrontier!");
923 I->second.insert(Node);
926 void removeFromFrontier(iterator I, BasicBlock *Node) {
927 assert(I != end() && "BB is not in DominanceFrontier!");
928 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
929 I->second.erase(Node);
932 /// compareDomSet - Return false if two domsets match. Otherwise
934 bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
935 std::set<BasicBlock *> tmpSet;
936 for (DomSetType::const_iterator I = DS2.begin(),
937 E = DS2.end(); I != E; ++I)
940 for (DomSetType::const_iterator I = DS1.begin(),
941 E = DS1.end(); I != E; ) {
942 BasicBlock *Node = *I++;
944 if (tmpSet.erase(Node) == 0)
945 // Node is in DS1 but not in DS2.
950 // There are nodes that are in DS2 but not in DS1.
953 // DS1 and DS2 matches.
957 /// compare - Return true if the other dominance frontier base matches
958 /// this dominance frontier base. Otherwise return false.
959 bool compare(DominanceFrontierBase &Other) const {
960 DomSetMapType tmpFrontiers;
961 for (DomSetMapType::const_iterator I = Other.begin(),
962 E = Other.end(); I != E; ++I)
963 tmpFrontiers.insert(std::make_pair(I->first, I->second));
965 for (DomSetMapType::iterator I = tmpFrontiers.begin(),
966 E = tmpFrontiers.end(); I != E; ) {
967 BasicBlock *Node = I->first;
968 const_iterator DFI = find(Node);
972 if (compareDomSet(I->second, DFI->second))
976 tmpFrontiers.erase(Node);
979 if (!tmpFrontiers.empty())
985 /// print - Convert to human readable form
987 virtual void print(raw_ostream &OS, const Module* = 0) const;
991 //===-------------------------------------
992 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
993 /// used to compute a forward dominator frontiers.
995 class DominanceFrontier : public DominanceFrontierBase {
997 static char ID; // Pass ID, replacement for typeid
998 DominanceFrontier() :
999 DominanceFrontierBase(&ID, false) {}
1001 BasicBlock *getRoot() const {
1002 assert(Roots.size() == 1 && "Should always have entry node!");
1006 virtual bool runOnFunction(Function &) {
1008 DominatorTree &DT = getAnalysis<DominatorTree>();
1009 Roots = DT.getRoots();
1010 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1011 calculate(DT, DT[Roots[0]]);
1015 virtual void verifyAnalysis() const;
1017 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1018 AU.setPreservesAll();
1019 AU.addRequired<DominatorTree>();
1022 /// splitBlock - BB is split and now it has one successor. Update dominance
1023 /// frontier to reflect this change.
1024 void splitBlock(BasicBlock *BB);
1026 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1027 /// to reflect this change.
1028 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1029 DominatorTree *DT) {
1030 // NewBB is now dominating BB. Which means BB's dominance
1031 // frontier is now part of NewBB's dominance frontier. However, BB
1032 // itself is not member of NewBB's dominance frontier.
1033 DominanceFrontier::iterator NewDFI = find(NewBB);
1034 DominanceFrontier::iterator DFI = find(BB);
1035 // If BB was an entry block then its frontier is empty.
1038 DominanceFrontier::DomSetType BBSet = DFI->second;
1039 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1040 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1041 BasicBlock *DFMember = *BBSetI;
1042 // Insert only if NewBB dominates DFMember.
1043 if (!DT->dominates(NewBB, DFMember))
1044 NewDFI->second.insert(DFMember);
1046 NewDFI->second.erase(BB);
1049 const DomSetType &calculate(const DominatorTree &DT,
1050 const DomTreeNode *Node);
1054 } // End llvm namespace