1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the following classes:
11 // 1. DominatorTree: Represent dominators as an explicit tree structure.
12 // 2. ETForest: Efficient data structure for dominance comparisons and
13 // nearest-common-ancestor queries.
14 // 3. DominanceFrontier: Calculate and hold the dominance frontier for a
17 // These data structures are listed in increasing order of complexity. It
18 // takes longer to calculate the dominator frontier, for example, than the
19 // DominatorTree mapping.
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_ANALYSIS_DOMINATORS_H
24 #define LLVM_ANALYSIS_DOMINATORS_H
26 #include "llvm/Analysis/ET-Forest.h"
27 #include "llvm/Pass.h"
34 template <typename GraphType> struct GraphTraits;
36 //===----------------------------------------------------------------------===//
37 /// DominatorBase - Base class that other, more interesting dominator analyses
40 class DominatorBase : public FunctionPass {
42 std::vector<BasicBlock*> Roots;
43 const bool IsPostDominators;
44 inline DominatorBase(intptr_t ID, bool isPostDom) :
45 FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
48 /// getRoots - Return the root blocks of the current CFG. This may include
49 /// multiple blocks if we are computing post dominators. For forward
50 /// dominators, this will always be a single block (the entry node).
52 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
54 /// isPostDominator - Returns true if analysis based of postdoms
56 bool isPostDominator() const { return IsPostDominators; }
60 //===----------------------------------------------------------------------===//
61 // DomTreeNode - Dominator Tree Node
67 std::vector<DomTreeNode*> Children;
69 typedef std::vector<DomTreeNode*>::iterator iterator;
70 typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
72 iterator begin() { return Children.begin(); }
73 iterator end() { return Children.end(); }
74 const_iterator begin() const { return Children.begin(); }
75 const_iterator end() const { return Children.end(); }
77 inline BasicBlock *getBlock() const { return TheBB; }
78 inline DomTreeNode *getIDom() const { return IDom; }
79 inline ETNode *getETNode() const { return ETN; }
80 inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
82 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom, ETNode *E)
83 : TheBB(BB), IDom(iDom), ETN(E) {
85 ETN->setFather(IDom->getETNode());
87 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
88 void setIDom(DomTreeNode *NewIDom);
91 //===----------------------------------------------------------------------===//
92 /// DominatorTree - Calculate the immediate dominator tree for a function.
94 class DominatorTreeBase : public DominatorBase {
98 typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
99 DomTreeNodeMapType DomTreeNodes;
100 DomTreeNode *RootNode;
102 typedef std::map<BasicBlock*, ETNode*> ETMapType;
106 unsigned int SlowQueries;
107 // Information record used during immediate dominators computation.
111 BasicBlock *Label, *Parent, *Child, *Ancestor;
113 std::vector<BasicBlock*> Bucket;
115 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
118 std::map<BasicBlock*, BasicBlock*> IDoms;
120 // Vertex - Map the DFS number to the BasicBlock*
121 std::vector<BasicBlock*> Vertex;
123 // Info - Collection of information used during the computation of idoms.
124 std::map<BasicBlock*, InfoRec> Info;
127 DominatorTreeBase(intptr_t ID, bool isPostDom)
128 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
129 ~DominatorTreeBase() { reset(); }
131 virtual void releaseMemory() { reset(); }
133 /// getNode - return the (Post)DominatorTree node for the specified basic
134 /// block. This is the same as using operator[] on this class.
136 inline DomTreeNode *getNode(BasicBlock *BB) const {
137 DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
138 return (i != DomTreeNodes.end()) ? i->second : 0;
141 inline DomTreeNode *operator[](BasicBlock *BB) const {
145 /// getIDomBlock - return basic block BB's immediate domiantor basic block.
147 BasicBlock *getIDomBlock(BasicBlock *BB) {
148 DomTreeNode *N = getNode(BB);
149 assert (N && "Missing dominator tree node");
150 DomTreeNode *I = N->getIDom();
151 assert (N && "Missing immediate dominator");
152 return I->getBlock();
155 /// getRootNode - This returns the entry node for the CFG of the function. If
156 /// this tree represents the post-dominance relations for a function, however,
157 /// this root may be a node with the block == NULL. This is the case when
158 /// there are multiple exit nodes from a particular function. Consumers of
159 /// post-dominance information must be capable of dealing with this
162 DomTreeNode *getRootNode() { return RootNode; }
163 const DomTreeNode *getRootNode() const { return RootNode; }
165 /// properlyDominates - Returns true iff this dominates N and this != N.
166 /// Note that this is not a constant time operation!
168 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
169 if (A == 0 || B == 0) return false;
170 return dominatedBySlowTreeWalk(A, B);
173 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
174 return properlyDominates(getNode(A), getNode(B));
177 bool dominatedBySlowTreeWalk(const DomTreeNode *A,
178 const DomTreeNode *B) const {
179 const DomTreeNode *IDom;
180 if (A == 0 || B == 0) return false;
181 while ((IDom = B->getIDom()) != 0 && IDom != A)
182 B = IDom; // Walk up the tree
186 void updateDFSNumbers();
188 /// Return the nearest common dominator of A and B.
189 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
190 ETNode *NodeA = getNode(A)->getETNode();
191 ETNode *NodeB = getNode(B)->getETNode();
193 ETNode *Common = NodeA->NCA(NodeB);
196 return Common->getData<BasicBlock>();
199 /// isReachableFromEntry - Return true if A is dominated by the entry
200 /// block of the function containing it.
201 const bool isReachableFromEntry(BasicBlock* A);
203 /// dominates - Returns true iff this dominates N. Note that this is not a
204 /// constant time operation!
206 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
208 return true; // A node trivially dominates itself.
210 if (A == 0 || B == 0)
213 ETNode *NodeA = A->getETNode();
214 ETNode *NodeB = B->getETNode();
217 return NodeB->DominatedBy(NodeA);
219 // If we end up with too many slow queries, just update the
220 // DFS numbers on the theory that we are going to keep querying.
222 if (SlowQueries > 32) {
224 return NodeB->DominatedBy(NodeA);
226 //return NodeB->DominatedBySlow(NodeA);
227 return dominatedBySlowTreeWalk(A, B);
230 inline bool dominates(BasicBlock *A, BasicBlock *B) {
234 return dominates(getNode(A), getNode(B));
237 // dominates - Return true if A dominates B. This performs the
238 // special checks necessary if A and B are in the same basic block.
239 bool dominates(Instruction *A, Instruction *B);
241 //===--------------------------------------------------------------------===//
242 // API to update (Post)DominatorTree information based on modifications to
245 /// addNewBlock - Add a new node to the dominator tree information. This
246 /// creates a new node as a child of DomBB dominator node,linking it into
247 /// the children list of the immediate dominator.
248 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
249 assert(getNode(BB) == 0 && "Block already in dominator tree!");
250 DomTreeNode *IDomNode = getNode(DomBB);
251 assert(IDomNode && "Not immediate dominator specified for block!");
252 DFSInfoValid = false;
253 ETNode *E = new ETNode(BB);
255 return DomTreeNodes[BB] =
256 IDomNode->addChild(new DomTreeNode(BB, IDomNode, E));
259 /// changeImmediateDominator - This method is used to update the dominator
260 /// tree information when a node's immediate dominator changes.
262 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
263 assert(N && NewIDom && "Cannot change null node pointers!");
264 DFSInfoValid = false;
268 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
269 changeImmediateDominator(getNode(BB), getNode(NewBB));
272 /// removeNode - Removes a node from the dominator tree. Block must not
273 /// dominate any other blocks. Invalidates any node pointing to removed
275 void removeNode(BasicBlock *BB) {
276 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
277 DomTreeNodes.erase(BB);
280 /// print - Convert to human readable form
282 virtual void print(std::ostream &OS, const Module* = 0) const;
283 void print(std::ostream *OS, const Module* M = 0) const {
284 if (OS) print(*OS, M);
289 //===-------------------------------------
290 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
291 /// compute a normal dominator tree.
293 class DominatorTree : public DominatorTreeBase {
295 static char ID; // Pass ID, replacement for typeid
296 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
298 BasicBlock *getRoot() const {
299 assert(Roots.size() == 1 && "Should always have entry node!");
303 virtual bool runOnFunction(Function &F);
305 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
306 AU.setPreservesAll();
309 void calculate(Function& F);
310 DomTreeNode *getNodeForBlock(BasicBlock *BB);
311 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
312 void Compress(BasicBlock *V);
313 BasicBlock *Eval(BasicBlock *v);
314 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
315 inline BasicBlock *getIDom(BasicBlock *BB) const {
316 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
317 return I != IDoms.end() ? I->second : 0;
321 //===-------------------------------------
322 /// DominatorTree GraphTraits specialization so the DominatorTree can be
323 /// iterable by generic graph iterators.
325 template <> struct GraphTraits<DomTreeNode*> {
326 typedef DomTreeNode NodeType;
327 typedef NodeType::iterator ChildIteratorType;
329 static NodeType *getEntryNode(NodeType *N) {
332 static inline ChildIteratorType child_begin(NodeType* N) {
335 static inline ChildIteratorType child_end(NodeType* N) {
340 template <> struct GraphTraits<DominatorTree*>
341 : public GraphTraits<DomTreeNode*> {
342 static NodeType *getEntryNode(DominatorTree *DT) {
343 return DT->getRootNode();
348 //===-------------------------------------
349 /// ET-Forest Class - Class used to construct forwards and backwards
352 class ETForestBase : public DominatorBase {
354 ETForestBase(intptr_t ID, bool isPostDom)
355 : DominatorBase(ID, isPostDom), Nodes(),
356 DFSInfoValid(false), SlowQueries(0) {}
358 virtual void releaseMemory() { reset(); }
360 typedef std::map<BasicBlock*, ETNode*> ETMapType;
362 // FIXME : There is no need to make this interface public.
363 // Fix predicate simplifier.
364 void updateDFSNumbers();
366 /// dominates - Return true if A dominates B.
368 inline bool dominates(BasicBlock *A, BasicBlock *B) {
372 ETNode *NodeA = getNode(A);
373 ETNode *NodeB = getNode(B);
376 return NodeB->DominatedBy(NodeA);
378 // If we end up with too many slow queries, just update the
379 // DFS numbers on the theory that we are going to keep querying.
381 if (SlowQueries > 32) {
383 return NodeB->DominatedBy(NodeA);
385 return NodeB->DominatedBySlow(NodeA);
389 // dominates - Return true if A dominates B. This performs the
390 // special checks necessary if A and B are in the same basic block.
391 bool dominates(Instruction *A, Instruction *B);
393 /// properlyDominates - Return true if A dominates B and A != B.
395 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
396 return dominates(A, B) && A != B;
399 /// isReachableFromEntry - Return true if A is dominated by the entry
400 /// block of the function containing it.
401 const bool isReachableFromEntry(BasicBlock* A);
403 /// Return the nearest common dominator of A and B.
404 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
405 ETNode *NodeA = getNode(A);
406 ETNode *NodeB = getNode(B);
408 ETNode *Common = NodeA->NCA(NodeB);
411 return Common->getData<BasicBlock>();
414 /// Return the immediate dominator of A.
415 BasicBlock *getIDom(BasicBlock *A) const {
416 ETNode *NodeA = getNode(A);
417 if (!NodeA) return 0;
418 const ETNode *idom = NodeA->getFather();
419 return idom ? idom->getData<BasicBlock>() : 0;
422 void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
423 ETNode *NodeA = getNode(A);
425 const ETNode* son = NodeA->getSon();
428 children.push_back(son->getData<BasicBlock>());
430 const ETNode* brother = son->getBrother();
431 while (brother != son) {
432 children.push_back(brother->getData<BasicBlock>());
433 brother = brother->getBrother();
437 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
438 AU.setPreservesAll();
439 AU.addRequired<DominatorTree>();
441 //===--------------------------------------------------------------------===//
442 // API to update Forest information based on modifications
445 /// addNewBlock - Add a new block to the CFG, with the specified immediate
448 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
450 /// setImmediateDominator - Update the immediate dominator information to
451 /// change the current immediate dominator for the specified block
452 /// to another block. This method requires that BB for NewIDom
453 /// already have an ETNode, otherwise just use addNewBlock.
455 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
456 /// print - Convert to human readable form
458 virtual void print(std::ostream &OS, const Module* = 0) const;
459 void print(std::ostream *OS, const Module* M = 0) const {
460 if (OS) print(*OS, M);
464 /// getNode - return the (Post)DominatorTree node for the specified basic
465 /// block. This is the same as using operator[] on this class.
467 inline ETNode *getNode(BasicBlock *BB) const {
468 ETMapType::const_iterator i = Nodes.find(BB);
469 return (i != Nodes.end()) ? i->second : 0;
472 inline ETNode *operator[](BasicBlock *BB) const {
479 unsigned int SlowQueries;
483 //==-------------------------------------
484 /// ETForest Class - Concrete subclass of ETForestBase that is used to
485 /// compute a forwards ET-Forest.
487 class ETForest : public ETForestBase {
489 static char ID; // Pass identification, replacement for typeid
491 ETForest() : ETForestBase((intptr_t)&ID, false) {}
493 BasicBlock *getRoot() const {
494 assert(Roots.size() == 1 && "Should always have entry node!");
498 virtual bool runOnFunction(Function &F) {
499 reset(); // Reset from the last time we were run...
500 DominatorTree &DT = getAnalysis<DominatorTree>();
501 Roots = DT.getRoots();
506 void calculate(const DominatorTree &DT);
507 // FIXME : There is no need to make getNodeForBlock public. Fix
508 // predicate simplifier.
509 ETNode *getNodeForBlock(BasicBlock *BB);
512 //===----------------------------------------------------------------------===//
513 /// DominanceFrontierBase - Common base class for computing forward and inverse
514 /// dominance frontiers for a function.
516 class DominanceFrontierBase : public DominatorBase {
518 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
519 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
521 DomSetMapType Frontiers;
523 DominanceFrontierBase(intptr_t ID, bool isPostDom)
524 : DominatorBase(ID, isPostDom) {}
526 virtual void releaseMemory() { Frontiers.clear(); }
528 // Accessor interface:
529 typedef DomSetMapType::iterator iterator;
530 typedef DomSetMapType::const_iterator const_iterator;
531 iterator begin() { return Frontiers.begin(); }
532 const_iterator begin() const { return Frontiers.begin(); }
533 iterator end() { return Frontiers.end(); }
534 const_iterator end() const { return Frontiers.end(); }
535 iterator find(BasicBlock *B) { return Frontiers.find(B); }
536 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
538 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
539 assert(find(BB) == end() && "Block already in DominanceFrontier!");
540 Frontiers.insert(std::make_pair(BB, frontier));
543 void addToFrontier(iterator I, BasicBlock *Node) {
544 assert(I != end() && "BB is not in DominanceFrontier!");
545 I->second.insert(Node);
548 void removeFromFrontier(iterator I, BasicBlock *Node) {
549 assert(I != end() && "BB is not in DominanceFrontier!");
550 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
551 I->second.erase(Node);
554 /// print - Convert to human readable form
556 virtual void print(std::ostream &OS, const Module* = 0) const;
557 void print(std::ostream *OS, const Module* M = 0) const {
558 if (OS) print(*OS, M);
564 //===-------------------------------------
565 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
566 /// used to compute a forward dominator frontiers.
568 class DominanceFrontier : public DominanceFrontierBase {
570 static char ID; // Pass ID, replacement for typeid
571 DominanceFrontier() :
572 DominanceFrontierBase((intptr_t)& ID, false) {}
574 BasicBlock *getRoot() const {
575 assert(Roots.size() == 1 && "Should always have entry node!");
579 virtual bool runOnFunction(Function &) {
581 DominatorTree &DT = getAnalysis<DominatorTree>();
582 Roots = DT.getRoots();
583 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
584 calculate(DT, DT[Roots[0]]);
588 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
589 AU.setPreservesAll();
590 AU.addRequired<DominatorTree>();
594 const DomSetType &calculate(const DominatorTree &DT,
595 const DomTreeNode *Node);
599 } // End llvm namespace