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 the ImmediateDominator as an explicit tree
13 // 2. ETForest: Efficient data structure for dominance comparisons and
14 // nearest-common-ancestor queries.
15 // 3. DominanceFrontier: Calculate and hold the dominance frontier for a
18 // These data structures are listed in increasing order of complexity. It
19 // takes longer to calculate the dominator frontier, for example, than the
20 // ImmediateDominator mapping.
22 //===----------------------------------------------------------------------===//
24 #ifndef LLVM_ANALYSIS_DOMINATORS_H
25 #define LLVM_ANALYSIS_DOMINATORS_H
27 #include "llvm/Analysis/ET-Forest.h"
28 #include "llvm/Pass.h"
35 template <typename GraphType> struct GraphTraits;
37 //===----------------------------------------------------------------------===//
38 /// DominatorBase - Base class that other, more interesting dominator analyses
41 class DominatorBase : public FunctionPass {
43 std::vector<BasicBlock*> Roots;
44 const bool IsPostDominators;
45 inline DominatorBase(intptr_t ID, bool isPostDom) :
46 FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
49 /// getRoots - Return the root blocks of the current CFG. This may include
50 /// multiple blocks if we are computing post dominators. For forward
51 /// dominators, this will always be a single block (the entry node).
53 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
55 /// isPostDominator - Returns true if analysis based of postdoms
57 bool isPostDominator() const { return IsPostDominators; }
60 //===----------------------------------------------------------------------===//
61 /// DominatorTree - Calculate the immediate dominator tree for a function.
63 class DominatorTreeBase : public DominatorBase {
67 std::map<BasicBlock*, Node*> Nodes;
69 typedef std::map<BasicBlock*, Node*> NodeMapType;
76 BasicBlock *Label, *Parent, *Child, *Ancestor;
78 std::vector<BasicBlock*> Bucket;
80 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
83 std::map<BasicBlock*, BasicBlock*> IDoms;
85 // Vertex - Map the DFS number to the BasicBlock*
86 std::vector<BasicBlock*> Vertex;
88 // Info - Collection of information used during the computation of idoms.
89 std::map<BasicBlock*, InfoRec> Info;
93 friend class DominatorTree;
94 friend struct PostDominatorTree;
95 friend class DominatorTreeBase;
98 std::vector<Node*> Children;
100 typedef std::vector<Node*>::iterator iterator;
101 typedef std::vector<Node*>::const_iterator const_iterator;
103 iterator begin() { return Children.begin(); }
104 iterator end() { return Children.end(); }
105 const_iterator begin() const { return Children.begin(); }
106 const_iterator end() const { return Children.end(); }
108 inline BasicBlock *getBlock() const { return TheBB; }
109 inline Node *getIDom() const { return IDom; }
110 inline const std::vector<Node*> &getChildren() const { return Children; }
112 /// properlyDominates - Returns true iff this dominates N and this != N.
113 /// Note that this is not a constant time operation!
115 bool properlyDominates(const Node *N) const {
117 if (this == 0 || N == 0) return false;
118 while ((IDom = N->getIDom()) != 0 && IDom != this)
119 N = IDom; // Walk up the tree
123 /// dominates - Returns true iff this dominates N. Note that this is not a
124 /// constant time operation!
126 inline bool dominates(const Node *N) const {
127 if (N == this) return true; // A node trivially dominates itself.
128 return properlyDominates(N);
132 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
133 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
135 void setIDom(Node *NewIDom);
139 DominatorTreeBase(intptr_t ID, bool isPostDom)
140 : DominatorBase(ID, isPostDom) {}
141 ~DominatorTreeBase() { reset(); }
143 virtual void releaseMemory() { reset(); }
145 /// getNode - return the (Post)DominatorTree node for the specified basic
146 /// block. This is the same as using operator[] on this class.
148 inline Node *getNode(BasicBlock *BB) const {
149 NodeMapType::const_iterator i = Nodes.find(BB);
150 return (i != Nodes.end()) ? i->second : 0;
153 inline Node *operator[](BasicBlock *BB) const {
157 /// getRootNode - This returns the entry node for the CFG of the function. If
158 /// this tree represents the post-dominance relations for a function, however,
159 /// this root may be a node with the block == NULL. This is the case when
160 /// there are multiple exit nodes from a particular function. Consumers of
161 /// post-dominance information must be capable of dealing with this
164 Node *getRootNode() { return RootNode; }
165 const Node *getRootNode() const { return RootNode; }
167 //===--------------------------------------------------------------------===//
168 // API to update (Post)DominatorTree information based on modifications to
171 /// createNewNode - Add a new node to the dominator tree information. This
172 /// creates a new node as a child of IDomNode, linking it into the children
173 /// list of the immediate dominator.
175 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
176 assert(getNode(BB) == 0 && "Block already in dominator tree!");
177 assert(IDomNode && "Not immediate dominator specified for block!");
178 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
181 /// changeImmediateDominator - This method is used to update the dominator
182 /// tree information when a node's immediate dominator changes.
184 void changeImmediateDominator(Node *N, Node *NewIDom) {
185 assert(N && NewIDom && "Cannot change null node pointers!");
189 /// removeNode - Removes a node from the dominator tree. Block must not
190 /// dominate any other blocks. Invalidates any node pointing to removed
192 void removeNode(BasicBlock *BB) {
193 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
197 /// print - Convert to human readable form
199 virtual void print(std::ostream &OS, const Module* = 0) const;
200 void print(std::ostream *OS, const Module* M = 0) const {
201 if (OS) print(*OS, M);
205 //===-------------------------------------
206 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
207 /// compute a normal dominator tree.
209 class DominatorTree : public DominatorTreeBase {
211 static const int ID; // Pass ID, replacement for typeid
212 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
214 BasicBlock *getRoot() const {
215 assert(Roots.size() == 1 && "Should always have entry node!");
219 virtual bool runOnFunction(Function &F);
221 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222 AU.setPreservesAll();
225 void calculate(Function& F);
226 Node *getNodeForBlock(BasicBlock *BB);
227 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
228 void Compress(BasicBlock *V, InfoRec &VInfo);
229 BasicBlock *Eval(BasicBlock *v);
230 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
231 inline BasicBlock *getIDom(BasicBlock *BB) const {
232 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
233 return I != IDoms.end() ? I->second : 0;
237 //===-------------------------------------
238 /// DominatorTree GraphTraits specialization so the DominatorTree can be
239 /// iterable by generic graph iterators.
241 template <> struct GraphTraits<DominatorTree::Node*> {
242 typedef DominatorTree::Node NodeType;
243 typedef NodeType::iterator ChildIteratorType;
245 static NodeType *getEntryNode(NodeType *N) {
248 static inline ChildIteratorType child_begin(NodeType* N) {
251 static inline ChildIteratorType child_end(NodeType* N) {
256 template <> struct GraphTraits<DominatorTree*>
257 : public GraphTraits<DominatorTree::Node*> {
258 static NodeType *getEntryNode(DominatorTree *DT) {
259 return DT->getRootNode();
264 //===-------------------------------------
265 /// ET-Forest Class - Class used to construct forwards and backwards
268 class ETForestBase : public DominatorBase {
270 ETForestBase(intptr_t ID, bool isPostDom)
271 : DominatorBase(ID, isPostDom), Nodes(),
272 DFSInfoValid(false), SlowQueries(0) {}
274 virtual void releaseMemory() { reset(); }
276 typedef std::map<BasicBlock*, ETNode*> ETMapType;
278 void updateDFSNumbers();
280 /// dominates - Return true if A dominates B.
282 inline bool dominates(BasicBlock *A, BasicBlock *B) {
286 ETNode *NodeA = getNode(A);
287 ETNode *NodeB = getNode(B);
290 return NodeB->DominatedBy(NodeA);
292 // If we end up with too many slow queries, just update the
293 // DFS numbers on the theory that we are going to keep querying.
295 if (SlowQueries > 32) {
297 return NodeB->DominatedBy(NodeA);
299 return NodeB->DominatedBySlow(NodeA);
303 // dominates - Return true if A dominates B. This performs the
304 // special checks necessary if A and B are in the same basic block.
305 bool dominates(Instruction *A, Instruction *B);
307 /// properlyDominates - Return true if A dominates B and A != B.
309 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
310 return dominates(A, B) && A != B;
313 /// isReachableFromEntry - Return true if A is dominated by the entry
314 /// block of the function containing it.
315 const bool isReachableFromEntry(BasicBlock* A);
317 /// Return the nearest common dominator of A and B.
318 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
319 ETNode *NodeA = getNode(A);
320 ETNode *NodeB = getNode(B);
322 ETNode *Common = NodeA->NCA(NodeB);
325 return Common->getData<BasicBlock>();
328 /// Return the immediate dominator of A.
329 BasicBlock *getIDom(BasicBlock *A) const {
330 ETNode *NodeA = getNode(A);
331 if (!NodeA) return 0;
332 const ETNode *idom = NodeA->getFather();
333 return idom ? idom->getData<BasicBlock>() : 0;
336 void getChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
337 ETNode *NodeA = getNode(A);
339 const ETNode* son = NodeA->getSon();
342 children.push_back(son->getData<BasicBlock>());
344 const ETNode* brother = son->getBrother();
345 while (brother != son) {
346 children.push_back(brother->getData<BasicBlock>());
347 brother = brother->getBrother();
351 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
352 AU.setPreservesAll();
353 AU.addRequired<DominatorTree>();
355 //===--------------------------------------------------------------------===//
356 // API to update Forest information based on modifications
359 /// addNewBlock - Add a new block to the CFG, with the specified immediate
362 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
364 /// setImmediateDominator - Update the immediate dominator information to
365 /// change the current immediate dominator for the specified block
366 /// to another block. This method requires that BB for NewIDom
367 /// already have an ETNode, otherwise just use addNewBlock.
369 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
370 /// print - Convert to human readable form
372 virtual void print(std::ostream &OS, const Module* = 0) const;
373 void print(std::ostream *OS, const Module* M = 0) const {
374 if (OS) print(*OS, M);
377 /// getNode - return the (Post)DominatorTree node for the specified basic
378 /// block. This is the same as using operator[] on this class.
380 inline ETNode *getNode(BasicBlock *BB) const {
381 ETMapType::const_iterator i = Nodes.find(BB);
382 return (i != Nodes.end()) ? i->second : 0;
385 inline ETNode *operator[](BasicBlock *BB) const {
392 unsigned int SlowQueries;
396 //==-------------------------------------
397 /// ETForest Class - Concrete subclass of ETForestBase that is used to
398 /// compute a forwards ET-Forest.
400 class ETForest : public ETForestBase {
402 static const int ID; // Pass identifcation, replacement for typeid
404 ETForest() : ETForestBase((intptr_t)&ID, false) {}
406 BasicBlock *getRoot() const {
407 assert(Roots.size() == 1 && "Should always have entry node!");
411 virtual bool runOnFunction(Function &F) {
412 reset(); // Reset from the last time we were run...
413 DominatorTree &DT = getAnalysis<DominatorTree>();
414 Roots = DT.getRoots();
419 void calculate(const DominatorTree &DT);
420 ETNode *getNodeForBlock(BasicBlock *BB);
423 //===----------------------------------------------------------------------===//
424 /// DominanceFrontierBase - Common base class for computing forward and inverse
425 /// dominance frontiers for a function.
427 class DominanceFrontierBase : public DominatorBase {
429 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
430 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
432 DomSetMapType Frontiers;
434 DominanceFrontierBase(intptr_t ID, bool isPostDom)
435 : DominatorBase(ID, isPostDom) {}
437 virtual void releaseMemory() { Frontiers.clear(); }
439 // Accessor interface:
440 typedef DomSetMapType::iterator iterator;
441 typedef DomSetMapType::const_iterator const_iterator;
442 iterator begin() { return Frontiers.begin(); }
443 const_iterator begin() const { return Frontiers.begin(); }
444 iterator end() { return Frontiers.end(); }
445 const_iterator end() const { return Frontiers.end(); }
446 iterator find(BasicBlock *B) { return Frontiers.find(B); }
447 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
449 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
450 assert(find(BB) == end() && "Block already in DominanceFrontier!");
451 Frontiers.insert(std::make_pair(BB, frontier));
454 void addToFrontier(iterator I, BasicBlock *Node) {
455 assert(I != end() && "BB is not in DominanceFrontier!");
456 I->second.insert(Node);
459 void removeFromFrontier(iterator I, BasicBlock *Node) {
460 assert(I != end() && "BB is not in DominanceFrontier!");
461 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
462 I->second.erase(Node);
465 /// print - Convert to human readable form
467 virtual void print(std::ostream &OS, const Module* = 0) const;
468 void print(std::ostream *OS, const Module* M = 0) const {
469 if (OS) print(*OS, M);
474 //===-------------------------------------
475 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
476 /// used to compute a forward dominator frontiers.
478 class DominanceFrontier : public DominanceFrontierBase {
480 static const int ID; // Pass ID, replacement for typeid
481 DominanceFrontier() :
482 DominanceFrontierBase((intptr_t)& ID, false) {}
484 BasicBlock *getRoot() const {
485 assert(Roots.size() == 1 && "Should always have entry node!");
489 virtual bool runOnFunction(Function &) {
491 DominatorTree &DT = getAnalysis<DominatorTree>();
492 Roots = DT.getRoots();
493 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
494 calculate(DT, DT[Roots[0]]);
498 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
499 AU.setPreservesAll();
500 AU.addRequired<DominatorTree>();
503 const DomSetType &calculate(const DominatorTree &DT,
504 const DominatorTree::Node *Node);
508 } // End llvm namespace