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 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 std::ostream &operator<<(std::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, std::ostream &o,
180 o << std::string(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 // The newly inserted basic block will dominate existing basic blocks iff the
256 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
257 // the non-pred blocks, then they all must be the same block!
259 bool NewBBDominatesNewBBSucc = true;
261 typename GraphT::NodeType* OnePred = PredBlocks[0];
262 size_t i = 1, e = PredBlocks.size();
263 for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
264 assert(i != e && "Didn't find reachable pred?");
265 OnePred = PredBlocks[i];
269 if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
270 NewBBDominatesNewBBSucc = false;
274 if (NewBBDominatesNewBBSucc)
275 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
276 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
277 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
278 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
279 NewBBDominatesNewBBSucc = false;
284 // The other scenario where the new block can dominate its successors are when
285 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
287 if (!NewBBDominatesNewBBSucc) {
288 NewBBDominatesNewBBSucc = true;
289 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
290 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
291 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
292 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
293 NewBBDominatesNewBBSucc = false;
298 // Find NewBB's immediate dominator and create new dominator tree node for
300 NodeT *NewBBIDom = 0;
302 for (i = 0; i < PredBlocks.size(); ++i)
303 if (DT.isReachableFromEntry(PredBlocks[i])) {
304 NewBBIDom = PredBlocks[i];
307 assert(i != PredBlocks.size() && "No reachable preds?");
308 for (i = i + 1; i < PredBlocks.size(); ++i) {
309 if (DT.isReachableFromEntry(PredBlocks[i]))
310 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
312 assert(NewBBIDom && "No immediate dominator found??");
314 // Create the new dominator tree node... and set the idom of NewBB.
315 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
317 // If NewBB strictly dominates other blocks, then it is now the immediate
318 // dominator of NewBBSucc. Update the dominator tree as appropriate.
319 if (NewBBDominatesNewBBSucc) {
320 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
321 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
326 explicit DominatorTreeBase(bool isPostDom)
327 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
328 virtual ~DominatorTreeBase() { reset(); }
330 // FIXME: Should remove this
331 virtual bool runOnFunction(Function &F) { return false; }
333 /// compare - Return false if the other dominator tree base matches this
334 /// dominator tree base. Otherwise return true.
335 bool compare(DominatorTreeBase &Other) const {
337 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
338 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
341 SmallPtrSet<const NodeT *,4> MyBBs;
342 for (typename DomTreeNodeMapType::const_iterator
343 I = this->DomTreeNodes.begin(),
344 E = this->DomTreeNodes.end(); I != E; ++I) {
345 NodeT *BB = I->first;
346 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
347 if (OI == OtherDomTreeNodes.end())
350 DomTreeNodeBase<NodeT>* MyNd = I->second;
351 DomTreeNodeBase<NodeT>* OtherNd = OI->second;
353 if (MyNd->compare(OtherNd))
360 virtual void releaseMemory() { reset(); }
362 /// getNode - return the (Post)DominatorTree node for the specified basic
363 /// block. This is the same as using operator[] on this class.
365 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
366 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
367 return I != DomTreeNodes.end() ? I->second : 0;
370 /// getRootNode - This returns the entry node for the CFG of the function. If
371 /// this tree represents the post-dominance relations for a function, however,
372 /// this root may be a node with the block == NULL. This is the case when
373 /// there are multiple exit nodes from a particular function. Consumers of
374 /// post-dominance information must be capable of dealing with this
377 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
378 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
380 /// properlyDominates - Returns true iff this dominates N and this != N.
381 /// Note that this is not a constant time operation!
383 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
384 DomTreeNodeBase<NodeT> *B) const {
385 if (A == 0 || B == 0) return false;
386 return dominatedBySlowTreeWalk(A, B);
389 inline bool properlyDominates(NodeT *A, NodeT *B) {
390 return properlyDominates(getNode(A), getNode(B));
393 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
394 const DomTreeNodeBase<NodeT> *B) const {
395 const DomTreeNodeBase<NodeT> *IDom;
396 if (A == 0 || B == 0) return false;
397 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
398 B = IDom; // Walk up the tree
403 /// isReachableFromEntry - Return true if A is dominated by the entry
404 /// block of the function containing it.
405 bool isReachableFromEntry(NodeT* A) {
406 assert (!this->isPostDominator()
407 && "This is not implemented for post dominators");
408 return dominates(&A->getParent()->front(), A);
411 /// dominates - Returns true iff A dominates B. Note that this is not a
412 /// constant time operation!
414 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
415 DomTreeNodeBase<NodeT> *B) {
417 return true; // A node trivially dominates itself.
419 if (A == 0 || B == 0)
423 return B->DominatedBy(A);
425 // If we end up with too many slow queries, just update the
426 // DFS numbers on the theory that we are going to keep querying.
428 if (SlowQueries > 32) {
430 return B->DominatedBy(A);
433 return dominatedBySlowTreeWalk(A, B);
436 inline bool dominates(NodeT *A, NodeT *B) {
440 return dominates(getNode(A), getNode(B));
443 NodeT *getRoot() const {
444 assert(this->Roots.size() == 1 && "Should always have entry node!");
445 return this->Roots[0];
448 /// findNearestCommonDominator - Find nearest common dominator basic block
449 /// for basic block A and B. If there is no such block then return NULL.
450 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
452 assert (!this->isPostDominator()
453 && "This is not implemented for post dominators");
454 assert (A->getParent() == B->getParent()
455 && "Two blocks are not in same function");
457 // If either A or B is a entry block then it is nearest common dominator.
458 NodeT &Entry = A->getParent()->front();
459 if (A == &Entry || B == &Entry)
462 // If B dominates A then B is nearest common dominator.
466 // If A dominates B then A is nearest common dominator.
470 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
471 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
473 // Collect NodeA dominators set.
474 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
475 NodeADoms.insert(NodeA);
476 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
478 NodeADoms.insert(IDomA);
479 IDomA = IDomA->getIDom();
482 // Walk NodeB immediate dominators chain and find common dominator node.
483 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
485 if (NodeADoms.count(IDomB) != 0)
486 return IDomB->getBlock();
488 IDomB = IDomB->getIDom();
494 //===--------------------------------------------------------------------===//
495 // API to update (Post)DominatorTree information based on modifications to
498 /// addNewBlock - Add a new node to the dominator tree information. This
499 /// creates a new node as a child of DomBB dominator node,linking it into
500 /// the children list of the immediate dominator.
501 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
502 assert(getNode(BB) == 0 && "Block already in dominator tree!");
503 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
504 assert(IDomNode && "Not immediate dominator specified for block!");
505 DFSInfoValid = false;
506 return DomTreeNodes[BB] =
507 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
510 /// changeImmediateDominator - This method is used to update the dominator
511 /// tree information when a node's immediate dominator changes.
513 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
514 DomTreeNodeBase<NodeT> *NewIDom) {
515 assert(N && NewIDom && "Cannot change null node pointers!");
516 DFSInfoValid = false;
520 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
521 changeImmediateDominator(getNode(BB), getNode(NewBB));
524 /// eraseNode - Removes a node from the dominator tree. Block must not
525 /// domiante any other blocks. Removes node from its immediate dominator's
526 /// children list. Deletes dominator node associated with basic block BB.
527 void eraseNode(NodeT *BB) {
528 DomTreeNodeBase<NodeT> *Node = getNode(BB);
529 assert (Node && "Removing node that isn't in dominator tree.");
530 assert (Node->getChildren().empty() && "Node is not a leaf node.");
532 // Remove node from immediate dominator's children list.
533 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
535 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
536 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
537 assert(I != IDom->Children.end() &&
538 "Not in immediate dominator children set!");
539 // I am no longer your child...
540 IDom->Children.erase(I);
543 DomTreeNodes.erase(BB);
547 /// removeNode - Removes a node from the dominator tree. Block must not
548 /// dominate any other blocks. Invalidates any node pointing to removed
550 void removeNode(NodeT *BB) {
551 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
552 DomTreeNodes.erase(BB);
555 /// splitBlock - BB is split and now it has one successor. Update dominator
556 /// tree to reflect this change.
557 void splitBlock(NodeT* NewBB) {
558 if (this->IsPostDominators)
559 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
561 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
564 /// print - Convert to human readable form
566 virtual void print(std::ostream &o, const Module* ) const {
567 o << "=============================--------------------------------\n";
568 if (this->isPostDominator())
569 o << "Inorder PostDominator Tree: ";
571 o << "Inorder Dominator Tree: ";
572 if (this->DFSInfoValid)
573 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
576 PrintDomTree<NodeT>(getRootNode(), o, 1);
579 void print(std::ostream *OS, const Module* M = 0) const {
580 if (OS) print(*OS, M);
583 virtual void dump() {
588 template<class GraphT>
589 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
590 typename GraphT::NodeType* VIn);
592 template<class GraphT>
593 friend typename GraphT::NodeType* Eval(
594 DominatorTreeBase<typename GraphT::NodeType>& DT,
595 typename GraphT::NodeType* V);
597 template<class GraphT>
598 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
599 unsigned DFSNumV, typename GraphT::NodeType* W,
600 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
602 template<class GraphT>
603 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
604 typename GraphT::NodeType* V,
607 template<class FuncT, class N>
608 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
611 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
612 /// dominator tree in dfs order.
613 void updateDFSNumbers() {
616 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
617 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
619 for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
620 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
621 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
622 ThisRoot->DFSNumIn = DFSNum++;
624 while (!WorkStack.empty()) {
625 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
626 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
627 WorkStack.back().second;
629 // If we visited all of the children of this node, "recurse" back up the
630 // stack setting the DFOutNum.
631 if (ChildIt == Node->end()) {
632 Node->DFSNumOut = DFSNum++;
633 WorkStack.pop_back();
635 // Otherwise, recursively visit this child.
636 DomTreeNodeBase<NodeT> *Child = *ChildIt;
637 ++WorkStack.back().second;
639 WorkStack.push_back(std::make_pair(Child, Child->begin()));
640 Child->DFSNumIn = DFSNum++;
649 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
650 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
653 // Haven't calculated this node yet? Get or calculate the node for the
654 // immediate dominator.
655 NodeT *IDom = getIDom(BB);
657 assert(IDom || this->DomTreeNodes[NULL]);
658 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
660 // Add a new tree node for this BasicBlock, and link it as a child of
662 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
663 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
666 inline NodeT *getIDom(NodeT *BB) const {
667 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
668 return I != IDoms.end() ? I->second : 0;
671 inline void addRoot(NodeT* BB) {
672 this->Roots.push_back(BB);
676 /// recalculate - compute a dominator tree for the given function
678 void recalculate(FT& F) {
679 if (!this->IsPostDominators) {
683 this->Roots.push_back(&F.front());
684 this->IDoms[&F.front()] = 0;
685 this->DomTreeNodes[&F.front()] = 0;
686 this->Vertex.push_back(0);
688 Calculate<FT, NodeT*>(*this, F);
692 reset(); // Reset from the last time we were run...
694 // Initialize the roots list
695 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
696 if (std::distance(GraphTraits<FT*>::child_begin(I),
697 GraphTraits<FT*>::child_end(I)) == 0)
700 // Prepopulate maps so that we don't get iterator invalidation issues later.
702 this->DomTreeNodes[I] = 0;
705 this->Vertex.push_back(0);
707 Calculate<FT, Inverse<NodeT*> >(*this, F);
712 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
714 //===-------------------------------------
715 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
716 /// compute a normal dominator tree.
718 class DominatorTree : public FunctionPass {
720 static char ID; // Pass ID, replacement for typeid
721 DominatorTreeBase<BasicBlock>* DT;
723 DominatorTree() : FunctionPass(&ID) {
724 DT = new DominatorTreeBase<BasicBlock>(false);
732 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
734 /// getRoots - Return the root blocks of the current CFG. This may include
735 /// multiple blocks if we are computing post dominators. For forward
736 /// dominators, this will always be a single block (the entry node).
738 inline const std::vector<BasicBlock*> &getRoots() const {
739 return DT->getRoots();
742 inline BasicBlock *getRoot() const {
743 return DT->getRoot();
746 inline DomTreeNode *getRootNode() const {
747 return DT->getRootNode();
750 /// compare - Return false if the other dominator tree matches this
751 /// dominator tree. Otherwise return true.
752 inline bool compare(DominatorTree &Other) const {
753 DomTreeNode *R = getRootNode();
754 DomTreeNode *OtherR = Other.getRootNode();
756 if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
759 if (DT->compare(Other.getBase()))
765 virtual bool runOnFunction(Function &F);
767 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
768 AU.setPreservesAll();
771 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
772 return DT->dominates(A, B);
775 inline bool dominates(BasicBlock* A, BasicBlock* B) const {
776 return DT->dominates(A, B);
779 // dominates - Return true if A dominates B. This performs the
780 // special checks necessary if A and B are in the same basic block.
781 bool dominates(Instruction *A, Instruction *B) const {
782 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
783 if (BBA != BBB) return DT->dominates(BBA, BBB);
785 // It is not possible to determine dominance between two PHI nodes
786 // based on their ordering.
787 if (isa<PHINode>(A) && isa<PHINode>(B))
790 // Loop through the basic block until we find A or B.
791 BasicBlock::iterator I = BBA->begin();
792 for (; &*I != A && &*I != B; ++I) /*empty*/;
794 //if(!DT.IsPostDominators) {
795 // A dominates B if it is found first in the basic block.
798 // // A post-dominates B if B is found first in the basic block.
803 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
804 return DT->properlyDominates(A, B);
807 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
808 return DT->properlyDominates(A, B);
811 /// findNearestCommonDominator - Find nearest common dominator basic block
812 /// for basic block A and B. If there is no such block then return NULL.
813 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
814 return DT->findNearestCommonDominator(A, B);
817 inline DomTreeNode *operator[](BasicBlock *BB) const {
818 return DT->getNode(BB);
821 /// getNode - return the (Post)DominatorTree node for the specified basic
822 /// block. This is the same as using operator[] on this class.
824 inline DomTreeNode *getNode(BasicBlock *BB) const {
825 return DT->getNode(BB);
828 /// addNewBlock - Add a new node to the dominator tree information. This
829 /// creates a new node as a child of DomBB dominator node,linking it into
830 /// the children list of the immediate dominator.
831 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
832 return DT->addNewBlock(BB, DomBB);
835 /// changeImmediateDominator - This method is used to update the dominator
836 /// tree information when a node's immediate dominator changes.
838 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
839 DT->changeImmediateDominator(N, NewIDom);
842 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
843 DT->changeImmediateDominator(N, NewIDom);
846 /// eraseNode - Removes a node from the dominator tree. Block must not
847 /// domiante any other blocks. Removes node from its immediate dominator's
848 /// children list. Deletes dominator node associated with basic block BB.
849 inline void eraseNode(BasicBlock *BB) {
853 /// splitBlock - BB is split and now it has one successor. Update dominator
854 /// tree to reflect this change.
855 inline void splitBlock(BasicBlock* NewBB) {
856 DT->splitBlock(NewBB);
859 bool isReachableFromEntry(BasicBlock* A) {
860 return DT->isReachableFromEntry(A);
864 virtual void releaseMemory() {
868 virtual void print(std::ostream &OS, const Module* M= 0) const {
873 //===-------------------------------------
874 /// DominatorTree GraphTraits specialization so the DominatorTree can be
875 /// iterable by generic graph iterators.
877 template <> struct GraphTraits<DomTreeNode *> {
878 typedef DomTreeNode NodeType;
879 typedef NodeType::iterator ChildIteratorType;
881 static NodeType *getEntryNode(NodeType *N) {
884 static inline ChildIteratorType child_begin(NodeType* N) {
887 static inline ChildIteratorType child_end(NodeType* N) {
892 template <> struct GraphTraits<DominatorTree*>
893 : public GraphTraits<DomTreeNode *> {
894 static NodeType *getEntryNode(DominatorTree *DT) {
895 return DT->getRootNode();
900 //===----------------------------------------------------------------------===//
901 /// DominanceFrontierBase - Common base class for computing forward and inverse
902 /// dominance frontiers for a function.
904 class DominanceFrontierBase : public FunctionPass {
906 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
907 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
909 DomSetMapType Frontiers;
910 std::vector<BasicBlock*> Roots;
911 const bool IsPostDominators;
914 DominanceFrontierBase(void *ID, bool isPostDom)
915 : FunctionPass(ID), IsPostDominators(isPostDom) {}
917 /// getRoots - Return the root blocks of the current CFG. This may include
918 /// multiple blocks if we are computing post dominators. For forward
919 /// dominators, this will always be a single block (the entry node).
921 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
923 /// isPostDominator - Returns true if analysis based of postdoms
925 bool isPostDominator() const { return IsPostDominators; }
927 virtual void releaseMemory() { Frontiers.clear(); }
929 // Accessor interface:
930 typedef DomSetMapType::iterator iterator;
931 typedef DomSetMapType::const_iterator const_iterator;
932 iterator begin() { return Frontiers.begin(); }
933 const_iterator begin() const { return Frontiers.begin(); }
934 iterator end() { return Frontiers.end(); }
935 const_iterator end() const { return Frontiers.end(); }
936 iterator find(BasicBlock *B) { return Frontiers.find(B); }
937 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
939 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
940 assert(find(BB) == end() && "Block already in DominanceFrontier!");
941 Frontiers.insert(std::make_pair(BB, frontier));
944 /// removeBlock - Remove basic block BB's frontier.
945 void removeBlock(BasicBlock *BB) {
946 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
947 for (iterator I = begin(), E = end(); I != E; ++I)
952 void addToFrontier(iterator I, BasicBlock *Node) {
953 assert(I != end() && "BB is not in DominanceFrontier!");
954 I->second.insert(Node);
957 void removeFromFrontier(iterator I, BasicBlock *Node) {
958 assert(I != end() && "BB is not in DominanceFrontier!");
959 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
960 I->second.erase(Node);
963 /// compareDomSet - Return false if two domsets match. Otherwise
965 bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
966 std::set<BasicBlock *> tmpSet;
967 for (DomSetType::const_iterator I = DS2.begin(),
968 E = DS2.end(); I != E; ++I)
971 for (DomSetType::const_iterator I = DS1.begin(),
972 E = DS1.end(); I != E; ++I) {
973 BasicBlock *Node = *I;
975 if (tmpSet.erase(Node) == 0)
976 // Node is in DS1 but not in DS2.
981 // There are nodes that are in DS2 but not in DS1.
984 // DS1 and DS2 matches.
988 /// compare - Return true if the other dominance frontier base matches
989 /// this dominance frontier base. Otherwise return false.
990 bool compare(DominanceFrontierBase &Other) const {
991 DomSetMapType tmpFrontiers;
992 for (DomSetMapType::const_iterator I = Other.begin(),
993 E = Other.end(); I != E; ++I)
994 tmpFrontiers.insert(std::make_pair(I->first, I->second));
996 for (DomSetMapType::iterator I = tmpFrontiers.begin(),
997 E = tmpFrontiers.end(); I != E; ++I) {
998 BasicBlock *Node = I->first;
999 const_iterator DFI = find(Node);
1003 if (compareDomSet(I->second, DFI->second))
1006 tmpFrontiers.erase(Node);
1009 if (!tmpFrontiers.empty())
1015 /// print - Convert to human readable form
1017 virtual void print(std::ostream &OS, const Module* = 0) const;
1018 void print(std::ostream *OS, const Module* M = 0) const {
1019 if (OS) print(*OS, M);
1021 virtual void dump();
1025 //===-------------------------------------
1026 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
1027 /// used to compute a forward dominator frontiers.
1029 class DominanceFrontier : public DominanceFrontierBase {
1031 static char ID; // Pass ID, replacement for typeid
1032 DominanceFrontier() :
1033 DominanceFrontierBase(&ID, false) {}
1035 BasicBlock *getRoot() const {
1036 assert(Roots.size() == 1 && "Should always have entry node!");
1040 virtual bool runOnFunction(Function &) {
1042 DominatorTree &DT = getAnalysis<DominatorTree>();
1043 Roots = DT.getRoots();
1044 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1045 calculate(DT, DT[Roots[0]]);
1049 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1050 AU.setPreservesAll();
1051 AU.addRequired<DominatorTree>();
1054 /// splitBlock - BB is split and now it has one successor. Update dominance
1055 /// frontier to reflect this change.
1056 void splitBlock(BasicBlock *BB);
1058 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1059 /// to reflect this change.
1060 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1061 DominatorTree *DT) {
1062 // NewBB is now dominating BB. Which means BB's dominance
1063 // frontier is now part of NewBB's dominance frontier. However, BB
1064 // itself is not member of NewBB's dominance frontier.
1065 DominanceFrontier::iterator NewDFI = find(NewBB);
1066 DominanceFrontier::iterator DFI = find(BB);
1067 // If BB was an entry block then its frontier is empty.
1070 DominanceFrontier::DomSetType BBSet = DFI->second;
1071 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1072 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1073 BasicBlock *DFMember = *BBSetI;
1074 // Insert only if NewBB dominates DFMember.
1075 if (!DT->dominates(NewBB, DFMember))
1076 NewDFI->second.insert(DFMember);
1078 NewDFI->second.erase(BB);
1081 const DomSetType &calculate(const DominatorTree &DT,
1082 const DomTreeNode *Node);
1086 } // End llvm namespace