0be0bb06ce83e4459ba28b614f95790774a2ed65
[oota-llvm.git] / include / llvm / Analysis / Dominators.h
1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the following classes:
11 //  1. DominatorTree: Represent the ImmediateDominator as an explicit tree
12 //     structure.
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
16 //     function.
17 //
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.
21 //
22 //===----------------------------------------------------------------------===//
23
24 #ifndef LLVM_ANALYSIS_DOMINATORS_H
25 #define LLVM_ANALYSIS_DOMINATORS_H
26
27 #include "llvm/Analysis/ET-Forest.h"
28 #include "llvm/Pass.h"
29 #include <set>
30
31 namespace llvm {
32
33 class Instruction;
34
35 template <typename GraphType> struct GraphTraits;
36
37 //===----------------------------------------------------------------------===//
38 /// DominatorBase - Base class that other, more interesting dominator analyses
39 /// inherit from.
40 ///
41 class DominatorBase : public FunctionPass {
42 protected:
43   std::vector<BasicBlock*> Roots;
44   const bool IsPostDominators;
45   inline DominatorBase(intptr_t ID, bool isPostDom) : 
46     FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
47 public:
48
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).
52   ///
53   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
54
55   /// isPostDominator - Returns true if analysis based of postdoms
56   ///
57   bool isPostDominator() const { return IsPostDominators; }
58 };
59
60 //===----------------------------------------------------------------------===//
61 /// DominatorTree - Calculate the immediate dominator tree for a function.
62 ///
63 class DominatorTreeBase : public DominatorBase {
64 public:
65   class Node;
66 protected:
67   std::map<BasicBlock*, Node*> Nodes;
68   void reset();
69   typedef std::map<BasicBlock*, Node*> NodeMapType;
70
71   Node *RootNode;
72
73   struct InfoRec {
74     unsigned Semi;
75     unsigned Size;
76     BasicBlock *Label, *Parent, *Child, *Ancestor;
77
78     std::vector<BasicBlock*> Bucket;
79
80     InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
81   };
82
83   std::map<BasicBlock*, BasicBlock*> IDoms;
84
85   // Vertex - Map the DFS number to the BasicBlock*
86   std::vector<BasicBlock*> Vertex;
87
88   // Info - Collection of information used during the computation of idoms.
89   std::map<BasicBlock*, InfoRec> Info;
90
91 public:
92   class Node {
93     friend class DominatorTree;
94     friend struct PostDominatorTree;
95     friend class DominatorTreeBase;
96     BasicBlock *TheBB;
97     Node *IDom;
98     std::vector<Node*> Children;
99   public:
100     typedef std::vector<Node*>::iterator iterator;
101     typedef std::vector<Node*>::const_iterator const_iterator;
102
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(); }
107
108     inline BasicBlock *getBlock() const { return TheBB; }
109     inline Node *getIDom() const { return IDom; }
110     inline const std::vector<Node*> &getChildren() const { return Children; }
111
112     /// properlyDominates - Returns true iff this dominates N and this != N.
113     /// Note that this is not a constant time operation!
114     ///
115     bool properlyDominates(const Node *N) const {
116       const Node *IDom;
117       if (this == 0 || N == 0) return false;
118       while ((IDom = N->getIDom()) != 0 && IDom != this)
119         N = IDom;   // Walk up the tree
120       return IDom != 0;
121     }
122
123     /// dominates - Returns true iff this dominates N.  Note that this is not a
124     /// constant time operation!
125     ///
126     inline bool dominates(const Node *N) const {
127       if (N == this) return true;  // A node trivially dominates itself.
128       return properlyDominates(N);
129     }
130     
131   private:
132     inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
133     inline Node *addChild(Node *C) { Children.push_back(C); return C; }
134
135     void setIDom(Node *NewIDom);
136   };
137
138 public:
139   DominatorTreeBase(intptr_t ID, bool isPostDom) 
140     : DominatorBase(ID, isPostDom) {}
141   ~DominatorTreeBase() { reset(); }
142
143   virtual void releaseMemory() { reset(); }
144
145   /// getNode - return the (Post)DominatorTree node for the specified basic
146   /// block.  This is the same as using operator[] on this class.
147   ///
148   inline Node *getNode(BasicBlock *BB) const {
149     NodeMapType::const_iterator i = Nodes.find(BB);
150     return (i != Nodes.end()) ? i->second : 0;
151   }
152
153   inline Node *operator[](BasicBlock *BB) const {
154     return getNode(BB);
155   }
156
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
162   /// possibility.
163   ///
164   Node *getRootNode() { return RootNode; }
165   const Node *getRootNode() const { return RootNode; }
166
167   //===--------------------------------------------------------------------===//
168   // API to update (Post)DominatorTree information based on modifications to
169   // the CFG...
170
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.
174   ///
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));
179   }
180
181   /// changeImmediateDominator - This method is used to update the dominator
182   /// tree information when a node's immediate dominator changes.
183   ///
184   void changeImmediateDominator(Node *N, Node *NewIDom) {
185     assert(N && NewIDom && "Cannot change null node pointers!");
186     N->setIDom(NewIDom);
187   }
188
189   /// removeNode - Removes a node from the dominator tree.  Block must not
190   /// dominate any other blocks.  Invalidates any node pointing to removed
191   /// block.
192   void removeNode(BasicBlock *BB) {
193     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
194     Nodes.erase(BB);
195   }
196
197   /// print - Convert to human readable form
198   ///
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);
202   }
203 };
204
205 //===-------------------------------------
206 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
207 /// compute a normal dominator tree.
208 ///
209 class DominatorTree : public DominatorTreeBase {
210 public:
211   static const char ID; // Pass ID, replacement for typeid
212   DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
213   
214   BasicBlock *getRoot() const {
215     assert(Roots.size() == 1 && "Should always have entry node!");
216     return Roots[0];
217   }
218   
219   virtual bool runOnFunction(Function &F);
220   
221   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222     AU.setPreservesAll();
223   }
224 private:
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;
234     }
235 };
236
237 //===-------------------------------------
238 /// DominatorTree GraphTraits specialization so the DominatorTree can be
239 /// iterable by generic graph iterators.
240 ///
241 template <> struct GraphTraits<DominatorTree::Node*> {
242   typedef DominatorTree::Node NodeType;
243   typedef NodeType::iterator  ChildIteratorType;
244   
245   static NodeType *getEntryNode(NodeType *N) {
246     return N;
247   }
248   static inline ChildIteratorType child_begin(NodeType* N) {
249     return N->begin();
250   }
251   static inline ChildIteratorType child_end(NodeType* N) {
252     return N->end();
253   }
254 };
255
256 template <> struct GraphTraits<DominatorTree*>
257   : public GraphTraits<DominatorTree::Node*> {
258   static NodeType *getEntryNode(DominatorTree *DT) {
259     return DT->getRootNode();
260   }
261 };
262
263
264 //===-------------------------------------
265 /// ET-Forest Class - Class used to construct forwards and backwards 
266 /// ET-Forests
267 ///
268 class ETForestBase : public DominatorBase {
269 public:
270   ETForestBase(intptr_t ID, bool isPostDom) 
271     : DominatorBase(ID, isPostDom), Nodes(), 
272       DFSInfoValid(false), SlowQueries(0) {}
273   
274   virtual void releaseMemory() { reset(); }
275
276   typedef std::map<BasicBlock*, ETNode*> ETMapType;
277
278   void updateDFSNumbers();
279     
280   /// dominates - Return true if A dominates B.
281   ///
282   inline bool dominates(BasicBlock *A, BasicBlock *B) {
283     if (A == B)
284       return true;
285     
286     ETNode *NodeA = getNode(A);
287     ETNode *NodeB = getNode(B);
288     
289     if (DFSInfoValid)
290       return NodeB->DominatedBy(NodeA);
291     else {
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.
294       SlowQueries++;
295       if (SlowQueries > 32) {
296         updateDFSNumbers();
297         return NodeB->DominatedBy(NodeA);
298       }
299       return NodeB->DominatedBySlow(NodeA);
300     }
301   }
302
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);
306
307   /// properlyDominates - Return true if A dominates B and A != B.
308   ///
309   bool properlyDominates(BasicBlock *A, BasicBlock *B) {
310     return dominates(A, B) && A != B;
311   }
312
313   /// isReachableFromEntry - Return true if A is dominated by the entry
314   /// block of the function containing it.
315   const bool isReachableFromEntry(BasicBlock* A);
316   
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);
321     
322     ETNode *Common = NodeA->NCA(NodeB);
323     if (!Common)
324       return NULL;
325     return Common->getData<BasicBlock>();
326   }
327   
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;
334   }
335   
336   void getChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
337     ETNode *NodeA = getNode(A);
338     if (!NodeA) return;
339     const ETNode* son = NodeA->getSon();
340     
341     if (!son) return;
342     children.push_back(son->getData<BasicBlock>());
343         
344     const ETNode* brother = son->getBrother();
345     while (brother != son) {
346       children.push_back(brother->getData<BasicBlock>());
347       brother = brother->getBrother();
348     }
349   }
350
351   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
352     AU.setPreservesAll();
353     AU.addRequired<DominatorTree>();
354   }
355   //===--------------------------------------------------------------------===//
356   // API to update Forest information based on modifications
357   // to the CFG...
358
359   /// addNewBlock - Add a new block to the CFG, with the specified immediate
360   /// dominator.
361   ///
362   void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
363
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.
368   ///
369   void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
370   /// print - Convert to human readable form
371   ///
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);
375   }
376 protected:
377   /// getNode - return the (Post)DominatorTree node for the specified basic
378   /// block.  This is the same as using operator[] on this class.
379   ///
380   inline ETNode *getNode(BasicBlock *BB) const {
381     ETMapType::const_iterator i = Nodes.find(BB);
382     return (i != Nodes.end()) ? i->second : 0;
383   }
384
385   inline ETNode *operator[](BasicBlock *BB) const {
386     return getNode(BB);
387   }
388
389   void reset();
390   ETMapType Nodes;
391   bool DFSInfoValid;
392   unsigned int SlowQueries;
393
394 };
395
396 //==-------------------------------------
397 /// ETForest Class - Concrete subclass of ETForestBase that is used to
398 /// compute a forwards ET-Forest.
399
400 class ETForest : public ETForestBase {
401 public:
402   static const char ID; // Pass identifcation, replacement for typeid
403
404   ETForest() : ETForestBase((intptr_t)&ID, false) {}
405
406   BasicBlock *getRoot() const {
407     assert(Roots.size() == 1 && "Should always have entry node!");
408     return Roots[0];
409   }
410
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();
415     calculate(DT);
416     return false;
417   }
418
419   void calculate(const DominatorTree &DT);
420   ETNode *getNodeForBlock(BasicBlock *BB);
421 };
422
423 //===----------------------------------------------------------------------===//
424 /// DominanceFrontierBase - Common base class for computing forward and inverse
425 /// dominance frontiers for a function.
426 ///
427 class DominanceFrontierBase : public DominatorBase {
428 public:
429   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
430   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
431 protected:
432   DomSetMapType Frontiers;
433 public:
434   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
435     : DominatorBase(ID, isPostDom) {}
436
437   virtual void releaseMemory() { Frontiers.clear(); }
438
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); }
448
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));
452   }
453
454   void addToFrontier(iterator I, BasicBlock *Node) {
455     assert(I != end() && "BB is not in DominanceFrontier!");
456     I->second.insert(Node);
457   }
458
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);
463   }
464
465   /// print - Convert to human readable form
466   ///
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);
470   }
471 };
472
473
474 //===-------------------------------------
475 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
476 /// used to compute a forward dominator frontiers.
477 ///
478 class DominanceFrontier : public DominanceFrontierBase {
479 public:
480   static const char ID; // Pass ID, replacement for typeid
481   DominanceFrontier() : 
482     DominanceFrontierBase((intptr_t)& ID, false) {}
483
484   BasicBlock *getRoot() const {
485     assert(Roots.size() == 1 && "Should always have entry node!");
486     return Roots[0];
487   }
488
489   virtual bool runOnFunction(Function &) {
490     Frontiers.clear();
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]]);
495     return false;
496   }
497
498   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
499     AU.setPreservesAll();
500     AU.addRequired<DominatorTree>();
501   }
502 private:
503   const DomSetType &calculate(const DominatorTree &DT,
504                               const DominatorTree::Node *Node);
505 };
506
507
508 } // End llvm namespace
509
510 #endif