Remove ETForest.
[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 dominators as an explicit tree structure.
12 //  2. DominanceFrontier: Calculate and hold the dominance frontier for a
13 //     function.
14 //
15 //  These data structures are listed in increasing order of complexity.  It
16 //  takes longer to calculate the dominator frontier, for example, than the
17 //  DominatorTree mapping.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_ANALYSIS_DOMINATORS_H
22 #define LLVM_ANALYSIS_DOMINATORS_H
23
24 #include "llvm/Pass.h"
25 #include <set>
26
27 namespace llvm {
28
29 class Instruction;
30
31 template <typename GraphType> struct GraphTraits;
32
33 //===----------------------------------------------------------------------===//
34 /// DominatorBase - Base class that other, more interesting dominator analyses
35 /// inherit from.
36 ///
37 class DominatorBase : public FunctionPass {
38 protected:
39   std::vector<BasicBlock*> Roots;
40   const bool IsPostDominators;
41   inline DominatorBase(intptr_t ID, bool isPostDom) : 
42     FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
43 public:
44
45   /// getRoots -  Return the root blocks of the current CFG.  This may include
46   /// multiple blocks if we are computing post dominators.  For forward
47   /// dominators, this will always be a single block (the entry node).
48   ///
49   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
50
51   /// isPostDominator - Returns true if analysis based of postdoms
52   ///
53   bool isPostDominator() const { return IsPostDominators; }
54 };
55
56
57 //===----------------------------------------------------------------------===//
58 // DomTreeNode - Dominator Tree Node
59 class DominatorTreeBase;
60 class PostDominatorTree;
61 class DomTreeNode {
62   BasicBlock *TheBB;
63   DomTreeNode *IDom;
64   std::vector<DomTreeNode*> Children;
65   int DFSNumIn, DFSNumOut;
66
67   friend class DominatorTreeBase;
68   friend class PostDominatorTree;
69 public:
70   typedef std::vector<DomTreeNode*>::iterator iterator;
71   typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
72   
73   iterator begin()             { return Children.begin(); }
74   iterator end()               { return Children.end(); }
75   const_iterator begin() const { return Children.begin(); }
76   const_iterator end()   const { return Children.end(); }
77   
78   inline BasicBlock *getBlock() const { return TheBB; }
79   inline DomTreeNode *getIDom() const { return IDom; }
80   inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
81   
82   inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
83     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
84   inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
85   void setIDom(DomTreeNode *NewIDom);
86
87 private:
88   // Return true if this node is dominated by other. Use this only if DFS info is valid.
89   bool DominatedBy(const DomTreeNode *other) const {
90     return this->DFSNumIn >= other->DFSNumIn &&
91       this->DFSNumOut <= other->DFSNumOut;
92   }
93
94   /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
95   /// in dfs order.
96   void assignDFSNumber(int num);
97 };
98
99 //===----------------------------------------------------------------------===//
100 /// DominatorTree - Calculate the immediate dominator tree for a function.
101 ///
102 class DominatorTreeBase : public DominatorBase {
103
104 protected:
105   void reset();
106   typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
107   DomTreeNodeMapType DomTreeNodes;
108   DomTreeNode *RootNode;
109
110   bool DFSInfoValid;
111   unsigned int SlowQueries;
112   // Information record used during immediate dominators computation.
113   struct InfoRec {
114     unsigned Semi;
115     unsigned Size;
116     BasicBlock *Label, *Parent, *Child, *Ancestor;
117
118     std::vector<BasicBlock*> Bucket;
119
120     InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
121   };
122
123   std::map<BasicBlock*, BasicBlock*> IDoms;
124
125   // Vertex - Map the DFS number to the BasicBlock*
126   std::vector<BasicBlock*> Vertex;
127
128   // Info - Collection of information used during the computation of idoms.
129   std::map<BasicBlock*, InfoRec> Info;
130
131   void updateDFSNumbers();
132
133   public:
134   DominatorTreeBase(intptr_t ID, bool isPostDom) 
135     : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
136   ~DominatorTreeBase() { reset(); }
137
138   virtual void releaseMemory() { reset(); }
139
140   /// getNode - return the (Post)DominatorTree node for the specified basic
141   /// block.  This is the same as using operator[] on this class.
142   ///
143   inline DomTreeNode *getNode(BasicBlock *BB) const {
144     DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
145     return (i != DomTreeNodes.end()) ? i->second : 0;
146   }
147
148   inline DomTreeNode *operator[](BasicBlock *BB) const {
149     return getNode(BB);
150   }
151
152   /// getIDomBlock - return basic block BB's immediate dominator basic block.
153   ///
154   BasicBlock *getIDomBlock(BasicBlock *BB) {
155     DomTreeNode *N = getNode(BB);
156     assert (N && "Missing dominator tree node");
157     DomTreeNode *I = N->getIDom();
158     assert (N && "Missing immediate dominator");
159     return I->getBlock();
160   }
161
162   /// getRootNode - This returns the entry node for the CFG of the function.  If
163   /// this tree represents the post-dominance relations for a function, however,
164   /// this root may be a node with the block == NULL.  This is the case when
165   /// there are multiple exit nodes from a particular function.  Consumers of
166   /// post-dominance information must be capable of dealing with this
167   /// possibility.
168   ///
169   DomTreeNode *getRootNode() { return RootNode; }
170   const DomTreeNode *getRootNode() const { return RootNode; }
171
172   /// properlyDominates - Returns true iff this dominates N and this != N.
173   /// Note that this is not a constant time operation!
174   ///
175   bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
176     if (A == 0 || B == 0) return false;
177     return dominatedBySlowTreeWalk(A, B);
178   }
179
180   inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
181     return properlyDominates(getNode(A), getNode(B));
182   }
183
184   bool dominatedBySlowTreeWalk(const DomTreeNode *A, 
185                                const DomTreeNode *B) const {
186     const DomTreeNode *IDom;
187     if (A == 0 || B == 0) return false;
188     while ((IDom = B->getIDom()) != 0 && IDom != A)
189       B = IDom;   // Walk up the tree
190     return IDom != 0;
191   }
192
193
194   /// isReachableFromEntry - Return true if A is dominated by the entry
195   /// block of the function containing it.
196   const bool isReachableFromEntry(BasicBlock* A);
197   
198   /// dominates - Returns true iff A dominates B.  Note that this is not a
199   /// constant time operation!
200   ///
201   inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
202     if (B == A) 
203       return true;  // A node trivially dominates itself.
204
205     if (A == 0 || B == 0)
206       return false;
207
208     if (DFSInfoValid)
209       return B->DominatedBy(A);
210
211     // If we end up with too many slow queries, just update the
212     // DFS numbers on the theory that we are going to keep querying.
213     SlowQueries++;
214     if (SlowQueries > 32) {
215       updateDFSNumbers();
216       return B->DominatedBy(A);
217     }
218
219     return dominatedBySlowTreeWalk(A, B);
220   }
221
222   inline bool dominates(BasicBlock *A, BasicBlock *B) {
223     if (A == B) 
224       return true;
225     
226     return dominates(getNode(A), getNode(B));
227   }
228
229   /// findNearestCommonDominator - Find nearest common dominator basic block
230   /// for basic block A and B. If there is no such block then return NULL.
231   BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
232
233   // dominates - Return true if A dominates B. This performs the
234   // special checks necessary if A and B are in the same basic block.
235   bool dominates(Instruction *A, Instruction *B);
236
237   //===--------------------------------------------------------------------===//
238   // API to update (Post)DominatorTree information based on modifications to
239   // the CFG...
240
241   /// addNewBlock - Add a new node to the dominator tree information.  This
242   /// creates a new node as a child of DomBB dominator node,linking it into 
243   /// the children list of the immediate dominator.
244   DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
245     assert(getNode(BB) == 0 && "Block already in dominator tree!");
246     DomTreeNode *IDomNode = getNode(DomBB);
247     assert(IDomNode && "Not immediate dominator specified for block!");
248     DFSInfoValid = false;
249     return DomTreeNodes[BB] = 
250       IDomNode->addChild(new DomTreeNode(BB, IDomNode));
251   }
252
253   /// changeImmediateDominator - This method is used to update the dominator
254   /// tree information when a node's immediate dominator changes.
255   ///
256   void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
257     assert(N && NewIDom && "Cannot change null node pointers!");
258     DFSInfoValid = false;
259     N->setIDom(NewIDom);
260   }
261
262   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
263     changeImmediateDominator(getNode(BB), getNode(NewBB));
264   }
265
266   /// removeNode - Removes a node from the dominator tree.  Block must not
267   /// dominate any other blocks.  Invalidates any node pointing to removed
268   /// block.
269   void removeNode(BasicBlock *BB) {
270     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
271     DomTreeNodes.erase(BB);
272   }
273
274   /// print - Convert to human readable form
275   ///
276   virtual void print(std::ostream &OS, const Module* = 0) const;
277   void print(std::ostream *OS, const Module* M = 0) const {
278     if (OS) print(*OS, M);
279   }
280   virtual void dump();
281 };
282
283 //===-------------------------------------
284 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
285 /// compute a normal dominator tree.
286 ///
287 class DominatorTree : public DominatorTreeBase {
288 public:
289   static char ID; // Pass ID, replacement for typeid
290   DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
291   
292   BasicBlock *getRoot() const {
293     assert(Roots.size() == 1 && "Should always have entry node!");
294     return Roots[0];
295   }
296   
297   virtual bool runOnFunction(Function &F);
298   
299   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
300     AU.setPreservesAll();
301   }
302
303   /// splitBlock
304   /// BB is split and now it has one successor. Update dominator tree to
305   /// reflect this change.
306   void splitBlock(BasicBlock *BB);
307 private:
308   void calculate(Function& F);
309   DomTreeNode *getNodeForBlock(BasicBlock *BB);
310   unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
311   void Compress(BasicBlock *V);
312   BasicBlock *Eval(BasicBlock *v);
313   void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
314   inline BasicBlock *getIDom(BasicBlock *BB) const {
315       std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
316       return I != IDoms.end() ? I->second : 0;
317     }
318 };
319
320 //===-------------------------------------
321 /// DominatorTree GraphTraits specialization so the DominatorTree can be
322 /// iterable by generic graph iterators.
323 ///
324 template <> struct GraphTraits<DomTreeNode*> {
325   typedef DomTreeNode NodeType;
326   typedef NodeType::iterator  ChildIteratorType;
327   
328   static NodeType *getEntryNode(NodeType *N) {
329     return N;
330   }
331   static inline ChildIteratorType child_begin(NodeType* N) {
332     return N->begin();
333   }
334   static inline ChildIteratorType child_end(NodeType* N) {
335     return N->end();
336   }
337 };
338
339 template <> struct GraphTraits<DominatorTree*>
340   : public GraphTraits<DomTreeNode*> {
341   static NodeType *getEntryNode(DominatorTree *DT) {
342     return DT->getRootNode();
343   }
344 };
345
346
347 //===----------------------------------------------------------------------===//
348 /// DominanceFrontierBase - Common base class for computing forward and inverse
349 /// dominance frontiers for a function.
350 ///
351 class DominanceFrontierBase : public DominatorBase {
352 public:
353   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
354   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
355 protected:
356   DomSetMapType Frontiers;
357 public:
358   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
359     : DominatorBase(ID, isPostDom) {}
360
361   virtual void releaseMemory() { Frontiers.clear(); }
362
363   // Accessor interface:
364   typedef DomSetMapType::iterator iterator;
365   typedef DomSetMapType::const_iterator const_iterator;
366   iterator       begin()       { return Frontiers.begin(); }
367   const_iterator begin() const { return Frontiers.begin(); }
368   iterator       end()         { return Frontiers.end(); }
369   const_iterator end()   const { return Frontiers.end(); }
370   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
371   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
372
373   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
374     assert(find(BB) == end() && "Block already in DominanceFrontier!");
375     Frontiers.insert(std::make_pair(BB, frontier));
376   }
377
378   void addToFrontier(iterator I, BasicBlock *Node) {
379     assert(I != end() && "BB is not in DominanceFrontier!");
380     I->second.insert(Node);
381   }
382
383   void removeFromFrontier(iterator I, BasicBlock *Node) {
384     assert(I != end() && "BB is not in DominanceFrontier!");
385     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
386     I->second.erase(Node);
387   }
388
389   /// print - Convert to human readable form
390   ///
391   virtual void print(std::ostream &OS, const Module* = 0) const;
392   void print(std::ostream *OS, const Module* M = 0) const {
393     if (OS) print(*OS, M);
394   }
395   virtual void dump();
396 };
397
398
399 //===-------------------------------------
400 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
401 /// used to compute a forward dominator frontiers.
402 ///
403 class DominanceFrontier : public DominanceFrontierBase {
404 public:
405   static char ID; // Pass ID, replacement for typeid
406   DominanceFrontier() : 
407     DominanceFrontierBase((intptr_t)& ID, false) {}
408
409   BasicBlock *getRoot() const {
410     assert(Roots.size() == 1 && "Should always have entry node!");
411     return Roots[0];
412   }
413
414   virtual bool runOnFunction(Function &) {
415     Frontiers.clear();
416     DominatorTree &DT = getAnalysis<DominatorTree>();
417     Roots = DT.getRoots();
418     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
419     calculate(DT, DT[Roots[0]]);
420     return false;
421   }
422
423   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
424     AU.setPreservesAll();
425     AU.addRequired<DominatorTree>();
426   }
427
428   /// splitBlock
429   /// BB is split and now it has one successor. Update dominace frontier to
430   /// reflect this change.
431   void splitBlock(BasicBlock *BB);
432
433 private:
434   const DomSetType &calculate(const DominatorTree &DT,
435                               const DomTreeNode *Node);
436 };
437
438
439 } // End llvm namespace
440
441 #endif