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
62 class DominatorTreeBase;
63 class PostDominatorTree;
67 std::vector<DomTreeNode*> Children;
68 int DFSNumIn, DFSNumOut;
70 friend class DominatorTreeBase;
71 friend class PostDominatorTree;
73 typedef std::vector<DomTreeNode*>::iterator iterator;
74 typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
76 iterator begin() { return Children.begin(); }
77 iterator end() { return Children.end(); }
78 const_iterator begin() const { return Children.begin(); }
79 const_iterator end() const { return Children.end(); }
81 inline BasicBlock *getBlock() const { return TheBB; }
82 inline DomTreeNode *getIDom() const { return IDom; }
83 inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
85 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
86 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
87 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
88 void setIDom(DomTreeNode *NewIDom);
91 // Return true if this node is dominated by other. Use this only if DFS info is valid.
92 bool DominatedBy(const DomTreeNode *other) const {
93 return this->DFSNumIn >= other->DFSNumIn &&
94 this->DFSNumOut <= other->DFSNumOut;
97 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
99 void assignDFSNumber(int num);
102 //===----------------------------------------------------------------------===//
103 /// DominatorTree - Calculate the immediate dominator tree for a function.
105 class DominatorTreeBase : public DominatorBase {
109 typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
110 DomTreeNodeMapType DomTreeNodes;
111 DomTreeNode *RootNode;
114 unsigned int SlowQueries;
115 // Information record used during immediate dominators computation.
119 BasicBlock *Label, *Parent, *Child, *Ancestor;
121 std::vector<BasicBlock*> Bucket;
123 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
126 std::map<BasicBlock*, BasicBlock*> IDoms;
128 // Vertex - Map the DFS number to the BasicBlock*
129 std::vector<BasicBlock*> Vertex;
131 // Info - Collection of information used during the computation of idoms.
132 std::map<BasicBlock*, InfoRec> Info;
134 void updateDFSNumbers();
137 DominatorTreeBase(intptr_t ID, bool isPostDom)
138 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
139 ~DominatorTreeBase() { reset(); }
141 virtual void releaseMemory() { reset(); }
143 /// getNode - return the (Post)DominatorTree node for the specified basic
144 /// block. This is the same as using operator[] on this class.
146 inline DomTreeNode *getNode(BasicBlock *BB) const {
147 DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
148 return (i != DomTreeNodes.end()) ? i->second : 0;
151 inline DomTreeNode *operator[](BasicBlock *BB) const {
155 /// getIDomBlock - return basic block BB's immediate dominator basic block.
157 BasicBlock *getIDomBlock(BasicBlock *BB) {
158 DomTreeNode *N = getNode(BB);
159 assert (N && "Missing dominator tree node");
160 DomTreeNode *I = N->getIDom();
161 assert (N && "Missing immediate dominator");
162 return I->getBlock();
165 /// getRootNode - This returns the entry node for the CFG of the function. If
166 /// this tree represents the post-dominance relations for a function, however,
167 /// this root may be a node with the block == NULL. This is the case when
168 /// there are multiple exit nodes from a particular function. Consumers of
169 /// post-dominance information must be capable of dealing with this
172 DomTreeNode *getRootNode() { return RootNode; }
173 const DomTreeNode *getRootNode() const { return RootNode; }
175 /// properlyDominates - Returns true iff this dominates N and this != N.
176 /// Note that this is not a constant time operation!
178 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
179 if (A == 0 || B == 0) return false;
180 return dominatedBySlowTreeWalk(A, B);
183 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
184 return properlyDominates(getNode(A), getNode(B));
187 bool dominatedBySlowTreeWalk(const DomTreeNode *A,
188 const DomTreeNode *B) const {
189 const DomTreeNode *IDom;
190 if (A == 0 || B == 0) return false;
191 while ((IDom = B->getIDom()) != 0 && IDom != A)
192 B = IDom; // Walk up the tree
197 /// isReachableFromEntry - Return true if A is dominated by the entry
198 /// block of the function containing it.
199 const bool isReachableFromEntry(BasicBlock* A);
201 /// dominates - Returns true iff A dominates B. Note that this is not a
202 /// constant time operation!
204 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
206 return true; // A node trivially dominates itself.
208 if (A == 0 || B == 0)
212 return B->DominatedBy(A);
214 // If we end up with too many slow queries, just update the
215 // DFS numbers on the theory that we are going to keep querying.
217 if (SlowQueries > 32) {
219 return B->DominatedBy(A);
222 return dominatedBySlowTreeWalk(A, B);
225 inline bool dominates(BasicBlock *A, BasicBlock *B) {
229 return dominates(getNode(A), getNode(B));
232 /// findNearestCommonDominator - Find nearest common dominator basic block
233 /// for basic block A and B. If there is no such block then return NULL.
234 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
236 // dominates - Return true if A dominates B. This performs the
237 // special checks necessary if A and B are in the same basic block.
238 bool dominates(Instruction *A, Instruction *B);
240 //===--------------------------------------------------------------------===//
241 // API to update (Post)DominatorTree information based on modifications to
244 /// addNewBlock - Add a new node to the dominator tree information. This
245 /// creates a new node as a child of DomBB dominator node,linking it into
246 /// the children list of the immediate dominator.
247 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
248 assert(getNode(BB) == 0 && "Block already in dominator tree!");
249 DomTreeNode *IDomNode = getNode(DomBB);
250 assert(IDomNode && "Not immediate dominator specified for block!");
251 DFSInfoValid = false;
252 return DomTreeNodes[BB] =
253 IDomNode->addChild(new DomTreeNode(BB, IDomNode));
256 /// changeImmediateDominator - This method is used to update the dominator
257 /// tree information when a node's immediate dominator changes.
259 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
260 assert(N && NewIDom && "Cannot change null node pointers!");
261 DFSInfoValid = false;
265 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
266 changeImmediateDominator(getNode(BB), getNode(NewBB));
269 /// removeNode - Removes a node from the dominator tree. Block must not
270 /// dominate any other blocks. Invalidates any node pointing to removed
272 void removeNode(BasicBlock *BB) {
273 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
274 DomTreeNodes.erase(BB);
277 /// print - Convert to human readable form
279 virtual void print(std::ostream &OS, const Module* = 0) const;
280 void print(std::ostream *OS, const Module* M = 0) const {
281 if (OS) print(*OS, M);
286 //===-------------------------------------
287 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
288 /// compute a normal dominator tree.
290 class DominatorTree : public DominatorTreeBase {
292 static char ID; // Pass ID, replacement for typeid
293 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
295 BasicBlock *getRoot() const {
296 assert(Roots.size() == 1 && "Should always have entry node!");
300 virtual bool runOnFunction(Function &F);
302 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
303 AU.setPreservesAll();
306 void calculate(Function& F);
307 DomTreeNode *getNodeForBlock(BasicBlock *BB);
308 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
309 void Compress(BasicBlock *V);
310 BasicBlock *Eval(BasicBlock *v);
311 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
312 inline BasicBlock *getIDom(BasicBlock *BB) const {
313 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
314 return I != IDoms.end() ? I->second : 0;
318 //===-------------------------------------
319 /// DominatorTree GraphTraits specialization so the DominatorTree can be
320 /// iterable by generic graph iterators.
322 template <> struct GraphTraits<DomTreeNode*> {
323 typedef DomTreeNode NodeType;
324 typedef NodeType::iterator ChildIteratorType;
326 static NodeType *getEntryNode(NodeType *N) {
329 static inline ChildIteratorType child_begin(NodeType* N) {
332 static inline ChildIteratorType child_end(NodeType* N) {
337 template <> struct GraphTraits<DominatorTree*>
338 : public GraphTraits<DomTreeNode*> {
339 static NodeType *getEntryNode(DominatorTree *DT) {
340 return DT->getRootNode();
345 //===-------------------------------------
346 /// ET-Forest Class - Class used to construct forwards and backwards
349 class ETForestBase : public DominatorBase {
351 ETForestBase(intptr_t ID, bool isPostDom)
352 : DominatorBase(ID, isPostDom), Nodes(),
353 DFSInfoValid(false), SlowQueries(0) {}
355 virtual void releaseMemory() { reset(); }
357 typedef std::map<BasicBlock*, ETNode*> ETMapType;
359 // FIXME : There is no need to make this interface public.
360 // Fix predicate simplifier.
361 void updateDFSNumbers();
363 /// dominates - Return true if A dominates B.
365 inline bool dominates(BasicBlock *A, BasicBlock *B) {
369 ETNode *NodeA = getNode(A);
370 ETNode *NodeB = getNode(B);
373 return NodeB->DominatedBy(NodeA);
375 // If we end up with too many slow queries, just update the
376 // DFS numbers on the theory that we are going to keep querying.
378 if (SlowQueries > 32) {
380 return NodeB->DominatedBy(NodeA);
382 return NodeB->DominatedBySlow(NodeA);
386 // dominates - Return true if A dominates B. This performs the
387 // special checks necessary if A and B are in the same basic block.
388 bool dominates(Instruction *A, Instruction *B);
390 /// properlyDominates - Return true if A dominates B and A != B.
392 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
393 return dominates(A, B) && A != B;
396 /// isReachableFromEntry - Return true if A is dominated by the entry
397 /// block of the function containing it.
398 const bool isReachableFromEntry(BasicBlock* A);
400 /// Return the nearest common dominator of A and B.
401 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
402 ETNode *NodeA = getNode(A);
403 ETNode *NodeB = getNode(B);
405 ETNode *Common = NodeA->NCA(NodeB);
408 return Common->getData<BasicBlock>();
411 /// Return the immediate dominator of A.
412 BasicBlock *getIDom(BasicBlock *A) const {
413 ETNode *NodeA = getNode(A);
414 if (!NodeA) return 0;
415 const ETNode *idom = NodeA->getFather();
416 return idom ? idom->getData<BasicBlock>() : 0;
419 void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
420 ETNode *NodeA = getNode(A);
422 const ETNode* son = NodeA->getSon();
425 children.push_back(son->getData<BasicBlock>());
427 const ETNode* brother = son->getBrother();
428 while (brother != son) {
429 children.push_back(brother->getData<BasicBlock>());
430 brother = brother->getBrother();
434 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
435 AU.setPreservesAll();
436 AU.addRequired<DominatorTree>();
438 //===--------------------------------------------------------------------===//
439 // API to update Forest information based on modifications
442 /// addNewBlock - Add a new block to the CFG, with the specified immediate
445 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
447 /// setImmediateDominator - Update the immediate dominator information to
448 /// change the current immediate dominator for the specified block
449 /// to another block. This method requires that BB for NewIDom
450 /// already have an ETNode, otherwise just use addNewBlock.
452 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
453 /// print - Convert to human readable form
455 virtual void print(std::ostream &OS, const Module* = 0) const;
456 void print(std::ostream *OS, const Module* M = 0) const {
457 if (OS) print(*OS, M);
461 /// getNode - return the (Post)DominatorTree node for the specified basic
462 /// block. This is the same as using operator[] on this class.
464 inline ETNode *getNode(BasicBlock *BB) const {
465 ETMapType::const_iterator i = Nodes.find(BB);
466 return (i != Nodes.end()) ? i->second : 0;
469 inline ETNode *operator[](BasicBlock *BB) const {
476 unsigned int SlowQueries;
480 //==-------------------------------------
481 /// ETForest Class - Concrete subclass of ETForestBase that is used to
482 /// compute a forwards ET-Forest.
484 class ETForest : public ETForestBase {
486 static char ID; // Pass identification, replacement for typeid
488 ETForest() : ETForestBase((intptr_t)&ID, false) {}
490 BasicBlock *getRoot() const {
491 assert(Roots.size() == 1 && "Should always have entry node!");
495 virtual bool runOnFunction(Function &F) {
496 reset(); // Reset from the last time we were run...
497 DominatorTree &DT = getAnalysis<DominatorTree>();
498 Roots = DT.getRoots();
503 void calculate(const DominatorTree &DT);
504 // FIXME : There is no need to make getNodeForBlock public. Fix
505 // predicate simplifier.
506 ETNode *getNodeForBlock(BasicBlock *BB);
509 //===----------------------------------------------------------------------===//
510 /// DominanceFrontierBase - Common base class for computing forward and inverse
511 /// dominance frontiers for a function.
513 class DominanceFrontierBase : public DominatorBase {
515 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
516 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
518 DomSetMapType Frontiers;
520 DominanceFrontierBase(intptr_t ID, bool isPostDom)
521 : DominatorBase(ID, isPostDom) {}
523 virtual void releaseMemory() { Frontiers.clear(); }
525 // Accessor interface:
526 typedef DomSetMapType::iterator iterator;
527 typedef DomSetMapType::const_iterator const_iterator;
528 iterator begin() { return Frontiers.begin(); }
529 const_iterator begin() const { return Frontiers.begin(); }
530 iterator end() { return Frontiers.end(); }
531 const_iterator end() const { return Frontiers.end(); }
532 iterator find(BasicBlock *B) { return Frontiers.find(B); }
533 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
535 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
536 assert(find(BB) == end() && "Block already in DominanceFrontier!");
537 Frontiers.insert(std::make_pair(BB, frontier));
540 void addToFrontier(iterator I, BasicBlock *Node) {
541 assert(I != end() && "BB is not in DominanceFrontier!");
542 I->second.insert(Node);
545 void removeFromFrontier(iterator I, BasicBlock *Node) {
546 assert(I != end() && "BB is not in DominanceFrontier!");
547 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
548 I->second.erase(Node);
551 /// print - Convert to human readable form
553 virtual void print(std::ostream &OS, const Module* = 0) const;
554 void print(std::ostream *OS, const Module* M = 0) const {
555 if (OS) print(*OS, M);
561 //===-------------------------------------
562 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
563 /// used to compute a forward dominator frontiers.
565 class DominanceFrontier : public DominanceFrontierBase {
567 static char ID; // Pass ID, replacement for typeid
568 DominanceFrontier() :
569 DominanceFrontierBase((intptr_t)& ID, false) {}
571 BasicBlock *getRoot() const {
572 assert(Roots.size() == 1 && "Should always have entry node!");
576 virtual bool runOnFunction(Function &) {
578 DominatorTree &DT = getAnalysis<DominatorTree>();
579 Roots = DT.getRoots();
580 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
581 calculate(DT, DT[Roots[0]]);
585 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
586 AU.setPreservesAll();
587 AU.addRequired<DominatorTree>();
591 const DomSetType &calculate(const DominatorTree &DT,
592 const DomTreeNode *Node);
596 } // End llvm namespace