Factor the dominator tree calculation details out into DominatorCalculation.h. This
[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   unsigned DFSPass(BasicBlock *V, unsigned N);
133
134 public:
135   DominatorTreeBase(intptr_t ID, bool isPostDom) 
136     : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
137   ~DominatorTreeBase() { reset(); }
138
139   virtual void releaseMemory() { reset(); }
140
141   /// getNode - return the (Post)DominatorTree node for the specified basic
142   /// block.  This is the same as using operator[] on this class.
143   ///
144   inline DomTreeNode *getNode(BasicBlock *BB) const {
145     DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
146     return I != DomTreeNodes.end() ? I->second : 0;
147   }
148
149   inline DomTreeNode *operator[](BasicBlock *BB) const {
150     return getNode(BB);
151   }
152
153   /// getRootNode - This returns the entry node for the CFG of the function.  If
154   /// this tree represents the post-dominance relations for a function, however,
155   /// this root may be a node with the block == NULL.  This is the case when
156   /// there are multiple exit nodes from a particular function.  Consumers of
157   /// post-dominance information must be capable of dealing with this
158   /// possibility.
159   ///
160   DomTreeNode *getRootNode() { return RootNode; }
161   const DomTreeNode *getRootNode() const { return RootNode; }
162
163   /// properlyDominates - Returns true iff this dominates N and this != N.
164   /// Note that this is not a constant time operation!
165   ///
166   bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
167     if (A == 0 || B == 0) return false;
168     return dominatedBySlowTreeWalk(A, B);
169   }
170
171   inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
172     return properlyDominates(getNode(A), getNode(B));
173   }
174
175   bool dominatedBySlowTreeWalk(const DomTreeNode *A, 
176                                const DomTreeNode *B) const {
177     const DomTreeNode *IDom;
178     if (A == 0 || B == 0) return false;
179     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
180       B = IDom;   // Walk up the tree
181     return IDom != 0;
182   }
183
184
185   /// isReachableFromEntry - Return true if A is dominated by the entry
186   /// block of the function containing it.
187   const bool isReachableFromEntry(BasicBlock* A);
188   
189   /// dominates - Returns true iff A dominates B.  Note that this is not a
190   /// constant time operation!
191   ///
192   inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
193     if (B == A) 
194       return true;  // A node trivially dominates itself.
195
196     if (A == 0 || B == 0)
197       return false;
198
199     if (DFSInfoValid)
200       return B->DominatedBy(A);
201
202     // If we end up with too many slow queries, just update the
203     // DFS numbers on the theory that we are going to keep querying.
204     SlowQueries++;
205     if (SlowQueries > 32) {
206       updateDFSNumbers();
207       return B->DominatedBy(A);
208     }
209
210     return dominatedBySlowTreeWalk(A, B);
211   }
212
213   inline bool dominates(BasicBlock *A, BasicBlock *B) {
214     if (A == B) 
215       return true;
216     
217     return dominates(getNode(A), getNode(B));
218   }
219
220   /// findNearestCommonDominator - Find nearest common dominator basic block
221   /// for basic block A and B. If there is no such block then return NULL.
222   BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
223
224   // dominates - Return true if A dominates B. This performs the
225   // special checks necessary if A and B are in the same basic block.
226   bool dominates(Instruction *A, Instruction *B);
227
228   //===--------------------------------------------------------------------===//
229   // API to update (Post)DominatorTree information based on modifications to
230   // the CFG...
231
232   /// addNewBlock - Add a new node to the dominator tree information.  This
233   /// creates a new node as a child of DomBB dominator node,linking it into 
234   /// the children list of the immediate dominator.
235   DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
236     assert(getNode(BB) == 0 && "Block already in dominator tree!");
237     DomTreeNode *IDomNode = getNode(DomBB);
238     assert(IDomNode && "Not immediate dominator specified for block!");
239     DFSInfoValid = false;
240     return DomTreeNodes[BB] = 
241       IDomNode->addChild(new DomTreeNode(BB, IDomNode));
242   }
243
244   /// changeImmediateDominator - This method is used to update the dominator
245   /// tree information when a node's immediate dominator changes.
246   ///
247   void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
248     assert(N && NewIDom && "Cannot change null node pointers!");
249     DFSInfoValid = false;
250     N->setIDom(NewIDom);
251   }
252
253   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
254     changeImmediateDominator(getNode(BB), getNode(NewBB));
255   }
256
257   /// eraseNode - Removes a node from  the dominator tree. Block must not
258   /// domiante any other blocks. Removes node from its immediate dominator's
259   /// children list. Deletes dominator node associated with basic block BB.
260   void eraseNode(BasicBlock *BB);
261
262   /// removeNode - Removes a node from the dominator tree.  Block must not
263   /// dominate any other blocks.  Invalidates any node pointing to removed
264   /// block.
265   void removeNode(BasicBlock *BB) {
266     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
267     DomTreeNodes.erase(BB);
268   }
269
270   /// print - Convert to human readable form
271   ///
272   virtual void print(std::ostream &OS, const Module* = 0) const;
273   void print(std::ostream *OS, const Module* M = 0) const {
274     if (OS) print(*OS, M);
275   }
276   virtual void dump();
277   
278 protected:
279   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
280   /// dominator tree in dfs order.
281   void updateDFSNumbers();
282   
283   DomTreeNode *getNodeForBlock(BasicBlock *BB);
284   
285   inline BasicBlock *getIDom(BasicBlock *BB) const {
286     DenseMap<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
287     return I != IDoms.end() ? I->second : 0;
288   }
289 };
290
291 //===-------------------------------------
292 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
293 /// compute a normal dominator tree.
294 ///
295 class DominatorTree : public DominatorTreeBase {
296 public:
297   static char ID; // Pass ID, replacement for typeid
298   DominatorTree() : DominatorTreeBase(intptr_t(&ID), false) {}
299   
300   BasicBlock *getRoot() const {
301     assert(Roots.size() == 1 && "Should always have entry node!");
302     return Roots[0];
303   }
304   
305   virtual bool runOnFunction(Function &F);
306   
307   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
308     AU.setPreservesAll();
309   }
310
311   /// splitBlock
312   /// BB is split and now it has one successor. Update dominator tree to
313   /// reflect this change.
314   void splitBlock(BasicBlock *BB);
315
316 private:
317   friend void DTcalculate(DominatorTree& DT, Function& F);
318   friend void DTCompress(DominatorTree& DT, BasicBlock *VIn);
319   friend BasicBlock *DTEval(DominatorTree& DT, BasicBlock *v);
320   friend void DTLink(DominatorTree& DT, BasicBlock *V,
321                      BasicBlock *W, InfoRec &WInfo);
322 };
323
324 //===-------------------------------------
325 /// DominatorTree GraphTraits specialization so the DominatorTree can be
326 /// iterable by generic graph iterators.
327 ///
328 template <> struct GraphTraits<DomTreeNode*> {
329   typedef DomTreeNode NodeType;
330   typedef NodeType::iterator  ChildIteratorType;
331   
332   static NodeType *getEntryNode(NodeType *N) {
333     return N;
334   }
335   static inline ChildIteratorType child_begin(NodeType* N) {
336     return N->begin();
337   }
338   static inline ChildIteratorType child_end(NodeType* N) {
339     return N->end();
340   }
341 };
342
343 template <> struct GraphTraits<DominatorTree*>
344   : public GraphTraits<DomTreeNode*> {
345   static NodeType *getEntryNode(DominatorTree *DT) {
346     return DT->getRootNode();
347   }
348 };
349
350
351 //===----------------------------------------------------------------------===//
352 /// DominanceFrontierBase - Common base class for computing forward and inverse
353 /// dominance frontiers for a function.
354 ///
355 class DominanceFrontierBase : public DominatorBase {
356 public:
357   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
358   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
359 protected:
360   DomSetMapType Frontiers;
361 public:
362   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
363     : DominatorBase(ID, isPostDom) {}
364
365   virtual void releaseMemory() { Frontiers.clear(); }
366
367   // Accessor interface:
368   typedef DomSetMapType::iterator iterator;
369   typedef DomSetMapType::const_iterator const_iterator;
370   iterator       begin()       { return Frontiers.begin(); }
371   const_iterator begin() const { return Frontiers.begin(); }
372   iterator       end()         { return Frontiers.end(); }
373   const_iterator end()   const { return Frontiers.end(); }
374   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
375   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
376
377   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
378     assert(find(BB) == end() && "Block already in DominanceFrontier!");
379     Frontiers.insert(std::make_pair(BB, frontier));
380   }
381
382   /// removeBlock - Remove basic block BB's frontier.
383   void removeBlock(BasicBlock *BB) {
384     assert(find(BB) != end() && "Block is not in DominanceFrontier!");
385     for (iterator I = begin(), E = end(); I != E; ++I)
386       I->second.erase(BB);
387     Frontiers.erase(BB);
388   }
389
390   void addToFrontier(iterator I, BasicBlock *Node) {
391     assert(I != end() && "BB is not in DominanceFrontier!");
392     I->second.insert(Node);
393   }
394
395   void removeFromFrontier(iterator I, BasicBlock *Node) {
396     assert(I != end() && "BB is not in DominanceFrontier!");
397     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
398     I->second.erase(Node);
399   }
400
401   /// print - Convert to human readable form
402   ///
403   virtual void print(std::ostream &OS, const Module* = 0) const;
404   void print(std::ostream *OS, const Module* M = 0) const {
405     if (OS) print(*OS, M);
406   }
407   virtual void dump();
408 };
409
410
411 //===-------------------------------------
412 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
413 /// used to compute a forward dominator frontiers.
414 ///
415 class DominanceFrontier : public DominanceFrontierBase {
416 public:
417   static char ID; // Pass ID, replacement for typeid
418   DominanceFrontier() : 
419     DominanceFrontierBase(intptr_t(&ID), false) {}
420
421   BasicBlock *getRoot() const {
422     assert(Roots.size() == 1 && "Should always have entry node!");
423     return Roots[0];
424   }
425
426   virtual bool runOnFunction(Function &) {
427     Frontiers.clear();
428     DominatorTree &DT = getAnalysis<DominatorTree>();
429     Roots = DT.getRoots();
430     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
431     calculate(DT, DT[Roots[0]]);
432     return false;
433   }
434
435   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
436     AU.setPreservesAll();
437     AU.addRequired<DominatorTree>();
438   }
439
440   /// splitBlock - BB is split and now it has one successor. Update dominance
441   /// frontier to reflect this change.
442   void splitBlock(BasicBlock *BB);
443
444   /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
445   /// to reflect this change.
446   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
447                                 DominatorTree *DT) {
448     // NewBB is now  dominating BB. Which means BB's dominance
449     // frontier is now part of NewBB's dominance frontier. However, BB
450     // itself is not member of NewBB's dominance frontier.
451     DominanceFrontier::iterator NewDFI = find(NewBB);
452     DominanceFrontier::iterator DFI = find(BB);
453     DominanceFrontier::DomSetType BBSet = DFI->second;
454     for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
455            BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
456       BasicBlock *DFMember = *BBSetI;
457       // Insert only if NewBB dominates DFMember.
458       if (!DT->dominates(NewBB, DFMember))
459         NewDFI->second.insert(DFMember);
460     }
461     NewDFI->second.erase(BB);
462   }
463
464 private:
465   const DomSetType &calculate(const DominatorTree &DT,
466                               const DomTreeNode *Node);
467 };
468
469
470 } // End llvm namespace
471
472 #endif