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();
307 /// BB is split and now it has one successor. Update dominator tree to
308 /// reflect this change.
309 void splitBlock(BasicBlock *BB);
311 void calculate(Function& F);
312 DomTreeNode *getNodeForBlock(BasicBlock *BB);
313 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
314 void Compress(BasicBlock *V);
315 BasicBlock *Eval(BasicBlock *v);
316 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
317 inline BasicBlock *getIDom(BasicBlock *BB) const {
318 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
319 return I != IDoms.end() ? I->second : 0;
323 //===-------------------------------------
324 /// DominatorTree GraphTraits specialization so the DominatorTree can be
325 /// iterable by generic graph iterators.
327 template <> struct GraphTraits<DomTreeNode*> {
328 typedef DomTreeNode NodeType;
329 typedef NodeType::iterator ChildIteratorType;
331 static NodeType *getEntryNode(NodeType *N) {
334 static inline ChildIteratorType child_begin(NodeType* N) {
337 static inline ChildIteratorType child_end(NodeType* N) {
342 template <> struct GraphTraits<DominatorTree*>
343 : public GraphTraits<DomTreeNode*> {
344 static NodeType *getEntryNode(DominatorTree *DT) {
345 return DT->getRootNode();
350 //===-------------------------------------
351 /// ET-Forest Class - Class used to construct forwards and backwards
354 class ETForestBase : public DominatorBase {
356 ETForestBase(intptr_t ID, bool isPostDom)
357 : DominatorBase(ID, isPostDom), Nodes(),
358 DFSInfoValid(false), SlowQueries(0) {}
360 virtual void releaseMemory() { reset(); }
362 typedef std::map<BasicBlock*, ETNode*> ETMapType;
364 // FIXME : There is no need to make this interface public.
365 // Fix predicate simplifier.
366 void updateDFSNumbers();
368 /// dominates - Return true if A dominates B.
370 inline bool dominates(BasicBlock *A, BasicBlock *B) {
374 ETNode *NodeA = getNode(A);
375 ETNode *NodeB = getNode(B);
378 return NodeB->DominatedBy(NodeA);
380 // If we end up with too many slow queries, just update the
381 // DFS numbers on the theory that we are going to keep querying.
383 if (SlowQueries > 32) {
385 return NodeB->DominatedBy(NodeA);
387 return NodeB->DominatedBySlow(NodeA);
391 // dominates - Return true if A dominates B. This performs the
392 // special checks necessary if A and B are in the same basic block.
393 bool dominates(Instruction *A, Instruction *B);
395 /// properlyDominates - Return true if A dominates B and A != B.
397 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
398 return dominates(A, B) && A != B;
401 /// isReachableFromEntry - Return true if A is dominated by the entry
402 /// block of the function containing it.
403 const bool isReachableFromEntry(BasicBlock* A);
405 /// Return the nearest common dominator of A and B.
406 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
407 ETNode *NodeA = getNode(A);
408 ETNode *NodeB = getNode(B);
410 ETNode *Common = NodeA->NCA(NodeB);
413 return Common->getData<BasicBlock>();
416 /// Return the immediate dominator of A.
417 BasicBlock *getIDom(BasicBlock *A) const {
418 ETNode *NodeA = getNode(A);
419 if (!NodeA) return 0;
420 const ETNode *idom = NodeA->getFather();
421 return idom ? idom->getData<BasicBlock>() : 0;
424 void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
425 ETNode *NodeA = getNode(A);
427 const ETNode* son = NodeA->getSon();
430 children.push_back(son->getData<BasicBlock>());
432 const ETNode* brother = son->getBrother();
433 while (brother != son) {
434 children.push_back(brother->getData<BasicBlock>());
435 brother = brother->getBrother();
439 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
440 AU.setPreservesAll();
441 AU.addRequired<DominatorTree>();
443 //===--------------------------------------------------------------------===//
444 // API to update Forest information based on modifications
447 /// addNewBlock - Add a new block to the CFG, with the specified immediate
450 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
452 /// setImmediateDominator - Update the immediate dominator information to
453 /// change the current immediate dominator for the specified block
454 /// to another block. This method requires that BB for NewIDom
455 /// already have an ETNode, otherwise just use addNewBlock.
457 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
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);
466 /// getNode - return the (Post)DominatorTree node for the specified basic
467 /// block. This is the same as using operator[] on this class.
469 inline ETNode *getNode(BasicBlock *BB) const {
470 ETMapType::const_iterator i = Nodes.find(BB);
471 return (i != Nodes.end()) ? i->second : 0;
474 inline ETNode *operator[](BasicBlock *BB) const {
481 unsigned int SlowQueries;
485 //==-------------------------------------
486 /// ETForest Class - Concrete subclass of ETForestBase that is used to
487 /// compute a forwards ET-Forest.
489 class ETForest : public ETForestBase {
491 static char ID; // Pass identification, replacement for typeid
493 ETForest() : ETForestBase((intptr_t)&ID, false) {}
495 BasicBlock *getRoot() const {
496 assert(Roots.size() == 1 && "Should always have entry node!");
500 virtual bool runOnFunction(Function &F) {
501 reset(); // Reset from the last time we were run...
502 DominatorTree &DT = getAnalysis<DominatorTree>();
503 Roots = DT.getRoots();
508 void calculate(const DominatorTree &DT);
509 // FIXME : There is no need to make getNodeForBlock public. Fix
510 // predicate simplifier.
511 ETNode *getNodeForBlock(BasicBlock *BB);
514 //===----------------------------------------------------------------------===//
515 /// DominanceFrontierBase - Common base class for computing forward and inverse
516 /// dominance frontiers for a function.
518 class DominanceFrontierBase : public DominatorBase {
520 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
521 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
523 DomSetMapType Frontiers;
525 DominanceFrontierBase(intptr_t ID, bool isPostDom)
526 : DominatorBase(ID, isPostDom) {}
528 virtual void releaseMemory() { Frontiers.clear(); }
530 // Accessor interface:
531 typedef DomSetMapType::iterator iterator;
532 typedef DomSetMapType::const_iterator const_iterator;
533 iterator begin() { return Frontiers.begin(); }
534 const_iterator begin() const { return Frontiers.begin(); }
535 iterator end() { return Frontiers.end(); }
536 const_iterator end() const { return Frontiers.end(); }
537 iterator find(BasicBlock *B) { return Frontiers.find(B); }
538 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
540 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
541 assert(find(BB) == end() && "Block already in DominanceFrontier!");
542 Frontiers.insert(std::make_pair(BB, frontier));
545 void addToFrontier(iterator I, BasicBlock *Node) {
546 assert(I != end() && "BB is not in DominanceFrontier!");
547 I->second.insert(Node);
550 void removeFromFrontier(iterator I, BasicBlock *Node) {
551 assert(I != end() && "BB is not in DominanceFrontier!");
552 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
553 I->second.erase(Node);
556 /// print - Convert to human readable form
558 virtual void print(std::ostream &OS, const Module* = 0) const;
559 void print(std::ostream *OS, const Module* M = 0) const {
560 if (OS) print(*OS, M);
566 //===-------------------------------------
567 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
568 /// used to compute a forward dominator frontiers.
570 class DominanceFrontier : public DominanceFrontierBase {
572 static char ID; // Pass ID, replacement for typeid
573 DominanceFrontier() :
574 DominanceFrontierBase((intptr_t)& ID, false) {}
576 BasicBlock *getRoot() const {
577 assert(Roots.size() == 1 && "Should always have entry node!");
581 virtual bool runOnFunction(Function &) {
583 DominatorTree &DT = getAnalysis<DominatorTree>();
584 Roots = DT.getRoots();
585 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
586 calculate(DT, DT[Roots[0]]);
590 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
591 AU.setPreservesAll();
592 AU.addRequired<DominatorTree>();
596 /// BB is split and now it has one successor. Update dominace frontier to
597 /// reflect this change.
598 void splitBlock(BasicBlock *BB);
601 const DomSetType &calculate(const DominatorTree &DT,
602 const DomTreeNode *Node);
606 } // End llvm namespace