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 DominatorTree class, which provides fast and efficient
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_DOMINATORS_H
16 #define LLVM_ANALYSIS_DOMINATORS_H
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DepthFirstIterator.h"
20 #include "llvm/ADT/GraphTraits.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/raw_ostream.h"
32 //===----------------------------------------------------------------------===//
33 /// DominatorBase - Base class that other, more interesting dominator analyses
36 template <class NodeT>
39 std::vector<NodeT*> Roots;
40 const bool IsPostDominators;
41 inline explicit DominatorBase(bool isPostDom) :
42 Roots(), IsPostDominators(isPostDom) {}
45 /// getRoots - Return the root blocks of the current CFG. This may include
46 /// multiple blocks if we are computing post dominators. For forward
47 /// dominators, this will always be a single block (the entry node).
49 inline const std::vector<NodeT*> &getRoots() const { return Roots; }
51 /// isPostDominator - Returns true if analysis based of postdoms
53 bool isPostDominator() const { return IsPostDominators; }
57 //===----------------------------------------------------------------------===//
58 // DomTreeNode - Dominator Tree Node
59 template<class NodeT> class DominatorTreeBase;
60 struct PostDominatorTree;
61 class MachineBasicBlock;
63 template <class NodeT>
64 class DomTreeNodeBase {
66 DomTreeNodeBase<NodeT> *IDom;
67 std::vector<DomTreeNodeBase<NodeT> *> Children;
68 int DFSNumIn, DFSNumOut;
70 template<class N> friend class DominatorTreeBase;
71 friend struct PostDominatorTree;
73 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
74 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
77 iterator begin() { return Children.begin(); }
78 iterator end() { return Children.end(); }
79 const_iterator begin() const { return Children.begin(); }
80 const_iterator end() const { return Children.end(); }
82 NodeT *getBlock() const { return TheBB; }
83 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
84 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
88 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
89 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
91 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
92 Children.push_back(C);
96 size_t getNumChildren() const {
97 return Children.size();
100 void clearAllChildren() {
104 bool compare(const DomTreeNodeBase<NodeT> *Other) const {
105 if (getNumChildren() != Other->getNumChildren())
108 SmallPtrSet<const NodeT *, 4> OtherChildren;
109 for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
110 const NodeT *Nd = (*I)->getBlock();
111 OtherChildren.insert(Nd);
114 for (const_iterator I = begin(), E = end(); I != E; ++I) {
115 const NodeT *N = (*I)->getBlock();
116 if (OtherChildren.count(N) == 0)
122 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
123 assert(IDom && "No immediate dominator?");
124 if (IDom != NewIDom) {
125 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
126 std::find(IDom->Children.begin(), IDom->Children.end(), this);
127 assert(I != IDom->Children.end() &&
128 "Not in immediate dominator children set!");
129 // I am no longer your child...
130 IDom->Children.erase(I);
132 // Switch to new dominator
134 IDom->Children.push_back(this);
138 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
140 unsigned getDFSNumIn() const { return DFSNumIn; }
141 unsigned getDFSNumOut() const { return DFSNumOut; }
143 // Return true if this node is dominated by other. Use this only if DFS info
145 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
146 return this->DFSNumIn >= other->DFSNumIn &&
147 this->DFSNumOut <= other->DFSNumOut;
151 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
152 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
154 template<class NodeT>
155 inline raw_ostream &operator<<(raw_ostream &o,
156 const DomTreeNodeBase<NodeT> *Node) {
157 if (Node->getBlock())
158 Node->getBlock()->printAsOperand(o, false);
160 o << " <<exit node>>";
162 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
167 template<class NodeT>
168 inline void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
170 o.indent(2*Lev) << "[" << Lev << "] " << N;
171 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
172 E = N->end(); I != E; ++I)
173 PrintDomTree<NodeT>(*I, o, Lev+1);
176 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
178 //===----------------------------------------------------------------------===//
179 /// DominatorTree - Calculate the immediate dominator tree for a function.
182 template<class FuncT, class N>
183 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
186 template<class NodeT>
187 class DominatorTreeBase : public DominatorBase<NodeT> {
188 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
189 const DomTreeNodeBase<NodeT> *B) const {
191 assert(isReachableFromEntry(B));
192 assert(isReachableFromEntry(A));
194 const DomTreeNodeBase<NodeT> *IDom;
195 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
196 B = IDom; // Walk up the tree
201 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
202 DomTreeNodeMapType DomTreeNodes;
203 DomTreeNodeBase<NodeT> *RootNode;
206 unsigned int SlowQueries;
207 // Information record used during immediate dominators computation.
214 InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(0) {}
217 DenseMap<NodeT*, NodeT*> IDoms;
219 // Vertex - Map the DFS number to the BasicBlock*
220 std::vector<NodeT*> Vertex;
222 // Info - Collection of information used during the computation of idoms.
223 DenseMap<NodeT*, InfoRec> Info;
226 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
227 E = DomTreeNodes.end(); I != E; ++I)
229 DomTreeNodes.clear();
236 // NewBB is split and now it has one successor. Update dominator tree to
237 // reflect this change.
238 template<class N, class GraphT>
239 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
240 typename GraphT::NodeType* NewBB) {
241 assert(std::distance(GraphT::child_begin(NewBB),
242 GraphT::child_end(NewBB)) == 1 &&
243 "NewBB should have a single successor!");
244 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
246 std::vector<typename GraphT::NodeType*> PredBlocks;
247 typedef GraphTraits<Inverse<N> > InvTraits;
248 for (typename InvTraits::ChildIteratorType PI =
249 InvTraits::child_begin(NewBB),
250 PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
251 PredBlocks.push_back(*PI);
253 assert(!PredBlocks.empty() && "No predblocks?");
255 bool NewBBDominatesNewBBSucc = true;
256 for (typename InvTraits::ChildIteratorType PI =
257 InvTraits::child_begin(NewBBSucc),
258 E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
259 typename InvTraits::NodeType *ND = *PI;
260 if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
261 DT.isReachableFromEntry(ND)) {
262 NewBBDominatesNewBBSucc = false;
267 // Find NewBB's immediate dominator and create new dominator tree node for
269 NodeT *NewBBIDom = 0;
271 for (i = 0; i < PredBlocks.size(); ++i)
272 if (DT.isReachableFromEntry(PredBlocks[i])) {
273 NewBBIDom = PredBlocks[i];
277 // It's possible that none of the predecessors of NewBB are reachable;
278 // in that case, NewBB itself is unreachable, so nothing needs to be
283 for (i = i + 1; i < PredBlocks.size(); ++i) {
284 if (DT.isReachableFromEntry(PredBlocks[i]))
285 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
288 // Create the new dominator tree node... and set the idom of NewBB.
289 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
291 // If NewBB strictly dominates other blocks, then it is now the immediate
292 // dominator of NewBBSucc. Update the dominator tree as appropriate.
293 if (NewBBDominatesNewBBSucc) {
294 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
295 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
300 explicit DominatorTreeBase(bool isPostDom)
301 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
302 virtual ~DominatorTreeBase() { reset(); }
304 /// compare - Return false if the other dominator tree base matches this
305 /// dominator tree base. Otherwise return true.
306 bool compare(DominatorTreeBase &Other) const {
308 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
309 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
312 for (typename DomTreeNodeMapType::const_iterator
313 I = this->DomTreeNodes.begin(),
314 E = this->DomTreeNodes.end(); I != E; ++I) {
315 NodeT *BB = I->first;
316 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
317 if (OI == OtherDomTreeNodes.end())
320 DomTreeNodeBase<NodeT>* MyNd = I->second;
321 DomTreeNodeBase<NodeT>* OtherNd = OI->second;
323 if (MyNd->compare(OtherNd))
330 virtual void releaseMemory() { reset(); }
332 /// getNode - return the (Post)DominatorTree node for the specified basic
333 /// block. This is the same as using operator[] on this class.
335 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
336 return DomTreeNodes.lookup(BB);
339 /// getRootNode - This returns the entry node for the CFG of the function. If
340 /// this tree represents the post-dominance relations for a function, however,
341 /// this root may be a node with the block == NULL. This is the case when
342 /// there are multiple exit nodes from a particular function. Consumers of
343 /// post-dominance information must be capable of dealing with this
346 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
347 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
349 /// Get all nodes dominated by R, including R itself.
350 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
352 const DomTreeNodeBase<NodeT> *RN = getNode(R);
354 return; // If R is unreachable, it will not be present in the DOM tree.
355 SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
358 while (!WL.empty()) {
359 const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
360 Result.push_back(N->getBlock());
361 WL.append(N->begin(), N->end());
365 /// properlyDominates - Returns true iff A dominates B and A != B.
366 /// Note that this is not a constant time operation!
368 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
369 const DomTreeNodeBase<NodeT> *B) {
370 if (A == 0 || B == 0)
374 return dominates(A, B);
377 bool properlyDominates(const NodeT *A, const NodeT *B);
379 /// isReachableFromEntry - Return true if A is dominated by the entry
380 /// block of the function containing it.
381 bool isReachableFromEntry(const NodeT* A) const {
382 assert(!this->isPostDominator() &&
383 "This is not implemented for post dominators");
384 return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
387 inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
391 /// dominates - Returns true iff A dominates B. Note that this is not a
392 /// constant time operation!
394 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
395 const DomTreeNodeBase<NodeT> *B) {
396 // A node trivially dominates itself.
400 // An unreachable node is dominated by anything.
401 if (!isReachableFromEntry(B))
404 // And dominates nothing.
405 if (!isReachableFromEntry(A))
408 // Compare the result of the tree walk and the dfs numbers, if expensive
409 // checks are enabled.
411 assert((!DFSInfoValid ||
412 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
413 "Tree walk disagrees with dfs numbers!");
417 return B->DominatedBy(A);
419 // If we end up with too many slow queries, just update the
420 // DFS numbers on the theory that we are going to keep querying.
422 if (SlowQueries > 32) {
424 return B->DominatedBy(A);
427 return dominatedBySlowTreeWalk(A, B);
430 bool dominates(const NodeT *A, const NodeT *B);
432 NodeT *getRoot() const {
433 assert(this->Roots.size() == 1 && "Should always have entry node!");
434 return this->Roots[0];
437 /// findNearestCommonDominator - Find nearest common dominator basic block
438 /// for basic block A and B. If there is no such block then return NULL.
439 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
440 assert(A->getParent() == B->getParent() &&
441 "Two blocks are not in same function");
443 // If either A or B is a entry block then it is nearest common dominator
444 // (for forward-dominators).
445 if (!this->isPostDominator()) {
446 NodeT &Entry = A->getParent()->front();
447 if (A == &Entry || B == &Entry)
451 // If B dominates A then B is nearest common dominator.
455 // If A dominates B then A is nearest common dominator.
459 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
460 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
462 // Collect NodeA dominators set.
463 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
464 NodeADoms.insert(NodeA);
465 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
467 NodeADoms.insert(IDomA);
468 IDomA = IDomA->getIDom();
471 // Walk NodeB immediate dominators chain and find common dominator node.
472 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
474 if (NodeADoms.count(IDomB) != 0)
475 return IDomB->getBlock();
477 IDomB = IDomB->getIDom();
483 const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
484 // Cast away the const qualifiers here. This is ok since
485 // const is re-introduced on the return type.
486 return findNearestCommonDominator(const_cast<NodeT *>(A),
487 const_cast<NodeT *>(B));
490 //===--------------------------------------------------------------------===//
491 // API to update (Post)DominatorTree information based on modifications to
494 /// addNewBlock - Add a new node to the dominator tree information. This
495 /// creates a new node as a child of DomBB dominator node,linking it into
496 /// the children list of the immediate dominator.
497 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
498 assert(getNode(BB) == 0 && "Block already in dominator tree!");
499 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
500 assert(IDomNode && "Not immediate dominator specified for block!");
501 DFSInfoValid = false;
502 return DomTreeNodes[BB] =
503 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
506 /// changeImmediateDominator - This method is used to update the dominator
507 /// tree information when a node's immediate dominator changes.
509 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
510 DomTreeNodeBase<NodeT> *NewIDom) {
511 assert(N && NewIDom && "Cannot change null node pointers!");
512 DFSInfoValid = false;
516 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
517 changeImmediateDominator(getNode(BB), getNode(NewBB));
520 /// eraseNode - Removes a node from the dominator tree. Block must not
521 /// dominate any other blocks. Removes node from its immediate dominator's
522 /// children list. Deletes dominator node associated with basic block BB.
523 void eraseNode(NodeT *BB) {
524 DomTreeNodeBase<NodeT> *Node = getNode(BB);
525 assert(Node && "Removing node that isn't in dominator tree.");
526 assert(Node->getChildren().empty() && "Node is not a leaf node.");
528 // Remove node from immediate dominator's children list.
529 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
531 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
532 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
533 assert(I != IDom->Children.end() &&
534 "Not in immediate dominator children set!");
535 // I am no longer your child...
536 IDom->Children.erase(I);
539 DomTreeNodes.erase(BB);
543 /// removeNode - Removes a node from the dominator tree. Block must not
544 /// dominate any other blocks. Invalidates any node pointing to removed
546 void removeNode(NodeT *BB) {
547 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
548 DomTreeNodes.erase(BB);
551 /// splitBlock - BB is split and now it has one successor. Update dominator
552 /// tree to reflect this change.
553 void splitBlock(NodeT* NewBB) {
554 if (this->IsPostDominators)
555 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
557 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
560 /// print - Convert to human readable form
562 void print(raw_ostream &o) const {
563 o << "=============================--------------------------------\n";
564 if (this->isPostDominator())
565 o << "Inorder PostDominator Tree: ";
567 o << "Inorder Dominator Tree: ";
568 if (!this->DFSInfoValid)
569 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
572 // The postdom tree can have a null root if there are no returns.
574 PrintDomTree<NodeT>(getRootNode(), o, 1);
578 template<class GraphT>
579 friend typename GraphT::NodeType* Eval(
580 DominatorTreeBase<typename GraphT::NodeType>& DT,
581 typename GraphT::NodeType* V,
582 unsigned LastLinked);
584 template<class GraphT>
585 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
586 typename GraphT::NodeType* V,
589 template<class FuncT, class N>
590 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
593 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
594 /// dominator tree in dfs order.
595 void updateDFSNumbers() {
598 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
599 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
601 DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
606 // Even in the case of multiple exits that form the post dominator root
607 // nodes, do not iterate over all exits, but start from the virtual root
608 // node. Otherwise bbs, that are not post dominated by any exit but by the
609 // virtual root node, will never be assigned a DFS number.
610 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
611 ThisRoot->DFSNumIn = DFSNum++;
613 while (!WorkStack.empty()) {
614 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
615 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
616 WorkStack.back().second;
618 // If we visited all of the children of this node, "recurse" back up the
619 // stack setting the DFOutNum.
620 if (ChildIt == Node->end()) {
621 Node->DFSNumOut = DFSNum++;
622 WorkStack.pop_back();
624 // Otherwise, recursively visit this child.
625 DomTreeNodeBase<NodeT> *Child = *ChildIt;
626 ++WorkStack.back().second;
628 WorkStack.push_back(std::make_pair(Child, Child->begin()));
629 Child->DFSNumIn = DFSNum++;
637 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
638 if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
641 // Haven't calculated this node yet? Get or calculate the node for the
642 // immediate dominator.
643 NodeT *IDom = getIDom(BB);
645 assert(IDom || this->DomTreeNodes[NULL]);
646 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
648 // Add a new tree node for this BasicBlock, and link it as a child of
650 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
651 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
654 inline NodeT *getIDom(NodeT *BB) const {
655 return IDoms.lookup(BB);
658 inline void addRoot(NodeT* BB) {
659 this->Roots.push_back(BB);
663 /// recalculate - compute a dominator tree for the given function
665 void recalculate(FT& F) {
666 typedef GraphTraits<FT*> TraitsTy;
668 this->Vertex.push_back(0);
670 if (!this->IsPostDominators) {
672 NodeT *entry = TraitsTy::getEntryNode(&F);
673 this->Roots.push_back(entry);
674 this->IDoms[entry] = 0;
675 this->DomTreeNodes[entry] = 0;
677 Calculate<FT, NodeT*>(*this, F);
679 // Initialize the roots list
680 for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
681 E = TraitsTy::nodes_end(&F); I != E; ++I) {
682 if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
685 // Prepopulate maps so that we don't get iterator invalidation issues later.
687 this->DomTreeNodes[I] = 0;
690 Calculate<FT, Inverse<NodeT*> >(*this, F);
695 // These two functions are declared out of line as a workaround for building
696 // with old (< r147295) versions of clang because of pr11642.
697 template<class NodeT>
698 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) {
702 // Cast away the const qualifiers here. This is ok since
703 // this function doesn't actually return the values returned
705 return dominates(getNode(const_cast<NodeT *>(A)),
706 getNode(const_cast<NodeT *>(B)));
708 template<class NodeT>
710 DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B) {
714 // Cast away the const qualifiers here. This is ok since
715 // this function doesn't actually return the values returned
717 return dominates(getNode(const_cast<NodeT *>(A)),
718 getNode(const_cast<NodeT *>(B)));
721 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
723 class BasicBlockEdge {
724 const BasicBlock *Start;
725 const BasicBlock *End;
727 BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) :
728 Start(Start_), End(End_) { }
729 const BasicBlock *getStart() const {
732 const BasicBlock *getEnd() const {
735 bool isSingleEdge() const;
738 //===-------------------------------------
739 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
740 /// compute a normal dominator tree.
742 class DominatorTree : public FunctionPass {
744 static char ID; // Pass ID, replacement for typeid
745 DominatorTreeBase<BasicBlock>* DT;
747 DominatorTree() : FunctionPass(ID) {
748 initializeDominatorTreePass(*PassRegistry::getPassRegistry());
749 DT = new DominatorTreeBase<BasicBlock>(false);
756 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
758 /// getRoots - Return the root blocks of the current CFG. This may include
759 /// multiple blocks if we are computing post dominators. For forward
760 /// dominators, this will always be a single block (the entry node).
762 inline const std::vector<BasicBlock*> &getRoots() const {
763 return DT->getRoots();
766 inline BasicBlock *getRoot() const {
767 return DT->getRoot();
770 inline DomTreeNode *getRootNode() const {
771 return DT->getRootNode();
774 /// Get all nodes dominated by R, including R itself.
775 void getDescendants(BasicBlock *R,
776 SmallVectorImpl<BasicBlock *> &Result) const {
777 DT->getDescendants(R, Result);
780 /// compare - Return false if the other dominator tree matches this
781 /// dominator tree. Otherwise return true.
782 inline bool compare(DominatorTree &Other) const {
783 DomTreeNode *R = getRootNode();
784 DomTreeNode *OtherR = Other.getRootNode();
786 if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
789 if (DT->compare(Other.getBase()))
795 virtual bool runOnFunction(Function &F);
797 virtual void verifyAnalysis() const;
799 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
800 AU.setPreservesAll();
803 inline bool dominates(const DomTreeNode* A, const DomTreeNode* B) const {
804 return DT->dominates(A, B);
807 inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
808 return DT->dominates(A, B);
811 // dominates - Return true if Def dominates a use in User. This performs
812 // the special checks necessary if Def and User are in the same basic block.
813 // Note that Def doesn't dominate a use in Def itself!
814 bool dominates(const Instruction *Def, const Use &U) const;
815 bool dominates(const Instruction *Def, const Instruction *User) const;
816 bool dominates(const Instruction *Def, const BasicBlock *BB) const;
817 bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
818 bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
820 bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
821 return DT->properlyDominates(A, B);
824 bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const {
825 return DT->properlyDominates(A, B);
828 /// findNearestCommonDominator - Find nearest common dominator basic block
829 /// for basic block A and B. If there is no such block then return NULL.
830 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
831 return DT->findNearestCommonDominator(A, B);
834 inline const BasicBlock *findNearestCommonDominator(const BasicBlock *A,
835 const BasicBlock *B) {
836 return DT->findNearestCommonDominator(A, B);
839 inline DomTreeNode *operator[](BasicBlock *BB) const {
840 return DT->getNode(BB);
843 /// getNode - return the (Post)DominatorTree node for the specified basic
844 /// block. This is the same as using operator[] on this class.
846 inline DomTreeNode *getNode(BasicBlock *BB) const {
847 return DT->getNode(BB);
850 /// addNewBlock - Add a new node to the dominator tree information. This
851 /// creates a new node as a child of DomBB dominator node,linking it into
852 /// the children list of the immediate dominator.
853 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
854 return DT->addNewBlock(BB, DomBB);
857 /// changeImmediateDominator - This method is used to update the dominator
858 /// tree information when a node's immediate dominator changes.
860 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
861 DT->changeImmediateDominator(N, NewIDom);
864 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
865 DT->changeImmediateDominator(N, NewIDom);
868 /// eraseNode - Removes a node from the dominator tree. Block must not
869 /// dominate any other blocks. Removes node from its immediate dominator's
870 /// children list. Deletes dominator node associated with basic block BB.
871 inline void eraseNode(BasicBlock *BB) {
875 /// splitBlock - BB is split and now it has one successor. Update dominator
876 /// tree to reflect this change.
877 inline void splitBlock(BasicBlock* NewBB) {
878 DT->splitBlock(NewBB);
881 bool isReachableFromEntry(const BasicBlock* A) const {
882 return DT->isReachableFromEntry(A);
885 bool isReachableFromEntry(const Use &U) const;
888 virtual void releaseMemory() {
892 virtual void print(raw_ostream &OS, const Module* M= 0) const;
895 //===-------------------------------------
896 /// DominatorTree GraphTraits specialization so the DominatorTree can be
897 /// iterable by generic graph iterators.
899 template <> struct GraphTraits<DomTreeNode*> {
900 typedef DomTreeNode NodeType;
901 typedef NodeType::iterator ChildIteratorType;
903 static NodeType *getEntryNode(NodeType *N) {
906 static inline ChildIteratorType child_begin(NodeType *N) {
909 static inline ChildIteratorType child_end(NodeType *N) {
913 typedef df_iterator<DomTreeNode*> nodes_iterator;
915 static nodes_iterator nodes_begin(DomTreeNode *N) {
916 return df_begin(getEntryNode(N));
919 static nodes_iterator nodes_end(DomTreeNode *N) {
920 return df_end(getEntryNode(N));
924 template <> struct GraphTraits<DominatorTree*>
925 : public GraphTraits<DomTreeNode*> {
926 static NodeType *getEntryNode(DominatorTree *DT) {
927 return DT->getRootNode();
930 static nodes_iterator nodes_begin(DominatorTree *N) {
931 return df_begin(getEntryNode(N));
934 static nodes_iterator nodes_end(DominatorTree *N) {
935 return df_end(getEntryNode(N));
940 } // End llvm namespace