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