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. ImmediateDominators: Calculates and holds a mapping between BasicBlocks
12 // and their immediate dominator.
13 // 2. DominatorSet: Calculates the [reverse] dominator set for a function
14 // 3. DominatorTree: Represent the ImmediateDominator as an explicit tree
16 // 4. ETForest: Efficient data structure for dominance comparisons and
17 // nearest-common-ancestor queries.
18 // 5. DominanceFrontier: Calculate and hold the dominance frontier for a
21 // These data structures are listed in increasing order of complexity. It
22 // takes longer to calculate the dominator frontier, for example, than the
23 // ImmediateDominator mapping.
25 //===----------------------------------------------------------------------===//
27 #ifndef LLVM_ANALYSIS_DOMINATORS_H
28 #define LLVM_ANALYSIS_DOMINATORS_H
30 #include "llvm/Analysis/ET-Forest.h"
31 #include "llvm/Pass.h"
38 template <typename GraphType> struct GraphTraits;
40 //===----------------------------------------------------------------------===//
41 /// DominatorBase - Base class that other, more interesting dominator analyses
44 class DominatorBase : public FunctionPass {
46 std::vector<BasicBlock*> Roots;
47 const bool IsPostDominators;
49 inline DominatorBase(bool isPostDom) : Roots(), IsPostDominators(isPostDom) {}
51 /// getRoots - Return the root blocks of the current CFG. This may include
52 /// multiple blocks if we are computing post dominators. For forward
53 /// dominators, this will always be a single block (the entry node).
55 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
57 /// isPostDominator - Returns true if analysis based of postdoms
59 bool isPostDominator() const { return IsPostDominators; }
63 //===----------------------------------------------------------------------===//
64 /// ImmediateDominators - Calculate the immediate dominator for each node in a
67 class ImmediateDominatorsBase : public DominatorBase {
72 BasicBlock *Label, *Parent, *Child, *Ancestor;
74 std::vector<BasicBlock*> Bucket;
76 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
79 std::map<BasicBlock*, BasicBlock*> IDoms;
81 // Vertex - Map the DFS number to the BasicBlock*
82 std::vector<BasicBlock*> Vertex;
84 // Info - Collection of information used during the computation of idoms.
85 std::map<BasicBlock*, InfoRec> Info;
87 ImmediateDominatorsBase(bool isPostDom) : DominatorBase(isPostDom) {}
89 virtual void releaseMemory() { IDoms.clear(); }
91 // Accessor interface:
92 typedef std::map<BasicBlock*, BasicBlock*> IDomMapType;
93 typedef IDomMapType::const_iterator const_iterator;
94 inline const_iterator begin() const { return IDoms.begin(); }
95 inline const_iterator end() const { return IDoms.end(); }
96 inline const_iterator find(BasicBlock* B) const { return IDoms.find(B);}
98 /// operator[] - Return the idom for the specified basic block. The start
99 /// node returns null, because it does not have an immediate dominator.
101 inline BasicBlock *operator[](BasicBlock *BB) const {
105 /// dominates - Return true if A dominates B.
107 bool dominates(BasicBlock *A, BasicBlock *B) const;
109 /// properlyDominates - Return true if A dominates B and A != B.
111 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
112 return A != B || properlyDominates(A, B);
115 /// get() - Synonym for operator[].
117 inline BasicBlock *get(BasicBlock *BB) const {
118 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
119 return I != IDoms.end() ? I->second : 0;
122 //===--------------------------------------------------------------------===//
123 // API to update Immediate(Post)Dominators information based on modifications
126 /// addNewBlock - Add a new block to the CFG, with the specified immediate
129 void addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
130 assert(get(BB) == 0 && "BasicBlock already in idom info!");
134 /// setImmediateDominator - Update the immediate dominator information to
135 /// change the current immediate dominator for the specified block to another
136 /// block. This method requires that BB already have an IDom, otherwise just
139 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom) {
140 assert(IDoms.find(BB) != IDoms.end() && "BB doesn't have idom yet!");
144 /// print - Convert to human readable form
146 virtual void print(std::ostream &OS, const Module* = 0) const;
147 void print(std::ostream *OS, const Module* M = 0) const {
148 if (OS) print(*OS, M);
152 //===-------------------------------------
153 /// ImmediateDominators Class - Concrete subclass of ImmediateDominatorsBase
154 /// that is used to compute a normal immediate dominator set.
156 class ImmediateDominators : public ImmediateDominatorsBase {
158 ImmediateDominators() : ImmediateDominatorsBase(false) {}
160 BasicBlock *getRoot() const {
161 assert(Roots.size() == 1 && "Should always have entry node!");
165 virtual bool runOnFunction(Function &F);
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.setPreservesAll();
172 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
173 void Compress(BasicBlock *V, InfoRec &VInfo);
174 BasicBlock *Eval(BasicBlock *v);
175 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
180 //===----------------------------------------------------------------------===//
181 /// DominatorSet - Maintain a set<BasicBlock*> for every basic block in a
182 /// function, that represents the blocks that dominate the block. If the block
183 /// is unreachable in this function, the set will be empty. This cannot happen
184 /// for reachable code, because every block dominates at least itself.
186 class DominatorSetBase : public DominatorBase {
188 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
190 typedef std::map<BasicBlock*, DomSetType> DomSetMapType;
194 DominatorSetBase(bool isPostDom) : DominatorBase(isPostDom) {}
196 virtual void releaseMemory() { Doms.clear(); }
198 // Accessor interface:
199 typedef DomSetMapType::const_iterator const_iterator;
200 typedef DomSetMapType::iterator iterator;
201 inline const_iterator begin() const { return Doms.begin(); }
202 inline iterator begin() { return Doms.begin(); }
203 inline const_iterator end() const { return Doms.end(); }
204 inline iterator end() { return Doms.end(); }
205 inline const_iterator find(BasicBlock* B) const { return Doms.find(B); }
206 inline iterator find(BasicBlock* B) { return Doms.find(B); }
209 /// getDominators - Return the set of basic blocks that dominate the specified
212 inline const DomSetType &getDominators(BasicBlock *BB) const {
213 const_iterator I = find(BB);
214 assert(I != end() && "BB not in function!");
218 /// isReachable - Return true if the specified basicblock is reachable. If
219 /// the block is reachable, we have dominator set information for it.
221 bool isReachable(BasicBlock *BB) const {
222 return !getDominators(BB).empty();
225 /// dominates - Return true if A dominates B.
227 inline bool dominates(BasicBlock *A, BasicBlock *B) const {
228 return getDominators(B).count(A) != 0;
231 /// properlyDominates - Return true if A dominates B and A != B.
233 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
234 return dominates(A, B) && A != B;
237 /// print - Convert to human readable form
239 virtual void print(std::ostream &OS, const Module* = 0) const;
240 void print(std::ostream *OS, const Module* M = 0) const {
241 if (OS) print(*OS, M);
244 /// dominates - Return true if A dominates B. This performs the special
245 /// checks necessary if A and B are in the same basic block.
247 bool dominates(Instruction *A, Instruction *B) const;
249 //===--------------------------------------------------------------------===//
250 // API to update (Post)DominatorSet information based on modifications to
253 /// addBasicBlock - Call to update the dominator set with information about a
254 /// new block that was inserted into the function.
256 void addBasicBlock(BasicBlock *BB, const DomSetType &Dominators) {
257 assert(find(BB) == end() && "Block already in DominatorSet!");
258 Doms.insert(std::make_pair(BB, Dominators));
261 /// addDominator - If a new block is inserted into the CFG, then method may be
262 /// called to notify the blocks it dominates that it is in their set.
264 void addDominator(BasicBlock *BB, BasicBlock *NewDominator) {
265 iterator I = find(BB);
266 assert(I != end() && "BB is not in DominatorSet!");
267 I->second.insert(NewDominator);
272 //===-------------------------------------
273 /// DominatorSet Class - Concrete subclass of DominatorSetBase that is used to
274 /// compute a normal dominator set.
276 class DominatorSet : public DominatorSetBase {
278 DominatorSet() : DominatorSetBase(false) {}
280 virtual bool runOnFunction(Function &F);
282 BasicBlock *getRoot() const {
283 assert(Roots.size() == 1 && "Should always have entry node!");
287 /// getAnalysisUsage - This simply provides a dominator set
289 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
290 AU.addRequired<ImmediateDominators>();
291 AU.setPreservesAll();
294 // stub - dummy function, just ignore it
299 //===----------------------------------------------------------------------===//
300 /// DominatorTree - Calculate the immediate dominator tree for a function.
302 class DominatorTreeBase : public DominatorBase {
306 std::map<BasicBlock*, Node*> Nodes;
308 typedef std::map<BasicBlock*, Node*> NodeMapType;
313 friend class DominatorTree;
314 friend struct PostDominatorTree;
315 friend class DominatorTreeBase;
318 std::vector<Node*> Children;
320 typedef std::vector<Node*>::iterator iterator;
321 typedef std::vector<Node*>::const_iterator const_iterator;
323 iterator begin() { return Children.begin(); }
324 iterator end() { return Children.end(); }
325 const_iterator begin() const { return Children.begin(); }
326 const_iterator end() const { return Children.end(); }
328 inline BasicBlock *getBlock() const { return TheBB; }
329 inline Node *getIDom() const { return IDom; }
330 inline const std::vector<Node*> &getChildren() const { return Children; }
332 /// properlyDominates - Returns true iff this dominates N and this != N.
333 /// Note that this is not a constant time operation!
335 bool properlyDominates(const Node *N) const {
337 if (this == 0 || N == 0) return false;
338 while ((IDom = N->getIDom()) != 0 && IDom != this)
339 N = IDom; // Walk up the tree
343 /// dominates - Returns true iff this dominates N. Note that this is not a
344 /// constant time operation!
346 inline bool dominates(const Node *N) const {
347 if (N == this) return true; // A node trivially dominates itself.
348 return properlyDominates(N);
352 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
353 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
355 void setIDom(Node *NewIDom);
359 DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
360 ~DominatorTreeBase() { reset(); }
362 virtual void releaseMemory() { reset(); }
364 /// getNode - return the (Post)DominatorTree node for the specified basic
365 /// block. This is the same as using operator[] on this class.
367 inline Node *getNode(BasicBlock *BB) const {
368 NodeMapType::const_iterator i = Nodes.find(BB);
369 return (i != Nodes.end()) ? i->second : 0;
372 inline Node *operator[](BasicBlock *BB) const {
376 /// getRootNode - This returns the entry node for the CFG of the function. If
377 /// this tree represents the post-dominance relations for a function, however,
378 /// this root may be a node with the block == NULL. This is the case when
379 /// there are multiple exit nodes from a particular function. Consumers of
380 /// post-dominance information must be capable of dealing with this
383 Node *getRootNode() { return RootNode; }
384 const Node *getRootNode() const { return RootNode; }
386 //===--------------------------------------------------------------------===//
387 // API to update (Post)DominatorTree information based on modifications to
390 /// createNewNode - Add a new node to the dominator tree information. This
391 /// creates a new node as a child of IDomNode, linking it into the children
392 /// list of the immediate dominator.
394 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
395 assert(getNode(BB) == 0 && "Block already in dominator tree!");
396 assert(IDomNode && "Not immediate dominator specified for block!");
397 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
400 /// changeImmediateDominator - This method is used to update the dominator
401 /// tree information when a node's immediate dominator changes.
403 void changeImmediateDominator(Node *N, Node *NewIDom) {
404 assert(N && NewIDom && "Cannot change null node pointers!");
408 /// removeNode - Removes a node from the dominator tree. Block must not
409 /// dominate any other blocks. Invalidates any node pointing to removed
411 void removeNode(BasicBlock *BB) {
412 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
416 /// print - Convert to human readable form
418 virtual void print(std::ostream &OS, const Module* = 0) const;
419 void print(std::ostream *OS, const Module* M = 0) const {
420 if (OS) print(*OS, M);
424 //===-------------------------------------
425 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
426 /// compute a normal dominator tree.
428 class DominatorTree : public DominatorTreeBase {
430 DominatorTree() : DominatorTreeBase(false) {}
432 BasicBlock *getRoot() const {
433 assert(Roots.size() == 1 && "Should always have entry node!");
437 virtual bool runOnFunction(Function &F) {
438 reset(); // Reset from the last time we were run...
439 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
440 Roots = ID.getRoots();
445 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
446 AU.setPreservesAll();
447 AU.addRequired<ImmediateDominators>();
450 void calculate(const ImmediateDominators &ID);
451 Node *getNodeForBlock(BasicBlock *BB);
454 //===-------------------------------------
455 /// DominatorTree GraphTraits specialization so the DominatorTree can be
456 /// iterable by generic graph iterators.
458 template <> struct GraphTraits<DominatorTree::Node*> {
459 typedef DominatorTree::Node NodeType;
460 typedef NodeType::iterator ChildIteratorType;
462 static NodeType *getEntryNode(NodeType *N) {
465 static inline ChildIteratorType child_begin(NodeType* N) {
468 static inline ChildIteratorType child_end(NodeType* N) {
473 template <> struct GraphTraits<DominatorTree*>
474 : public GraphTraits<DominatorTree::Node*> {
475 static NodeType *getEntryNode(DominatorTree *DT) {
476 return DT->getRootNode();
481 //===-------------------------------------
482 /// ET-Forest Class - Class used to construct forwards and backwards
485 class ETForestBase : public DominatorBase {
487 ETForestBase(bool isPostDom) : DominatorBase(isPostDom), Nodes(),
488 DFSInfoValid(false), SlowQueries(0) {}
490 virtual void releaseMemory() { reset(); }
492 typedef std::map<BasicBlock*, ETNode*> ETMapType;
494 void updateDFSNumbers();
496 /// dominates - Return true if A dominates B.
498 inline bool dominates(BasicBlock *A, BasicBlock *B) {
502 ETNode *NodeA = getNode(A);
503 ETNode *NodeB = getNode(B);
506 return NodeB->DominatedBy(NodeA);
508 // If we end up with too many slow queries, just update the
509 // DFS numbers on the theory that we are going to keep querying.
511 if (SlowQueries > 32) {
513 return NodeB->DominatedBy(NodeA);
515 return NodeB->DominatedBySlow(NodeA);
519 // dominates - Return true if A dominates B. THis performs the
520 // special checks necessary if A and B are in the same basic block.
521 bool dominates(Instruction *A, Instruction *B);
523 /// properlyDominates - Return true if A dominates B and A != B.
525 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
526 return dominates(A, B) && A != B;
529 /// Return the nearest common dominator of A and B.
530 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
531 ETNode *NodeA = getNode(A);
532 ETNode *NodeB = getNode(B);
534 ETNode *Common = NodeA->NCA(NodeB);
537 return Common->getData<BasicBlock>();
540 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
541 AU.setPreservesAll();
542 AU.addRequired<ImmediateDominators>();
544 //===--------------------------------------------------------------------===//
545 // API to update Forest information based on modifications
548 /// addNewBlock - Add a new block to the CFG, with the specified immediate
551 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
553 /// setImmediateDominator - Update the immediate dominator information to
554 /// change the current immediate dominator for the specified block
555 /// to another block. This method requires that BB for NewIDom
556 /// already have an ETNode, otherwise just use addNewBlock.
558 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
559 /// print - Convert to human readable form
561 virtual void print(std::ostream &OS, const Module* = 0) const;
562 void print(std::ostream *OS, const Module* M = 0) const {
563 if (OS) print(*OS, M);
566 /// getNode - return the (Post)DominatorTree node for the specified basic
567 /// block. This is the same as using operator[] on this class.
569 inline ETNode *getNode(BasicBlock *BB) const {
570 ETMapType::const_iterator i = Nodes.find(BB);
571 return (i != Nodes.end()) ? i->second : 0;
574 inline ETNode *operator[](BasicBlock *BB) const {
581 unsigned int SlowQueries;
585 //==-------------------------------------
586 /// ETForest Class - Concrete subclass of ETForestBase that is used to
587 /// compute a forwards ET-Forest.
589 class ETForest : public ETForestBase {
591 ETForest() : ETForestBase(false) {}
593 BasicBlock *getRoot() const {
594 assert(Roots.size() == 1 && "Should always have entry node!");
598 virtual bool runOnFunction(Function &F) {
599 reset(); // Reset from the last time we were run...
600 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
601 Roots = ID.getRoots();
606 void calculate(const ImmediateDominators &ID);
607 ETNode *getNodeForBlock(BasicBlock *BB);
610 //===----------------------------------------------------------------------===//
611 /// DominanceFrontierBase - Common base class for computing forward and inverse
612 /// dominance frontiers for a function.
614 class DominanceFrontierBase : public DominatorBase {
616 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
617 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
619 DomSetMapType Frontiers;
621 DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
623 virtual void releaseMemory() { Frontiers.clear(); }
625 // Accessor interface:
626 typedef DomSetMapType::iterator iterator;
627 typedef DomSetMapType::const_iterator const_iterator;
628 iterator begin() { return Frontiers.begin(); }
629 const_iterator begin() const { return Frontiers.begin(); }
630 iterator end() { return Frontiers.end(); }
631 const_iterator end() const { return Frontiers.end(); }
632 iterator find(BasicBlock *B) { return Frontiers.find(B); }
633 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
635 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
636 assert(find(BB) == end() && "Block already in DominanceFrontier!");
637 Frontiers.insert(std::make_pair(BB, frontier));
640 void addToFrontier(iterator I, BasicBlock *Node) {
641 assert(I != end() && "BB is not in DominanceFrontier!");
642 I->second.insert(Node);
645 void removeFromFrontier(iterator I, BasicBlock *Node) {
646 assert(I != end() && "BB is not in DominanceFrontier!");
647 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
648 I->second.erase(Node);
651 /// print - Convert to human readable form
653 virtual void print(std::ostream &OS, const Module* = 0) const;
654 void print(std::ostream *OS, const Module* M = 0) const {
655 if (OS) print(*OS, M);
660 //===-------------------------------------
661 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
662 /// used to compute a forward dominator frontiers.
664 class DominanceFrontier : public DominanceFrontierBase {
666 DominanceFrontier() : DominanceFrontierBase(false) {}
668 BasicBlock *getRoot() const {
669 assert(Roots.size() == 1 && "Should always have entry node!");
673 virtual bool runOnFunction(Function &) {
675 DominatorTree &DT = getAnalysis<DominatorTree>();
676 Roots = DT.getRoots();
677 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
678 calculate(DT, DT[Roots[0]]);
682 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
683 AU.setPreservesAll();
684 AU.addRequired<DominatorTree>();
687 const DomSetType &calculate(const DominatorTree &DT,
688 const DominatorTree::Node *Node);
692 } // End llvm namespace
694 // Make sure that any clients of this file link in Dominators.cpp
695 FORCE_DEFINING_FILE_TO_BE_LINKED(DominatorSet)