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