Add and use DominatorTreeBase::findNearestCommonDominator().
[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   /// getIDomBlock - return basic block BB's immediate dominator basic block.
146   ///
147   BasicBlock *getIDomBlock(BasicBlock *BB) {
148     DomTreeNode *N = getNode(BB);
149     assert (N && "Missing dominator tree node");
150     DomTreeNode *I = N->getIDom();
151     assert (N && "Missing immediate dominator");
152     return I->getBlock();
153   }
154
155   /// getRootNode - This returns the entry node for the CFG of the function.  If
156   /// this tree represents the post-dominance relations for a function, however,
157   /// this root may be a node with the block == NULL.  This is the case when
158   /// there are multiple exit nodes from a particular function.  Consumers of
159   /// post-dominance information must be capable of dealing with this
160   /// possibility.
161   ///
162   DomTreeNode *getRootNode() { return RootNode; }
163   const DomTreeNode *getRootNode() const { return RootNode; }
164
165   /// properlyDominates - Returns true iff this dominates N and this != N.
166   /// Note that this is not a constant time operation!
167   ///
168   bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
169     if (A == 0 || B == 0) return false;
170     return dominatedBySlowTreeWalk(A, B);
171   }
172
173   inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
174     return properlyDominates(getNode(A), getNode(B));
175   }
176
177   bool dominatedBySlowTreeWalk(const DomTreeNode *A, 
178                                const DomTreeNode *B) const {
179     const DomTreeNode *IDom;
180     if (A == 0 || B == 0) return false;
181     while ((IDom = B->getIDom()) != 0 && IDom != A)
182       B = IDom;   // Walk up the tree
183     return IDom != 0;
184   }
185
186   void updateDFSNumbers();  
187
188   /// Return the nearest common dominator of A and B.
189   BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const  {
190     ETNode *NodeA = getNode(A)->getETNode();
191     ETNode *NodeB = getNode(B)->getETNode();
192     
193     ETNode *Common = NodeA->NCA(NodeB);
194     if (!Common)
195       return NULL;
196     return Common->getData<BasicBlock>();
197   }
198
199   /// isReachableFromEntry - Return true if A is dominated by the entry
200   /// block of the function containing it.
201   const bool isReachableFromEntry(BasicBlock* A);
202   
203   /// dominates - Returns true iff this dominates N.  Note that this is not a
204   /// constant time operation!
205   ///
206   inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
207     if (B == A) 
208       return true;  // A node trivially dominates itself.
209
210     if (A == 0 || B == 0)
211       return false;
212
213     ETNode *NodeA = A->getETNode();
214     ETNode *NodeB = B->getETNode();
215     
216     if (DFSInfoValid)
217       return NodeB->DominatedBy(NodeA);
218
219     // If we end up with too many slow queries, just update the
220     // DFS numbers on the theory that we are going to keep querying.
221     SlowQueries++;
222     if (SlowQueries > 32) {
223       updateDFSNumbers();
224       return NodeB->DominatedBy(NodeA);
225     }
226     //return NodeB->DominatedBySlow(NodeA);
227     return dominatedBySlowTreeWalk(A, B);
228   }
229
230   inline bool dominates(BasicBlock *A, BasicBlock *B) {
231     if (A == B) 
232       return true;
233     
234     return dominates(getNode(A), getNode(B));
235   }
236
237   /// findNearestCommonDominator - Find nearest common dominator basic block
238   /// for basic block A and B. If there is no such block then return NULL.
239   BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
240
241   // dominates - Return true if A dominates B. This performs the
242   // special checks necessary if A and B are in the same basic block.
243   bool dominates(Instruction *A, Instruction *B);
244
245   //===--------------------------------------------------------------------===//
246   // API to update (Post)DominatorTree information based on modifications to
247   // the CFG...
248
249   /// addNewBlock - Add a new node to the dominator tree information.  This
250   /// creates a new node as a child of DomBB dominator node,linking it into 
251   /// the children list of the immediate dominator.
252   DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
253     assert(getNode(BB) == 0 && "Block already in dominator tree!");
254     DomTreeNode *IDomNode = getNode(DomBB);
255     assert(IDomNode && "Not immediate dominator specified for block!");
256     DFSInfoValid = false;
257     ETNode *E = new ETNode(BB);
258     ETNodes[BB] = E;
259     return DomTreeNodes[BB] = 
260       IDomNode->addChild(new DomTreeNode(BB, IDomNode, E));
261   }
262
263   /// changeImmediateDominator - This method is used to update the dominator
264   /// tree information when a node's immediate dominator changes.
265   ///
266   void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
267     assert(N && NewIDom && "Cannot change null node pointers!");
268     DFSInfoValid = false;
269     N->setIDom(NewIDom);
270   }
271
272   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
273     changeImmediateDominator(getNode(BB), getNode(NewBB));
274   }
275
276   /// removeNode - Removes a node from the dominator tree.  Block must not
277   /// dominate any other blocks.  Invalidates any node pointing to removed
278   /// block.
279   void removeNode(BasicBlock *BB) {
280     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
281     DomTreeNodes.erase(BB);
282   }
283
284   /// print - Convert to human readable form
285   ///
286   virtual void print(std::ostream &OS, const Module* = 0) const;
287   void print(std::ostream *OS, const Module* M = 0) const {
288     if (OS) print(*OS, M);
289   }
290   virtual void dump();
291 };
292
293 //===-------------------------------------
294 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
295 /// compute a normal dominator tree.
296 ///
297 class DominatorTree : public DominatorTreeBase {
298 public:
299   static char ID; // Pass ID, replacement for typeid
300   DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
301   
302   BasicBlock *getRoot() const {
303     assert(Roots.size() == 1 && "Should always have entry node!");
304     return Roots[0];
305   }
306   
307   virtual bool runOnFunction(Function &F);
308   
309   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
310     AU.setPreservesAll();
311   }
312 private:
313   void calculate(Function& F);
314   DomTreeNode *getNodeForBlock(BasicBlock *BB);
315   unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
316   void Compress(BasicBlock *V);
317   BasicBlock *Eval(BasicBlock *v);
318   void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
319   inline BasicBlock *getIDom(BasicBlock *BB) const {
320       std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
321       return I != IDoms.end() ? I->second : 0;
322     }
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 /// ET-Forest Class - Class used to construct forwards and backwards 
354 /// ET-Forests
355 ///
356 class ETForestBase : public DominatorBase {
357 public:
358   ETForestBase(intptr_t ID, bool isPostDom) 
359     : DominatorBase(ID, isPostDom), Nodes(), 
360       DFSInfoValid(false), SlowQueries(0) {}
361   
362   virtual void releaseMemory() { reset(); }
363
364   typedef std::map<BasicBlock*, ETNode*> ETMapType;
365
366   // FIXME : There is no need to make this interface public. 
367   // Fix predicate simplifier.
368   void updateDFSNumbers();
369     
370   /// dominates - Return true if A dominates B.
371   ///
372   inline bool dominates(BasicBlock *A, BasicBlock *B) {
373     if (A == B)
374       return true;
375     
376     ETNode *NodeA = getNode(A);
377     ETNode *NodeB = getNode(B);
378     
379     if (DFSInfoValid)
380       return NodeB->DominatedBy(NodeA);
381     else {
382       // If we end up with too many slow queries, just update the
383       // DFS numbers on the theory that we are going to keep querying.
384       SlowQueries++;
385       if (SlowQueries > 32) {
386         updateDFSNumbers();
387         return NodeB->DominatedBy(NodeA);
388       }
389       return NodeB->DominatedBySlow(NodeA);
390     }
391   }
392
393   // dominates - Return true if A dominates B. This performs the
394   // special checks necessary if A and B are in the same basic block.
395   bool dominates(Instruction *A, Instruction *B);
396
397   /// properlyDominates - Return true if A dominates B and A != B.
398   ///
399   bool properlyDominates(BasicBlock *A, BasicBlock *B) {
400     return dominates(A, B) && A != B;
401   }
402
403   /// isReachableFromEntry - Return true if A is dominated by the entry
404   /// block of the function containing it.
405   const bool isReachableFromEntry(BasicBlock* A);
406   
407   /// Return the nearest common dominator of A and B.
408   BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const  {
409     ETNode *NodeA = getNode(A);
410     ETNode *NodeB = getNode(B);
411     
412     ETNode *Common = NodeA->NCA(NodeB);
413     if (!Common)
414       return NULL;
415     return Common->getData<BasicBlock>();
416   }
417   
418   /// Return the immediate dominator of A.
419   BasicBlock *getIDom(BasicBlock *A) const {
420     ETNode *NodeA = getNode(A);
421     if (!NodeA) return 0;
422     const ETNode *idom = NodeA->getFather();
423     return idom ? idom->getData<BasicBlock>() : 0;
424   }
425   
426   void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
427     ETNode *NodeA = getNode(A);
428     if (!NodeA) return;
429     const ETNode* son = NodeA->getSon();
430     
431     if (!son) return;
432     children.push_back(son->getData<BasicBlock>());
433         
434     const ETNode* brother = son->getBrother();
435     while (brother != son) {
436       children.push_back(brother->getData<BasicBlock>());
437       brother = brother->getBrother();
438     }
439   }
440
441   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
442     AU.setPreservesAll();
443     AU.addRequired<DominatorTree>();
444   }
445   //===--------------------------------------------------------------------===//
446   // API to update Forest information based on modifications
447   // to the CFG...
448
449   /// addNewBlock - Add a new block to the CFG, with the specified immediate
450   /// dominator.
451   ///
452   void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
453
454   /// setImmediateDominator - Update the immediate dominator information to
455   /// change the current immediate dominator for the specified block
456   /// to another block.  This method requires that BB for NewIDom
457   /// already have an ETNode, otherwise just use addNewBlock.
458   ///
459   void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
460   /// print - Convert to human readable form
461   ///
462   virtual void print(std::ostream &OS, const Module* = 0) const;
463   void print(std::ostream *OS, const Module* M = 0) const {
464     if (OS) print(*OS, M);
465   }
466   virtual void dump();
467 protected:
468   /// getNode - return the (Post)DominatorTree node for the specified basic
469   /// block.  This is the same as using operator[] on this class.
470   ///
471   inline ETNode *getNode(BasicBlock *BB) const {
472     ETMapType::const_iterator i = Nodes.find(BB);
473     return (i != Nodes.end()) ? i->second : 0;
474   }
475
476   inline ETNode *operator[](BasicBlock *BB) const {
477     return getNode(BB);
478   }
479
480   void reset();
481   ETMapType Nodes;
482   bool DFSInfoValid;
483   unsigned int SlowQueries;
484
485 };
486
487 //==-------------------------------------
488 /// ETForest Class - Concrete subclass of ETForestBase that is used to
489 /// compute a forwards ET-Forest.
490
491 class ETForest : public ETForestBase {
492 public:
493   static char ID; // Pass identification, replacement for typeid
494
495   ETForest() : ETForestBase((intptr_t)&ID, false) {}
496
497   BasicBlock *getRoot() const {
498     assert(Roots.size() == 1 && "Should always have entry node!");
499     return Roots[0];
500   }
501
502   virtual bool runOnFunction(Function &F) {
503     reset();     // Reset from the last time we were run...
504     DominatorTree &DT = getAnalysis<DominatorTree>();
505     Roots = DT.getRoots();
506     calculate(DT);
507     return false;
508   }
509
510   void calculate(const DominatorTree &DT);
511   // FIXME : There is no need to make getNodeForBlock public. Fix
512   // predicate simplifier.
513   ETNode *getNodeForBlock(BasicBlock *BB);
514 };
515
516 //===----------------------------------------------------------------------===//
517 /// DominanceFrontierBase - Common base class for computing forward and inverse
518 /// dominance frontiers for a function.
519 ///
520 class DominanceFrontierBase : public DominatorBase {
521 public:
522   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
523   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
524 protected:
525   DomSetMapType Frontiers;
526 public:
527   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
528     : DominatorBase(ID, isPostDom) {}
529
530   virtual void releaseMemory() { Frontiers.clear(); }
531
532   // Accessor interface:
533   typedef DomSetMapType::iterator iterator;
534   typedef DomSetMapType::const_iterator const_iterator;
535   iterator       begin()       { return Frontiers.begin(); }
536   const_iterator begin() const { return Frontiers.begin(); }
537   iterator       end()         { return Frontiers.end(); }
538   const_iterator end()   const { return Frontiers.end(); }
539   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
540   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
541
542   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
543     assert(find(BB) == end() && "Block already in DominanceFrontier!");
544     Frontiers.insert(std::make_pair(BB, frontier));
545   }
546
547   void addToFrontier(iterator I, BasicBlock *Node) {
548     assert(I != end() && "BB is not in DominanceFrontier!");
549     I->second.insert(Node);
550   }
551
552   void removeFromFrontier(iterator I, BasicBlock *Node) {
553     assert(I != end() && "BB is not in DominanceFrontier!");
554     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
555     I->second.erase(Node);
556   }
557
558   /// print - Convert to human readable form
559   ///
560   virtual void print(std::ostream &OS, const Module* = 0) const;
561   void print(std::ostream *OS, const Module* M = 0) const {
562     if (OS) print(*OS, M);
563   }
564   virtual void dump();
565 };
566
567
568 //===-------------------------------------
569 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
570 /// used to compute a forward dominator frontiers.
571 ///
572 class DominanceFrontier : public DominanceFrontierBase {
573 public:
574   static char ID; // Pass ID, replacement for typeid
575   DominanceFrontier() : 
576     DominanceFrontierBase((intptr_t)& ID, false) {}
577
578   BasicBlock *getRoot() const {
579     assert(Roots.size() == 1 && "Should always have entry node!");
580     return Roots[0];
581   }
582
583   virtual bool runOnFunction(Function &) {
584     Frontiers.clear();
585     DominatorTree &DT = getAnalysis<DominatorTree>();
586     Roots = DT.getRoots();
587     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
588     calculate(DT, DT[Roots[0]]);
589     return false;
590   }
591
592   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
593     AU.setPreservesAll();
594     AU.addRequired<DominatorTree>();
595   }
596
597 private:
598   const DomSetType &calculate(const DominatorTree &DT,
599                               const DomTreeNode *Node);
600 };
601
602
603 } // End llvm namespace
604
605 #endif