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