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;
46 inline DominatorBase(bool isPostDom) : 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; }
59 //===----------------------------------------------------------------------===//
60 /// DominatorTree - Calculate the immediate dominator tree for a function.
62 class DominatorTreeBase : public DominatorBase {
66 std::map<BasicBlock*, Node*> Nodes;
68 typedef std::map<BasicBlock*, Node*> NodeMapType;
75 BasicBlock *Label, *Parent, *Child, *Ancestor;
77 std::vector<BasicBlock*> Bucket;
79 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
82 std::map<BasicBlock*, BasicBlock*> IDoms;
84 // Vertex - Map the DFS number to the BasicBlock*
85 std::vector<BasicBlock*> Vertex;
87 // Info - Collection of information used during the computation of idoms.
88 std::map<BasicBlock*, InfoRec> Info;
92 friend class DominatorTree;
93 friend struct PostDominatorTree;
94 friend class DominatorTreeBase;
97 std::vector<Node*> Children;
99 typedef std::vector<Node*>::iterator iterator;
100 typedef std::vector<Node*>::const_iterator const_iterator;
102 iterator begin() { return Children.begin(); }
103 iterator end() { return Children.end(); }
104 const_iterator begin() const { return Children.begin(); }
105 const_iterator end() const { return Children.end(); }
107 inline BasicBlock *getBlock() const { return TheBB; }
108 inline Node *getIDom() const { return IDom; }
109 inline const std::vector<Node*> &getChildren() const { return Children; }
111 /// properlyDominates - Returns true iff this dominates N and this != N.
112 /// Note that this is not a constant time operation!
114 bool properlyDominates(const Node *N) const {
116 if (this == 0 || N == 0) return false;
117 while ((IDom = N->getIDom()) != 0 && IDom != this)
118 N = IDom; // Walk up the tree
122 /// dominates - Returns true iff this dominates N. Note that this is not a
123 /// constant time operation!
125 inline bool dominates(const Node *N) const {
126 if (N == this) return true; // A node trivially dominates itself.
127 return properlyDominates(N);
131 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
132 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
134 void setIDom(Node *NewIDom);
138 DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
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 Node *getNode(BasicBlock *BB) const {
147 NodeMapType::const_iterator i = Nodes.find(BB);
148 return (i != Nodes.end()) ? i->second : 0;
151 inline Node *operator[](BasicBlock *BB) const {
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 Node *getRootNode() { return RootNode; }
163 const Node *getRootNode() const { return RootNode; }
165 //===--------------------------------------------------------------------===//
166 // API to update (Post)DominatorTree information based on modifications to
169 /// createNewNode - Add a new node to the dominator tree information. This
170 /// creates a new node as a child of IDomNode, linking it into the children
171 /// list of the immediate dominator.
173 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
174 assert(getNode(BB) == 0 && "Block already in dominator tree!");
175 assert(IDomNode && "Not immediate dominator specified for block!");
176 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
179 /// changeImmediateDominator - This method is used to update the dominator
180 /// tree information when a node's immediate dominator changes.
182 void changeImmediateDominator(Node *N, Node *NewIDom) {
183 assert(N && NewIDom && "Cannot change null node pointers!");
187 /// removeNode - Removes a node from the dominator tree. Block must not
188 /// dominate any other blocks. Invalidates any node pointing to removed
190 void removeNode(BasicBlock *BB) {
191 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
195 /// print - Convert to human readable form
197 virtual void print(std::ostream &OS, const Module* = 0) const;
198 void print(std::ostream *OS, const Module* M = 0) const {
199 if (OS) print(*OS, M);
203 //===-------------------------------------
204 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
205 /// compute a normal dominator tree.
207 class DominatorTree : public DominatorTreeBase {
209 DominatorTree() : DominatorTreeBase(false) {}
211 BasicBlock *getRoot() const {
212 assert(Roots.size() == 1 && "Should always have entry node!");
216 virtual bool runOnFunction(Function &F);
218 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
219 AU.setPreservesAll();
222 void calculate(Function& F);
223 Node *getNodeForBlock(BasicBlock *BB);
224 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
225 void Compress(BasicBlock *V, InfoRec &VInfo);
226 BasicBlock *Eval(BasicBlock *v);
227 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
228 inline BasicBlock *getIDom(BasicBlock *BB) const {
229 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
230 return I != IDoms.end() ? I->second : 0;
234 //===-------------------------------------
235 /// DominatorTree GraphTraits specialization so the DominatorTree can be
236 /// iterable by generic graph iterators.
238 template <> struct GraphTraits<DominatorTree::Node*> {
239 typedef DominatorTree::Node NodeType;
240 typedef NodeType::iterator ChildIteratorType;
242 static NodeType *getEntryNode(NodeType *N) {
245 static inline ChildIteratorType child_begin(NodeType* N) {
248 static inline ChildIteratorType child_end(NodeType* N) {
253 template <> struct GraphTraits<DominatorTree*>
254 : public GraphTraits<DominatorTree::Node*> {
255 static NodeType *getEntryNode(DominatorTree *DT) {
256 return DT->getRootNode();
261 //===-------------------------------------
262 /// ET-Forest Class - Class used to construct forwards and backwards
265 class ETForestBase : public DominatorBase {
267 ETForestBase(bool isPostDom) : DominatorBase(isPostDom), Nodes(),
268 DFSInfoValid(false), SlowQueries(0) {}
270 virtual void releaseMemory() { reset(); }
272 typedef std::map<BasicBlock*, ETNode*> ETMapType;
274 void updateDFSNumbers();
276 /// dominates - Return true if A dominates B.
278 inline bool dominates(BasicBlock *A, BasicBlock *B) {
282 ETNode *NodeA = getNode(A);
283 ETNode *NodeB = getNode(B);
286 return NodeB->DominatedBy(NodeA);
288 // If we end up with too many slow queries, just update the
289 // DFS numbers on the theory that we are going to keep querying.
291 if (SlowQueries > 32) {
293 return NodeB->DominatedBy(NodeA);
295 return NodeB->DominatedBySlow(NodeA);
299 // dominates - Return true if A dominates B. This performs the
300 // special checks necessary if A and B are in the same basic block.
301 bool dominates(Instruction *A, Instruction *B);
303 /// properlyDominates - Return true if A dominates B and A != B.
305 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
306 return dominates(A, B) && A != B;
309 /// isReachableFromEntry - Return true if A is dominated by the entry
310 /// block of the function containing it.
311 const bool isReachableFromEntry(BasicBlock* A);
313 /// Return the nearest common dominator of A and B.
314 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
315 ETNode *NodeA = getNode(A);
316 ETNode *NodeB = getNode(B);
318 ETNode *Common = NodeA->NCA(NodeB);
321 return Common->getData<BasicBlock>();
324 /// Return the immediate dominator of A.
325 BasicBlock *getIDom(BasicBlock *A) const {
326 ETNode *NodeA = getNode(A);
327 if (!NodeA) return 0;
328 const ETNode *idom = NodeA->getFather();
329 return idom ? idom->getData<BasicBlock>() : 0;
332 void getChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
333 ETNode *NodeA = getNode(A);
335 const ETNode* son = NodeA->getSon();
338 children.push_back(son->getData<BasicBlock>());
340 const ETNode* brother = son->getBrother();
341 while (brother != son) {
342 children.push_back(brother->getData<BasicBlock>());
343 brother = brother->getBrother();
347 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
348 AU.setPreservesAll();
349 AU.addRequired<DominatorTree>();
351 //===--------------------------------------------------------------------===//
352 // API to update Forest information based on modifications
355 /// addNewBlock - Add a new block to the CFG, with the specified immediate
358 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
360 /// setImmediateDominator - Update the immediate dominator information to
361 /// change the current immediate dominator for the specified block
362 /// to another block. This method requires that BB for NewIDom
363 /// already have an ETNode, otherwise just use addNewBlock.
365 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
366 /// print - Convert to human readable form
368 virtual void print(std::ostream &OS, const Module* = 0) const;
369 void print(std::ostream *OS, const Module* M = 0) const {
370 if (OS) print(*OS, M);
373 /// getNode - return the (Post)DominatorTree node for the specified basic
374 /// block. This is the same as using operator[] on this class.
376 inline ETNode *getNode(BasicBlock *BB) const {
377 ETMapType::const_iterator i = Nodes.find(BB);
378 return (i != Nodes.end()) ? i->second : 0;
381 inline ETNode *operator[](BasicBlock *BB) const {
388 unsigned int SlowQueries;
392 //==-------------------------------------
393 /// ETForest Class - Concrete subclass of ETForestBase that is used to
394 /// compute a forwards ET-Forest.
396 class ETForest : public ETForestBase {
398 ETForest() : ETForestBase(false) {}
400 BasicBlock *getRoot() const {
401 assert(Roots.size() == 1 && "Should always have entry node!");
405 virtual bool runOnFunction(Function &F) {
406 reset(); // Reset from the last time we were run...
407 DominatorTree &DT = getAnalysis<DominatorTree>();
408 Roots = DT.getRoots();
413 void calculate(const DominatorTree &DT);
414 ETNode *getNodeForBlock(BasicBlock *BB);
417 //===----------------------------------------------------------------------===//
418 /// DominanceFrontierBase - Common base class for computing forward and inverse
419 /// dominance frontiers for a function.
421 class DominanceFrontierBase : public DominatorBase {
423 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
424 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
426 DomSetMapType Frontiers;
428 DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
430 virtual void releaseMemory() { Frontiers.clear(); }
432 // Accessor interface:
433 typedef DomSetMapType::iterator iterator;
434 typedef DomSetMapType::const_iterator const_iterator;
435 iterator begin() { return Frontiers.begin(); }
436 const_iterator begin() const { return Frontiers.begin(); }
437 iterator end() { return Frontiers.end(); }
438 const_iterator end() const { return Frontiers.end(); }
439 iterator find(BasicBlock *B) { return Frontiers.find(B); }
440 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
442 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
443 assert(find(BB) == end() && "Block already in DominanceFrontier!");
444 Frontiers.insert(std::make_pair(BB, frontier));
447 void addToFrontier(iterator I, BasicBlock *Node) {
448 assert(I != end() && "BB is not in DominanceFrontier!");
449 I->second.insert(Node);
452 void removeFromFrontier(iterator I, BasicBlock *Node) {
453 assert(I != end() && "BB is not in DominanceFrontier!");
454 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
455 I->second.erase(Node);
458 /// print - Convert to human readable form
460 virtual void print(std::ostream &OS, const Module* = 0) const;
461 void print(std::ostream *OS, const Module* M = 0) const {
462 if (OS) print(*OS, M);
467 //===-------------------------------------
468 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
469 /// used to compute a forward dominator frontiers.
471 class DominanceFrontier : public DominanceFrontierBase {
473 DominanceFrontier() : DominanceFrontierBase(false) {}
475 BasicBlock *getRoot() const {
476 assert(Roots.size() == 1 && "Should always have entry node!");
480 virtual bool runOnFunction(Function &) {
482 DominatorTree &DT = getAnalysis<DominatorTree>();
483 Roots = DT.getRoots();
484 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
485 calculate(DT, DT[Roots[0]]);
489 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
490 AU.setPreservesAll();
491 AU.addRequired<DominatorTree>();
494 const DomSetType &calculate(const DominatorTree &DT,
495 const DominatorTree::Node *Node);
499 } // End llvm namespace