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