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