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 /// get() - Synonym for operator[].
107 inline BasicBlock *get(BasicBlock *BB) const {
108 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
109 return I != IDoms.end() ? I->second : 0;
112 //===--------------------------------------------------------------------===//
113 // API to update Immediate(Post)Dominators information based on modifications
116 /// addNewBlock - Add a new block to the CFG, with the specified immediate
119 void addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
120 assert(get(BB) == 0 && "BasicBlock already in idom info!");
124 /// setImmediateDominator - Update the immediate dominator information to
125 /// change the current immediate dominator for the specified block to another
126 /// block. This method requires that BB already have an IDom, otherwise just
129 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom) {
130 assert(IDoms.find(BB) != IDoms.end() && "BB doesn't have idom yet!");
134 /// print - Convert to human readable form
136 virtual void print(std::ostream &OS, const Module* = 0) const;
139 //===-------------------------------------
140 /// ImmediateDominators Class - Concrete subclass of ImmediateDominatorsBase
141 /// that is used to compute a normal immediate dominator set.
143 struct ImmediateDominators : public ImmediateDominatorsBase {
144 ImmediateDominators() : ImmediateDominatorsBase(false) {}
146 BasicBlock *getRoot() const {
147 assert(Roots.size() == 1 && "Should always have entry node!");
151 virtual bool runOnFunction(Function &F);
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.setPreservesAll();
158 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
159 void Compress(BasicBlock *V, InfoRec &VInfo);
160 BasicBlock *Eval(BasicBlock *v);
161 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
166 //===----------------------------------------------------------------------===//
167 /// DominatorSet - Maintain a set<BasicBlock*> for every basic block in a
168 /// function, that represents the blocks that dominate the block. If the block
169 /// is unreachable in this function, the set will be empty. This cannot happen
170 /// for reachable code, because every block dominates at least itself.
172 struct DominatorSetBase : public DominatorBase {
173 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
175 typedef std::map<BasicBlock*, DomSetType> DomSetMapType;
179 DominatorSetBase(bool isPostDom) : DominatorBase(isPostDom) {}
181 virtual void releaseMemory() { Doms.clear(); }
183 // Accessor interface:
184 typedef DomSetMapType::const_iterator const_iterator;
185 typedef DomSetMapType::iterator iterator;
186 inline const_iterator begin() const { return Doms.begin(); }
187 inline iterator begin() { return Doms.begin(); }
188 inline const_iterator end() const { return Doms.end(); }
189 inline iterator end() { return Doms.end(); }
190 inline const_iterator find(BasicBlock* B) const { return Doms.find(B); }
191 inline iterator find(BasicBlock* B) { return Doms.find(B); }
194 /// getDominators - Return the set of basic blocks that dominate the specified
197 inline const DomSetType &getDominators(BasicBlock *BB) const {
198 const_iterator I = find(BB);
199 assert(I != end() && "BB not in function!");
203 /// isReachable - Return true if the specified basicblock is reachable. If
204 /// the block is reachable, we have dominator set information for it.
206 bool isReachable(BasicBlock *BB) const {
207 return !getDominators(BB).empty();
210 /// dominates - Return true if A dominates B.
212 inline bool dominates(BasicBlock *A, BasicBlock *B) const {
213 return getDominators(B).count(A) != 0;
216 /// properlyDominates - Return true if A dominates B and A != B.
218 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
219 return dominates(A, B) && A != B;
222 /// print - Convert to human readable form
224 virtual void print(std::ostream &OS, const Module* = 0) const;
226 /// dominates - Return true if A dominates B. This performs the special
227 /// checks necessary if A and B are in the same basic block.
229 bool dominates(Instruction *A, Instruction *B) const;
231 //===--------------------------------------------------------------------===//
232 // API to update (Post)DominatorSet information based on modifications to
235 /// addBasicBlock - Call to update the dominator set with information about a
236 /// new block that was inserted into the function.
238 void addBasicBlock(BasicBlock *BB, const DomSetType &Dominators) {
239 assert(find(BB) == end() && "Block already in DominatorSet!");
240 Doms.insert(std::make_pair(BB, Dominators));
243 /// addDominator - If a new block is inserted into the CFG, then method may be
244 /// called to notify the blocks it dominates that it is in their set.
246 void addDominator(BasicBlock *BB, BasicBlock *NewDominator) {
247 iterator I = find(BB);
248 assert(I != end() && "BB is not in DominatorSet!");
249 I->second.insert(NewDominator);
254 //===-------------------------------------
255 /// DominatorSet Class - Concrete subclass of DominatorSetBase that is used to
256 /// compute a normal dominator set.
258 struct DominatorSet : public DominatorSetBase {
259 DominatorSet() : DominatorSetBase(false) {}
261 virtual bool runOnFunction(Function &F);
263 BasicBlock *getRoot() const {
264 assert(Roots.size() == 1 && "Should always have entry node!");
268 /// getAnalysisUsage - This simply provides a dominator set
270 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
271 AU.addRequired<ImmediateDominators>();
272 AU.setPreservesAll();
275 // stub - dummy function, just ignore it
280 //===----------------------------------------------------------------------===//
281 /// DominatorTree - Calculate the immediate dominator tree for a function.
283 struct DominatorTreeBase : public DominatorBase {
286 std::map<BasicBlock*, Node*> Nodes;
288 typedef std::map<BasicBlock*, Node*> NodeMapType;
293 friend struct DominatorTree;
294 friend struct PostDominatorTree;
295 friend struct DominatorTreeBase;
298 std::vector<Node*> Children;
300 typedef std::vector<Node*>::iterator iterator;
301 typedef std::vector<Node*>::const_iterator const_iterator;
303 iterator begin() { return Children.begin(); }
304 iterator end() { return Children.end(); }
305 const_iterator begin() const { return Children.begin(); }
306 const_iterator end() const { return Children.end(); }
308 inline BasicBlock *getBlock() const { return TheBB; }
309 inline Node *getIDom() const { return IDom; }
310 inline const std::vector<Node*> &getChildren() const { return Children; }
312 /// properlyDominates - Returns true iff this dominates N and this != N.
313 /// Note that this is not a constant time operation!
315 bool properlyDominates(const Node *N) const {
317 if (this == 0 || N == 0) return false;
318 while ((IDom = N->getIDom()) != 0 && IDom != this)
319 N = IDom; // Walk up the tree
323 /// dominates - Returns true iff this dominates N. Note that this is not a
324 /// constant time operation!
326 inline bool dominates(const Node *N) const {
327 if (N == this) return true; // A node trivially dominates itself.
328 return properlyDominates(N);
332 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
333 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
335 void setIDom(Node *NewIDom);
339 DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
340 ~DominatorTreeBase() { reset(); }
342 virtual void releaseMemory() { reset(); }
344 /// getNode - return the (Post)DominatorTree node for the specified basic
345 /// block. This is the same as using operator[] on this class.
347 inline Node *getNode(BasicBlock *BB) const {
348 NodeMapType::const_iterator i = Nodes.find(BB);
349 return (i != Nodes.end()) ? i->second : 0;
352 inline Node *operator[](BasicBlock *BB) const {
356 /// getRootNode - This returns the entry node for the CFG of the function. If
357 /// this tree represents the post-dominance relations for a function, however,
358 /// this root may be a node with the block == NULL. This is the case when
359 /// there are multiple exit nodes from a particular function. Consumers of
360 /// post-dominance information must be capable of dealing with this
363 Node *getRootNode() { return RootNode; }
364 const Node *getRootNode() const { return RootNode; }
366 //===--------------------------------------------------------------------===//
367 // API to update (Post)DominatorTree information based on modifications to
370 /// createNewNode - Add a new node to the dominator tree information. This
371 /// creates a new node as a child of IDomNode, linking it into the children
372 /// list of the immediate dominator.
374 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
375 assert(getNode(BB) == 0 && "Block already in dominator tree!");
376 assert(IDomNode && "Not immediate dominator specified for block!");
377 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
380 /// changeImmediateDominator - This method is used to update the dominator
381 /// tree information when a node's immediate dominator changes.
383 void changeImmediateDominator(Node *N, Node *NewIDom) {
384 assert(N && NewIDom && "Cannot change null node pointers!");
388 /// print - Convert to human readable form
390 virtual void print(std::ostream &OS, const Module* = 0) const;
394 //===-------------------------------------
395 /// ET-Forest Class - Class used to construct forwards and backwards
398 struct ETForestBase : public DominatorBase {
399 ETForestBase(bool isPostDom) : DominatorBase(isPostDom), Nodes(),
400 DFSInfoValid(false), SlowQueries(0) {}
402 virtual void releaseMemory() { reset(); }
404 typedef std::map<BasicBlock*, ETNode*> ETMapType;
406 void updateDFSNumbers();
408 /// dominates - Return true if A dominates B.
410 inline bool dominates(BasicBlock *A, BasicBlock *B) {
414 ETNode *NodeA = getNode(A);
415 ETNode *NodeB = getNode(B);
418 return NodeB->DominatedBy(NodeA);
420 // If we end up with too many slow queries, just update the
421 // DFS numbers on the theory that we are going to keep querying.
423 if (SlowQueries > 32) {
425 return NodeB->DominatedBy(NodeA);
427 return NodeB->DominatedBySlow(NodeA);
431 /// properlyDominates - Return true if A dominates B and A != B.
433 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
434 return dominates(A, B) && A != B;
437 /// Return the nearest common dominator of A and B.
438 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
439 ETNode *NodeA = getNode(A);
440 ETNode *NodeB = getNode(B);
442 ETNode *Common = NodeA->NCA(NodeB);
445 return Common->getData<BasicBlock>();
448 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
449 AU.setPreservesAll();
450 AU.addRequired<ImmediateDominators>();
452 //===--------------------------------------------------------------------===//
453 // API to update Forest information based on modifications
456 /// addNewBlock - Add a new block to the CFG, with the specified immediate
459 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
461 /// setImmediateDominator - Update the immediate dominator information to
462 /// change the current immediate dominator for the specified block
463 /// to another block. This method requires that BB for NewIDom
464 /// already have an ETNode, otherwise just use addNewBlock.
466 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
467 /// print - Convert to human readable form
469 virtual void print(std::ostream &OS, const Module* = 0) const;
471 /// getNode - return the (Post)DominatorTree node for the specified basic
472 /// block. This is the same as using operator[] on this class.
474 inline ETNode *getNode(BasicBlock *BB) const {
475 ETMapType::const_iterator i = Nodes.find(BB);
476 return (i != Nodes.end()) ? i->second : 0;
479 inline ETNode *operator[](BasicBlock *BB) const {
486 unsigned int SlowQueries;
490 //==-------------------------------------
491 /// ETForest Class - Concrete subclass of ETForestBase that is used to
492 /// compute a forwards ET-Forest.
494 struct ETForest : public ETForestBase {
495 ETForest() : ETForestBase(false) {}
497 BasicBlock *getRoot() const {
498 assert(Roots.size() == 1 && "Should always have entry node!");
502 virtual bool runOnFunction(Function &F) {
503 reset(); // Reset from the last time we were run...
504 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
505 Roots = ID.getRoots();
510 void calculate(const ImmediateDominators &ID);
511 ETNode *getNodeForBlock(BasicBlock *BB);
514 //===-------------------------------------
515 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
516 /// compute a normal dominator tree.
518 struct DominatorTree : public DominatorTreeBase {
519 DominatorTree() : DominatorTreeBase(false) {}
521 BasicBlock *getRoot() const {
522 assert(Roots.size() == 1 && "Should always have entry node!");
526 virtual bool runOnFunction(Function &F) {
527 reset(); // Reset from the last time we were run...
528 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
529 Roots = ID.getRoots();
534 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
535 AU.setPreservesAll();
536 AU.addRequired<ImmediateDominators>();
539 void calculate(const ImmediateDominators &ID);
540 Node *getNodeForBlock(BasicBlock *BB);
543 //===-------------------------------------
544 /// DominatorTree GraphTraits specialization so the DominatorTree can be
545 /// iterable by generic graph iterators.
547 template <> struct GraphTraits<DominatorTree::Node*> {
548 typedef DominatorTree::Node NodeType;
549 typedef NodeType::iterator ChildIteratorType;
551 static NodeType *getEntryNode(NodeType *N) {
554 static inline ChildIteratorType child_begin(NodeType* N) {
557 static inline ChildIteratorType child_end(NodeType* N) {
562 template <> struct GraphTraits<DominatorTree*>
563 : public GraphTraits<DominatorTree::Node*> {
564 static NodeType *getEntryNode(DominatorTree *DT) {
565 return DT->getRootNode();
569 //===----------------------------------------------------------------------===//
570 /// DominanceFrontier - Calculate the dominance frontiers for a function.
572 struct DominanceFrontierBase : public DominatorBase {
573 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
574 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
576 DomSetMapType Frontiers;
578 DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
580 virtual void releaseMemory() { Frontiers.clear(); }
582 // Accessor interface:
583 typedef DomSetMapType::iterator iterator;
584 typedef DomSetMapType::const_iterator const_iterator;
585 iterator begin() { return Frontiers.begin(); }
586 const_iterator begin() const { return Frontiers.begin(); }
587 iterator end() { return Frontiers.end(); }
588 const_iterator end() const { return Frontiers.end(); }
589 iterator find(BasicBlock *B) { return Frontiers.find(B); }
590 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
592 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
593 assert(find(BB) == end() && "Block already in DominanceFrontier!");
594 Frontiers.insert(std::make_pair(BB, frontier));
597 void addToFrontier(iterator I, BasicBlock *Node) {
598 assert(I != end() && "BB is not in DominanceFrontier!");
599 I->second.insert(Node);
602 void removeFromFrontier(iterator I, BasicBlock *Node) {
603 assert(I != end() && "BB is not in DominanceFrontier!");
604 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
605 I->second.erase(Node);
608 /// print - Convert to human readable form
610 virtual void print(std::ostream &OS, const Module* = 0) const;
614 //===-------------------------------------
615 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
616 /// compute a normal dominator tree.
618 struct DominanceFrontier : public DominanceFrontierBase {
619 DominanceFrontier() : DominanceFrontierBase(false) {}
621 BasicBlock *getRoot() const {
622 assert(Roots.size() == 1 && "Should always have entry node!");
626 virtual bool runOnFunction(Function &) {
628 DominatorTree &DT = getAnalysis<DominatorTree>();
629 Roots = DT.getRoots();
630 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
631 calculate(DT, DT[Roots[0]]);
635 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
636 AU.setPreservesAll();
637 AU.addRequired<DominatorTree>();
640 const DomSetType &calculate(const DominatorTree &DT,
641 const DominatorTree::Node *Node);
645 // Make sure that any clients of this file link in Dominators.cpp
647 DOMINATORS_INCLUDE_FILE((void*)&DominatorSet::stub);
648 } // End llvm namespace