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;
68 typedef std::vector<DomTreeNode*>::iterator iterator;
69 typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
71 iterator begin() { return Children.begin(); }
72 iterator end() { return Children.end(); }
73 const_iterator begin() const { return Children.begin(); }
74 const_iterator end() const { return Children.end(); }
76 inline BasicBlock *getBlock() const { return TheBB; }
77 inline DomTreeNode *getIDom() const { return IDom; }
78 inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
80 /// properlyDominates - Returns true iff this dominates N and this != N.
81 /// Note that this is not a constant time operation!
83 bool properlyDominates(const DomTreeNode *N) const {
84 const DomTreeNode *IDom;
85 if (this == 0 || N == 0) return false;
86 while ((IDom = N->getIDom()) != 0 && IDom != this)
87 N = IDom; // Walk up the tree
91 /// dominates - Returns true iff this dominates N. Note that this is not a
92 /// constant time operation!
94 inline bool dominates(const DomTreeNode *N) const {
95 if (N == this) return true; // A node trivially dominates itself.
96 return properlyDominates(N);
99 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom) : TheBB(BB), IDom(iDom) {}
100 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
101 void setIDom(DomTreeNode *NewIDom);
104 //===----------------------------------------------------------------------===//
105 /// DominatorTree - Calculate the immediate dominator tree for a function.
107 class DominatorTreeBase : public DominatorBase {
110 std::map<BasicBlock*, DomTreeNode*> DomTreeNodes;
112 typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
114 DomTreeNode *RootNode;
116 // Information record used during immediate dominators computation.
120 BasicBlock *Label, *Parent, *Child, *Ancestor;
122 std::vector<BasicBlock*> Bucket;
124 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
127 std::map<BasicBlock*, BasicBlock*> IDoms;
129 // Vertex - Map the DFS number to the BasicBlock*
130 std::vector<BasicBlock*> Vertex;
132 // Info - Collection of information used during the computation of idoms.
133 std::map<BasicBlock*, InfoRec> Info;
136 DominatorTreeBase(intptr_t ID, bool isPostDom)
137 : DominatorBase(ID, isPostDom) {}
138 ~DominatorTreeBase() { reset(); }
140 virtual void releaseMemory() { reset(); }
142 /// getNode - return the (Post)DominatorTree node for the specified basic
143 /// block. This is the same as using operator[] on this class.
145 inline DomTreeNode *getNode(BasicBlock *BB) const {
146 DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
147 return (i != DomTreeNodes.end()) ? i->second : 0;
150 inline DomTreeNode *operator[](BasicBlock *BB) const {
154 /// getRootNode - This returns the entry node for the CFG of the function. If
155 /// this tree represents the post-dominance relations for a function, however,
156 /// this root may be a node with the block == NULL. This is the case when
157 /// there are multiple exit nodes from a particular function. Consumers of
158 /// post-dominance information must be capable of dealing with this
161 DomTreeNode *getRootNode() { return RootNode; }
162 const DomTreeNode *getRootNode() const { return RootNode; }
164 //===--------------------------------------------------------------------===//
165 // API to update (Post)DominatorTree information based on modifications to
168 /// addNewBlock - Add a new node to the dominator tree information. This
169 /// creates a new node as a child of DomBB dominator node,linking it into
170 /// the children list of the immediate dominator.
171 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
172 assert(getNode(BB) == 0 && "Block already in dominator tree!");
173 DomTreeNode *IDomNode = getNode(DomBB);
174 assert(IDomNode && "Not immediate dominator specified for block!");
175 return DomTreeNodes[BB] = IDomNode->addChild(new DomTreeNode(BB, IDomNode));
178 /// changeImmediateDominator - This method is used to update the dominator
179 /// tree information when a node's immediate dominator changes.
181 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
182 assert(N && NewIDom && "Cannot change null node pointers!");
186 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
187 changeImmediateDominator(getNode(BB), getNode(NewBB));
191 /// removeNode - Removes a node from the dominator tree. Block must not
192 /// dominate any other blocks. Invalidates any node pointing to removed
194 void removeNode(BasicBlock *BB) {
195 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
196 DomTreeNodes.erase(BB);
199 /// print - Convert to human readable form
201 virtual void print(std::ostream &OS, const Module* = 0) const;
202 void print(std::ostream *OS, const Module* M = 0) const {
203 if (OS) print(*OS, M);
208 //===-------------------------------------
209 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
210 /// compute a normal dominator tree.
212 class DominatorTree : public DominatorTreeBase {
214 static char ID; // Pass ID, replacement for typeid
215 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
217 BasicBlock *getRoot() const {
218 assert(Roots.size() == 1 && "Should always have entry node!");
222 virtual bool runOnFunction(Function &F);
224 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
225 AU.setPreservesAll();
228 void calculate(Function& F);
229 DomTreeNode *getNodeForBlock(BasicBlock *BB);
230 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
231 void Compress(BasicBlock *V);
232 BasicBlock *Eval(BasicBlock *v);
233 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
234 inline BasicBlock *getIDom(BasicBlock *BB) const {
235 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
236 return I != IDoms.end() ? I->second : 0;
240 //===-------------------------------------
241 /// DominatorTree GraphTraits specialization so the DominatorTree can be
242 /// iterable by generic graph iterators.
244 template <> struct GraphTraits<DomTreeNode*> {
245 typedef DomTreeNode NodeType;
246 typedef NodeType::iterator ChildIteratorType;
248 static NodeType *getEntryNode(NodeType *N) {
251 static inline ChildIteratorType child_begin(NodeType* N) {
254 static inline ChildIteratorType child_end(NodeType* N) {
259 template <> struct GraphTraits<DominatorTree*>
260 : public GraphTraits<DomTreeNode*> {
261 static NodeType *getEntryNode(DominatorTree *DT) {
262 return DT->getRootNode();
267 //===-------------------------------------
268 /// ET-Forest Class - Class used to construct forwards and backwards
271 class ETForestBase : public DominatorBase {
273 ETForestBase(intptr_t ID, bool isPostDom)
274 : DominatorBase(ID, isPostDom), Nodes(),
275 DFSInfoValid(false), SlowQueries(0) {}
277 virtual void releaseMemory() { reset(); }
279 typedef std::map<BasicBlock*, ETNode*> ETMapType;
281 // FIXME : There is no need to make this interface public.
282 // Fix predicate simplifier.
283 void updateDFSNumbers();
285 /// dominates - Return true if A dominates B.
287 inline bool dominates(BasicBlock *A, BasicBlock *B) {
291 ETNode *NodeA = getNode(A);
292 ETNode *NodeB = getNode(B);
295 return NodeB->DominatedBy(NodeA);
297 // If we end up with too many slow queries, just update the
298 // DFS numbers on the theory that we are going to keep querying.
300 if (SlowQueries > 32) {
302 return NodeB->DominatedBy(NodeA);
304 return NodeB->DominatedBySlow(NodeA);
308 // dominates - Return true if A dominates B. This performs the
309 // special checks necessary if A and B are in the same basic block.
310 bool dominates(Instruction *A, Instruction *B);
312 /// properlyDominates - Return true if A dominates B and A != B.
314 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
315 return dominates(A, B) && A != B;
318 /// isReachableFromEntry - Return true if A is dominated by the entry
319 /// block of the function containing it.
320 const bool isReachableFromEntry(BasicBlock* A);
322 /// Return the nearest common dominator of A and B.
323 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
324 ETNode *NodeA = getNode(A);
325 ETNode *NodeB = getNode(B);
327 ETNode *Common = NodeA->NCA(NodeB);
330 return Common->getData<BasicBlock>();
333 /// Return the immediate dominator of A.
334 BasicBlock *getIDom(BasicBlock *A) const {
335 ETNode *NodeA = getNode(A);
336 if (!NodeA) return 0;
337 const ETNode *idom = NodeA->getFather();
338 return idom ? idom->getData<BasicBlock>() : 0;
341 void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
342 ETNode *NodeA = getNode(A);
344 const ETNode* son = NodeA->getSon();
347 children.push_back(son->getData<BasicBlock>());
349 const ETNode* brother = son->getBrother();
350 while (brother != son) {
351 children.push_back(brother->getData<BasicBlock>());
352 brother = brother->getBrother();
356 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
357 AU.setPreservesAll();
358 AU.addRequired<DominatorTree>();
360 //===--------------------------------------------------------------------===//
361 // API to update Forest information based on modifications
364 /// addNewBlock - Add a new block to the CFG, with the specified immediate
367 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
369 /// setImmediateDominator - Update the immediate dominator information to
370 /// change the current immediate dominator for the specified block
371 /// to another block. This method requires that BB for NewIDom
372 /// already have an ETNode, otherwise just use addNewBlock.
374 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
375 /// print - Convert to human readable form
377 virtual void print(std::ostream &OS, const Module* = 0) const;
378 void print(std::ostream *OS, const Module* M = 0) const {
379 if (OS) print(*OS, M);
383 /// getNode - return the (Post)DominatorTree node for the specified basic
384 /// block. This is the same as using operator[] on this class.
386 inline ETNode *getNode(BasicBlock *BB) const {
387 ETMapType::const_iterator i = Nodes.find(BB);
388 return (i != Nodes.end()) ? i->second : 0;
391 inline ETNode *operator[](BasicBlock *BB) const {
398 unsigned int SlowQueries;
402 //==-------------------------------------
403 /// ETForest Class - Concrete subclass of ETForestBase that is used to
404 /// compute a forwards ET-Forest.
406 class ETForest : public ETForestBase {
408 static char ID; // Pass identification, replacement for typeid
410 ETForest() : ETForestBase((intptr_t)&ID, false) {}
412 BasicBlock *getRoot() const {
413 assert(Roots.size() == 1 && "Should always have entry node!");
417 virtual bool runOnFunction(Function &F) {
418 reset(); // Reset from the last time we were run...
419 DominatorTree &DT = getAnalysis<DominatorTree>();
420 Roots = DT.getRoots();
425 void calculate(const DominatorTree &DT);
426 // FIXME : There is no need to make getNodeForBlock public. Fix
427 // predicate simplifier.
428 ETNode *getNodeForBlock(BasicBlock *BB);
431 //===----------------------------------------------------------------------===//
432 /// DominanceFrontierBase - Common base class for computing forward and inverse
433 /// dominance frontiers for a function.
435 class DominanceFrontierBase : public DominatorBase {
437 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
438 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
440 DomSetMapType Frontiers;
442 DominanceFrontierBase(intptr_t ID, bool isPostDom)
443 : DominatorBase(ID, isPostDom) {}
445 virtual void releaseMemory() { Frontiers.clear(); }
447 // Accessor interface:
448 typedef DomSetMapType::iterator iterator;
449 typedef DomSetMapType::const_iterator const_iterator;
450 iterator begin() { return Frontiers.begin(); }
451 const_iterator begin() const { return Frontiers.begin(); }
452 iterator end() { return Frontiers.end(); }
453 const_iterator end() const { return Frontiers.end(); }
454 iterator find(BasicBlock *B) { return Frontiers.find(B); }
455 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
457 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
458 assert(find(BB) == end() && "Block already in DominanceFrontier!");
459 Frontiers.insert(std::make_pair(BB, frontier));
462 void addToFrontier(iterator I, BasicBlock *Node) {
463 assert(I != end() && "BB is not in DominanceFrontier!");
464 I->second.insert(Node);
467 void removeFromFrontier(iterator I, BasicBlock *Node) {
468 assert(I != end() && "BB is not in DominanceFrontier!");
469 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
470 I->second.erase(Node);
473 /// print - Convert to human readable form
475 virtual void print(std::ostream &OS, const Module* = 0) const;
476 void print(std::ostream *OS, const Module* M = 0) const {
477 if (OS) print(*OS, M);
483 //===-------------------------------------
484 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
485 /// used to compute a forward dominator frontiers.
487 class DominanceFrontier : public DominanceFrontierBase {
489 static char ID; // Pass ID, replacement for typeid
490 DominanceFrontier() :
491 DominanceFrontierBase((intptr_t)& ID, false) {}
493 BasicBlock *getRoot() const {
494 assert(Roots.size() == 1 && "Should always have entry node!");
498 virtual bool runOnFunction(Function &) {
500 DominatorTree &DT = getAnalysis<DominatorTree>();
501 Roots = DT.getRoots();
502 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
503 calculate(DT, DT[Roots[0]]);
507 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
508 AU.setPreservesAll();
509 AU.addRequired<DominatorTree>();
513 const DomSetType &calculate(const DominatorTree &DT,
514 const DomTreeNode *Node);
518 } // End llvm namespace