Remove DomSet completely. This concludes work on PR1171.
[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   /// Return the nearest common dominator of A and B.
409   BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const  {
410     ETNode *NodeA = getNode(A);
411     ETNode *NodeB = getNode(B);
412     
413     ETNode *Common = NodeA->NCA(NodeB);
414     if (!Common)
415       return NULL;
416     return Common->getData<BasicBlock>();
417   }
418
419   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
420     AU.setPreservesAll();
421     AU.addRequired<ImmediateDominators>();
422   }
423   //===--------------------------------------------------------------------===//
424   // API to update Forest information based on modifications
425   // to the CFG...
426
427   /// addNewBlock - Add a new block to the CFG, with the specified immediate
428   /// dominator.
429   ///
430   void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
431
432   /// setImmediateDominator - Update the immediate dominator information to
433   /// change the current immediate dominator for the specified block
434   /// to another block.  This method requires that BB for NewIDom
435   /// already have an ETNode, otherwise just use addNewBlock.
436   ///
437   void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
438   /// print - Convert to human readable form
439   ///
440   virtual void print(std::ostream &OS, const Module* = 0) const;
441   void print(std::ostream *OS, const Module* M = 0) const {
442     if (OS) print(*OS, M);
443   }
444 protected:
445   /// getNode - return the (Post)DominatorTree node for the specified basic
446   /// block.  This is the same as using operator[] on this class.
447   ///
448   inline ETNode *getNode(BasicBlock *BB) const {
449     ETMapType::const_iterator i = Nodes.find(BB);
450     return (i != Nodes.end()) ? i->second : 0;
451   }
452
453   inline ETNode *operator[](BasicBlock *BB) const {
454     return getNode(BB);
455   }
456
457   void reset();
458   ETMapType Nodes;
459   bool DFSInfoValid;
460   unsigned int SlowQueries;
461
462 };
463
464 //==-------------------------------------
465 /// ETForest Class - Concrete subclass of ETForestBase that is used to
466 /// compute a forwards ET-Forest.
467
468 class ETForest : public ETForestBase {
469 public:
470   ETForest() : ETForestBase(false) {}
471
472   BasicBlock *getRoot() const {
473     assert(Roots.size() == 1 && "Should always have entry node!");
474     return Roots[0];
475   }
476
477   virtual bool runOnFunction(Function &F) {
478     reset();     // Reset from the last time we were run...
479     ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
480     Roots = ID.getRoots();
481     calculate(ID);
482     return false;
483   }
484
485   void calculate(const ImmediateDominators &ID);
486   ETNode *getNodeForBlock(BasicBlock *BB);
487 };
488
489 //===----------------------------------------------------------------------===//
490 /// DominanceFrontierBase - Common base class for computing forward and inverse
491 /// dominance frontiers for a function.
492 ///
493 class DominanceFrontierBase : public DominatorBase {
494 public:
495   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
496   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
497 protected:
498   DomSetMapType Frontiers;
499 public:
500   DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
501
502   virtual void releaseMemory() { Frontiers.clear(); }
503
504   // Accessor interface:
505   typedef DomSetMapType::iterator iterator;
506   typedef DomSetMapType::const_iterator const_iterator;
507   iterator       begin()       { return Frontiers.begin(); }
508   const_iterator begin() const { return Frontiers.begin(); }
509   iterator       end()         { return Frontiers.end(); }
510   const_iterator end()   const { return Frontiers.end(); }
511   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
512   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
513
514   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
515     assert(find(BB) == end() && "Block already in DominanceFrontier!");
516     Frontiers.insert(std::make_pair(BB, frontier));
517   }
518
519   void addToFrontier(iterator I, BasicBlock *Node) {
520     assert(I != end() && "BB is not in DominanceFrontier!");
521     I->second.insert(Node);
522   }
523
524   void removeFromFrontier(iterator I, BasicBlock *Node) {
525     assert(I != end() && "BB is not in DominanceFrontier!");
526     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
527     I->second.erase(Node);
528   }
529
530   /// print - Convert to human readable form
531   ///
532   virtual void print(std::ostream &OS, const Module* = 0) const;
533   void print(std::ostream *OS, const Module* M = 0) const {
534     if (OS) print(*OS, M);
535   }
536 };
537
538
539 //===-------------------------------------
540 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
541 /// used to compute a forward dominator frontiers.
542 ///
543 class DominanceFrontier : public DominanceFrontierBase {
544 public:
545   DominanceFrontier() : DominanceFrontierBase(false) {}
546
547   BasicBlock *getRoot() const {
548     assert(Roots.size() == 1 && "Should always have entry node!");
549     return Roots[0];
550   }
551
552   virtual bool runOnFunction(Function &) {
553     Frontiers.clear();
554     DominatorTree &DT = getAnalysis<DominatorTree>();
555     Roots = DT.getRoots();
556     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
557     calculate(DT, DT[Roots[0]]);
558     return false;
559   }
560
561   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
562     AU.setPreservesAll();
563     AU.addRequired<DominatorTree>();
564   }
565 private:
566   const DomSetType &calculate(const DominatorTree &DT,
567                               const DominatorTree::Node *Node);
568 };
569
570
571 } // End llvm namespace
572
573 #endif