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
66 std::vector<DomTreeNode*> Children;
67 int DFSNumIn, DFSNumOut;
70 typedef std::vector<DomTreeNode*>::iterator iterator;
71 typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
73 iterator begin() { return Children.begin(); }
74 iterator end() { return Children.end(); }
75 const_iterator begin() const { return Children.begin(); }
76 const_iterator end() const { return Children.end(); }
78 inline BasicBlock *getBlock() const { return TheBB; }
79 inline DomTreeNode *getIDom() const { return IDom; }
80 inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
82 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
83 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
84 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
85 void setIDom(DomTreeNode *NewIDom);
87 // Return true if this node is dominated by other. Use this only if DFS info is valid.
88 bool DominatedBy(const DomTreeNode *other) const {
89 return this->DFSNumIn >= other->DFSNumIn &&
90 this->DFSNumOut <= other->DFSNumOut;
93 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
95 void assignDFSNumber(int num);
98 //===----------------------------------------------------------------------===//
99 /// DominatorTree - Calculate the immediate dominator tree for a function.
101 class DominatorTreeBase : public DominatorBase {
105 typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
106 DomTreeNodeMapType DomTreeNodes;
107 DomTreeNode *RootNode;
110 unsigned int SlowQueries;
111 // Information record used during immediate dominators computation.
115 BasicBlock *Label, *Parent, *Child, *Ancestor;
117 std::vector<BasicBlock*> Bucket;
119 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
122 std::map<BasicBlock*, BasicBlock*> IDoms;
124 // Vertex - Map the DFS number to the BasicBlock*
125 std::vector<BasicBlock*> Vertex;
127 // Info - Collection of information used during the computation of idoms.
128 std::map<BasicBlock*, InfoRec> Info;
131 DominatorTreeBase(intptr_t ID, bool isPostDom)
132 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
133 ~DominatorTreeBase() { reset(); }
135 virtual void releaseMemory() { reset(); }
137 /// getNode - return the (Post)DominatorTree node for the specified basic
138 /// block. This is the same as using operator[] on this class.
140 inline DomTreeNode *getNode(BasicBlock *BB) const {
141 DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
142 return (i != DomTreeNodes.end()) ? i->second : 0;
145 inline DomTreeNode *operator[](BasicBlock *BB) const {
149 /// getIDomBlock - return basic block BB's immediate dominator basic block.
151 BasicBlock *getIDomBlock(BasicBlock *BB) {
152 DomTreeNode *N = getNode(BB);
153 assert (N && "Missing dominator tree node");
154 DomTreeNode *I = N->getIDom();
155 assert (N && "Missing immediate dominator");
156 return I->getBlock();
159 /// getRootNode - This returns the entry node for the CFG of the function. If
160 /// this tree represents the post-dominance relations for a function, however,
161 /// this root may be a node with the block == NULL. This is the case when
162 /// there are multiple exit nodes from a particular function. Consumers of
163 /// post-dominance information must be capable of dealing with this
166 DomTreeNode *getRootNode() { return RootNode; }
167 const DomTreeNode *getRootNode() const { return RootNode; }
169 /// properlyDominates - Returns true iff this dominates N and this != N.
170 /// Note that this is not a constant time operation!
172 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
173 if (A == 0 || B == 0) return false;
174 return dominatedBySlowTreeWalk(A, B);
177 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
178 return properlyDominates(getNode(A), getNode(B));
181 bool dominatedBySlowTreeWalk(const DomTreeNode *A,
182 const DomTreeNode *B) const {
183 const DomTreeNode *IDom;
184 if (A == 0 || B == 0) return false;
185 while ((IDom = B->getIDom()) != 0 && IDom != A)
186 B = IDom; // Walk up the tree
190 void updateDFSNumbers();
192 /// isReachableFromEntry - Return true if A is dominated by the entry
193 /// block of the function containing it.
194 const bool isReachableFromEntry(BasicBlock* A);
196 /// dominates - Returns true iff this dominates N. Note that this is not a
197 /// constant time operation!
199 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
201 return true; // A node trivially dominates itself.
203 if (A == 0 || B == 0)
207 return B->DominatedBy(A);
209 // If we end up with too many slow queries, just update the
210 // DFS numbers on the theory that we are going to keep querying.
212 if (SlowQueries > 32) {
214 return B->DominatedBy(A);
217 return dominatedBySlowTreeWalk(A, B);
220 inline bool dominates(BasicBlock *A, BasicBlock *B) {
224 return dominates(getNode(A), getNode(B));
227 /// findNearestCommonDominator - Find nearest common dominator basic block
228 /// for basic block A and B. If there is no such block then return NULL.
229 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
231 // dominates - Return true if A dominates B. This performs the
232 // special checks necessary if A and B are in the same basic block.
233 bool dominates(Instruction *A, Instruction *B);
235 //===--------------------------------------------------------------------===//
236 // API to update (Post)DominatorTree information based on modifications to
239 /// addNewBlock - Add a new node to the dominator tree information. This
240 /// creates a new node as a child of DomBB dominator node,linking it into
241 /// the children list of the immediate dominator.
242 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
243 assert(getNode(BB) == 0 && "Block already in dominator tree!");
244 DomTreeNode *IDomNode = getNode(DomBB);
245 assert(IDomNode && "Not immediate dominator specified for block!");
246 DFSInfoValid = false;
247 return DomTreeNodes[BB] =
248 IDomNode->addChild(new DomTreeNode(BB, IDomNode));
251 /// changeImmediateDominator - This method is used to update the dominator
252 /// tree information when a node's immediate dominator changes.
254 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
255 assert(N && NewIDom && "Cannot change null node pointers!");
256 DFSInfoValid = false;
260 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
261 changeImmediateDominator(getNode(BB), getNode(NewBB));
264 /// removeNode - Removes a node from the dominator tree. Block must not
265 /// dominate any other blocks. Invalidates any node pointing to removed
267 void removeNode(BasicBlock *BB) {
268 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
269 DomTreeNodes.erase(BB);
272 /// print - Convert to human readable form
274 virtual void print(std::ostream &OS, const Module* = 0) const;
275 void print(std::ostream *OS, const Module* M = 0) const {
276 if (OS) print(*OS, M);
281 //===-------------------------------------
282 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
283 /// compute a normal dominator tree.
285 class DominatorTree : public DominatorTreeBase {
287 static char ID; // Pass ID, replacement for typeid
288 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
290 BasicBlock *getRoot() const {
291 assert(Roots.size() == 1 && "Should always have entry node!");
295 virtual bool runOnFunction(Function &F);
297 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
298 AU.setPreservesAll();
301 void calculate(Function& F);
302 DomTreeNode *getNodeForBlock(BasicBlock *BB);
303 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
304 void Compress(BasicBlock *V);
305 BasicBlock *Eval(BasicBlock *v);
306 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
307 inline BasicBlock *getIDom(BasicBlock *BB) const {
308 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
309 return I != IDoms.end() ? I->second : 0;
313 //===-------------------------------------
314 /// DominatorTree GraphTraits specialization so the DominatorTree can be
315 /// iterable by generic graph iterators.
317 template <> struct GraphTraits<DomTreeNode*> {
318 typedef DomTreeNode NodeType;
319 typedef NodeType::iterator ChildIteratorType;
321 static NodeType *getEntryNode(NodeType *N) {
324 static inline ChildIteratorType child_begin(NodeType* N) {
327 static inline ChildIteratorType child_end(NodeType* N) {
332 template <> struct GraphTraits<DominatorTree*>
333 : public GraphTraits<DomTreeNode*> {
334 static NodeType *getEntryNode(DominatorTree *DT) {
335 return DT->getRootNode();
340 //===-------------------------------------
341 /// ET-Forest Class - Class used to construct forwards and backwards
344 class ETForestBase : public DominatorBase {
346 ETForestBase(intptr_t ID, bool isPostDom)
347 : DominatorBase(ID, isPostDom), Nodes(),
348 DFSInfoValid(false), SlowQueries(0) {}
350 virtual void releaseMemory() { reset(); }
352 typedef std::map<BasicBlock*, ETNode*> ETMapType;
354 // FIXME : There is no need to make this interface public.
355 // Fix predicate simplifier.
356 void updateDFSNumbers();
358 /// dominates - Return true if A dominates B.
360 inline bool dominates(BasicBlock *A, BasicBlock *B) {
364 ETNode *NodeA = getNode(A);
365 ETNode *NodeB = getNode(B);
368 return NodeB->DominatedBy(NodeA);
370 // If we end up with too many slow queries, just update the
371 // DFS numbers on the theory that we are going to keep querying.
373 if (SlowQueries > 32) {
375 return NodeB->DominatedBy(NodeA);
377 return NodeB->DominatedBySlow(NodeA);
381 // dominates - Return true if A dominates B. This performs the
382 // special checks necessary if A and B are in the same basic block.
383 bool dominates(Instruction *A, Instruction *B);
385 /// properlyDominates - Return true if A dominates B and A != B.
387 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
388 return dominates(A, B) && A != B;
391 /// isReachableFromEntry - Return true if A is dominated by the entry
392 /// block of the function containing it.
393 const bool isReachableFromEntry(BasicBlock* A);
395 /// Return the nearest common dominator of A and B.
396 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
397 ETNode *NodeA = getNode(A);
398 ETNode *NodeB = getNode(B);
400 ETNode *Common = NodeA->NCA(NodeB);
403 return Common->getData<BasicBlock>();
406 /// Return the immediate dominator of A.
407 BasicBlock *getIDom(BasicBlock *A) const {
408 ETNode *NodeA = getNode(A);
409 if (!NodeA) return 0;
410 const ETNode *idom = NodeA->getFather();
411 return idom ? idom->getData<BasicBlock>() : 0;
414 void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
415 ETNode *NodeA = getNode(A);
417 const ETNode* son = NodeA->getSon();
420 children.push_back(son->getData<BasicBlock>());
422 const ETNode* brother = son->getBrother();
423 while (brother != son) {
424 children.push_back(brother->getData<BasicBlock>());
425 brother = brother->getBrother();
429 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
430 AU.setPreservesAll();
431 AU.addRequired<DominatorTree>();
433 //===--------------------------------------------------------------------===//
434 // API to update Forest information based on modifications
437 /// addNewBlock - Add a new block to the CFG, with the specified immediate
440 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
442 /// setImmediateDominator - Update the immediate dominator information to
443 /// change the current immediate dominator for the specified block
444 /// to another block. This method requires that BB for NewIDom
445 /// already have an ETNode, otherwise just use addNewBlock.
447 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
448 /// print - Convert to human readable form
450 virtual void print(std::ostream &OS, const Module* = 0) const;
451 void print(std::ostream *OS, const Module* M = 0) const {
452 if (OS) print(*OS, M);
456 /// getNode - return the (Post)DominatorTree node for the specified basic
457 /// block. This is the same as using operator[] on this class.
459 inline ETNode *getNode(BasicBlock *BB) const {
460 ETMapType::const_iterator i = Nodes.find(BB);
461 return (i != Nodes.end()) ? i->second : 0;
464 inline ETNode *operator[](BasicBlock *BB) const {
471 unsigned int SlowQueries;
475 //==-------------------------------------
476 /// ETForest Class - Concrete subclass of ETForestBase that is used to
477 /// compute a forwards ET-Forest.
479 class ETForest : public ETForestBase {
481 static char ID; // Pass identification, replacement for typeid
483 ETForest() : ETForestBase((intptr_t)&ID, false) {}
485 BasicBlock *getRoot() const {
486 assert(Roots.size() == 1 && "Should always have entry node!");
490 virtual bool runOnFunction(Function &F) {
491 reset(); // Reset from the last time we were run...
492 DominatorTree &DT = getAnalysis<DominatorTree>();
493 Roots = DT.getRoots();
498 void calculate(const DominatorTree &DT);
499 // FIXME : There is no need to make getNodeForBlock public. Fix
500 // predicate simplifier.
501 ETNode *getNodeForBlock(BasicBlock *BB);
504 //===----------------------------------------------------------------------===//
505 /// DominanceFrontierBase - Common base class for computing forward and inverse
506 /// dominance frontiers for a function.
508 class DominanceFrontierBase : public DominatorBase {
510 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
511 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
513 DomSetMapType Frontiers;
515 DominanceFrontierBase(intptr_t ID, bool isPostDom)
516 : DominatorBase(ID, isPostDom) {}
518 virtual void releaseMemory() { Frontiers.clear(); }
520 // Accessor interface:
521 typedef DomSetMapType::iterator iterator;
522 typedef DomSetMapType::const_iterator const_iterator;
523 iterator begin() { return Frontiers.begin(); }
524 const_iterator begin() const { return Frontiers.begin(); }
525 iterator end() { return Frontiers.end(); }
526 const_iterator end() const { return Frontiers.end(); }
527 iterator find(BasicBlock *B) { return Frontiers.find(B); }
528 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
530 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
531 assert(find(BB) == end() && "Block already in DominanceFrontier!");
532 Frontiers.insert(std::make_pair(BB, frontier));
535 void addToFrontier(iterator I, BasicBlock *Node) {
536 assert(I != end() && "BB is not in DominanceFrontier!");
537 I->second.insert(Node);
540 void removeFromFrontier(iterator I, BasicBlock *Node) {
541 assert(I != end() && "BB is not in DominanceFrontier!");
542 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
543 I->second.erase(Node);
546 /// print - Convert to human readable form
548 virtual void print(std::ostream &OS, const Module* = 0) const;
549 void print(std::ostream *OS, const Module* M = 0) const {
550 if (OS) print(*OS, M);
556 //===-------------------------------------
557 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
558 /// used to compute a forward dominator frontiers.
560 class DominanceFrontier : public DominanceFrontierBase {
562 static char ID; // Pass ID, replacement for typeid
563 DominanceFrontier() :
564 DominanceFrontierBase((intptr_t)& ID, false) {}
566 BasicBlock *getRoot() const {
567 assert(Roots.size() == 1 && "Should always have entry node!");
571 virtual bool runOnFunction(Function &) {
573 DominatorTree &DT = getAnalysis<DominatorTree>();
574 Roots = DT.getRoots();
575 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
576 calculate(DT, DT[Roots[0]]);
580 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
581 AU.setPreservesAll();
582 AU.addRequired<DominatorTree>();
586 const DomSetType &calculate(const DominatorTree &DT,
587 const DomTreeNode *Node);
591 } // End llvm namespace