Fix some formatting.
[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. DominanceFrontier: Calculate and hold the dominance frontier for a
13 //     function.
14 //
15 //  These data structures are listed in increasing order of complexity.  It
16 //  takes longer to calculate the dominator frontier, for example, than the
17 //  DominatorTree mapping.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_ANALYSIS_DOMINATORS_H
22 #define LLVM_ANALYSIS_DOMINATORS_H
23
24 #include "llvm/Pass.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/Support/Compiler.h"
32 #include <algorithm>
33 #include <set>
34
35 namespace llvm {
36
37 template <typename GraphType> struct GraphTraits;
38
39 //===----------------------------------------------------------------------===//
40 /// DominatorBase - Base class that other, more interesting dominator analyses
41 /// inherit from.
42 ///
43 template <class NodeT>
44 class DominatorBase : public FunctionPass {
45 protected:
46   std::vector<NodeT*> Roots;
47   const bool IsPostDominators;
48   inline DominatorBase(intptr_t ID, bool isPostDom) : 
49     FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
50 public:
51
52   /// getRoots -  Return the root blocks of the current CFG.  This may include
53   /// multiple blocks if we are computing post dominators.  For forward
54   /// dominators, this will always be a single block (the entry node).
55   ///
56   inline const std::vector<NodeT*> &getRoots() const { return Roots; }
57
58   /// isPostDominator - Returns true if analysis based of postdoms
59   ///
60   bool isPostDominator() const { return IsPostDominators; }
61 };
62
63
64 //===----------------------------------------------------------------------===//
65 // DomTreeNode - Dominator Tree Node
66 template<class NodeT> class DominatorTreeBase;
67 class PostDominatorTree;
68 class MachineBasicBlock;
69
70 template <class NodeT>
71 class DomTreeNodeBase {
72   NodeT *TheBB;
73   DomTreeNodeBase<NodeT> *IDom;
74   std::vector<DomTreeNodeBase<NodeT> *> Children;
75   int DFSNumIn, DFSNumOut;
76
77   template<class N> friend class DominatorTreeBase;
78   friend class PostDominatorTree;
79 public:
80   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
81   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
82                    const_iterator;
83   
84   iterator begin()             { return Children.begin(); }
85   iterator end()               { return Children.end(); }
86   const_iterator begin() const { return Children.begin(); }
87   const_iterator end()   const { return Children.end(); }
88   
89   NodeT *getBlock() const { return TheBB; }
90   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
91   const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
92     return Children;
93   }
94   
95   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
96     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
97   
98   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
99     Children.push_back(C);
100     return C;
101   }
102   
103   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
104     assert(IDom && "No immediate dominator?");
105     if (IDom != NewIDom) {
106       std::vector<DomTreeNodeBase<BasicBlock>*>::iterator I =
107                   std::find(IDom->Children.begin(), IDom->Children.end(), this);
108       assert(I != IDom->Children.end() &&
109              "Not in immediate dominator children set!");
110       // I am no longer your child...
111       IDom->Children.erase(I);
112
113       // Switch to new dominator
114       IDom = NewIDom;
115       IDom->Children.push_back(this);
116     }
117   }
118   
119   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
120   /// not call them.
121   unsigned getDFSNumIn() const { return DFSNumIn; }
122   unsigned getDFSNumOut() const { return DFSNumOut; }
123 private:
124   // Return true if this node is dominated by other. Use this only if DFS info
125   // is valid.
126   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
127     return this->DFSNumIn >= other->DFSNumIn &&
128       this->DFSNumOut <= other->DFSNumOut;
129   }
130 };
131
132 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
133
134 template<class NodeT>
135 static std::ostream &operator<<(std::ostream &o,
136                                 const DomTreeNodeBase<NodeT> *Node) {
137   if (Node->getBlock())
138     WriteAsOperand(o, Node->getBlock(), false);
139   else
140     o << " <<exit node>>";
141   
142   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
143   
144   return o << "\n";
145 }
146
147 template<class NodeT>
148 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, std::ostream &o,
149                          unsigned Lev) {
150   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
151   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
152        E = N->end(); I != E; ++I)
153     PrintDomTree<NodeT>(*I, o, Lev+1);
154 }
155
156 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
157 typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
158
159 //===----------------------------------------------------------------------===//
160 /// DominatorTree - Calculate the immediate dominator tree for a function.
161 ///
162
163 template<class NodeT>
164 class DominatorTreeBase : public DominatorBase<NodeT> {
165 protected:
166   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
167   DomTreeNodeMapType DomTreeNodes;
168   DomTreeNodeBase<NodeT> *RootNode;
169
170   bool DFSInfoValid;
171   unsigned int SlowQueries;
172   // Information record used during immediate dominators computation.
173   struct InfoRec {
174     unsigned Semi;
175     unsigned Size;
176     NodeT *Label, *Parent, *Child, *Ancestor;
177
178     std::vector<NodeT*> Bucket;
179
180     InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0) {}
181   };
182
183   DenseMap<NodeT*, NodeT*> IDoms;
184
185   // Vertex - Map the DFS number to the BasicBlock*
186   std::vector<NodeT*> Vertex;
187
188   // Info - Collection of information used during the computation of idoms.
189   DenseMap<NodeT*, InfoRec> Info;
190
191   void reset() {
192     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(), 
193            E = DomTreeNodes.end(); I != E; ++I)
194       delete I->second;
195     DomTreeNodes.clear();
196     IDoms.clear();
197     this->Roots.clear();
198     Vertex.clear();
199     RootNode = 0;
200   }
201
202 public:
203   DominatorTreeBase(intptr_t ID, bool isPostDom) 
204     : DominatorBase<NodeT>(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
205   ~DominatorTreeBase() { reset(); }
206
207   virtual void releaseMemory() { reset(); }
208
209   /// getNode - return the (Post)DominatorTree node for the specified basic
210   /// block.  This is the same as using operator[] on this class.
211   ///
212   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
213     typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
214     return I != DomTreeNodes.end() ? I->second : 0;
215   }
216
217   inline DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const {
218     return getNode(BB);
219   }
220
221   /// getRootNode - This returns the entry node for the CFG of the function.  If
222   /// this tree represents the post-dominance relations for a function, however,
223   /// this root may be a node with the block == NULL.  This is the case when
224   /// there are multiple exit nodes from a particular function.  Consumers of
225   /// post-dominance information must be capable of dealing with this
226   /// possibility.
227   ///
228   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
229   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
230
231   /// properlyDominates - Returns true iff this dominates N and this != N.
232   /// Note that this is not a constant time operation!
233   ///
234   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
235                          DomTreeNodeBase<NodeT> *B) const {
236     if (A == 0 || B == 0) return false;
237     return dominatedBySlowTreeWalk(A, B);
238   }
239
240   inline bool properlyDominates(NodeT *A, NodeT *B) {
241     return properlyDominates(getNode(A), getNode(B));
242   }
243
244   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, 
245                                const DomTreeNodeBase<NodeT> *B) const {
246     const DomTreeNodeBase<NodeT> *IDom;
247     if (A == 0 || B == 0) return false;
248     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
249       B = IDom;   // Walk up the tree
250     return IDom != 0;
251   }
252
253
254   /// isReachableFromEntry - Return true if A is dominated by the entry
255   /// block of the function containing it.
256   const bool isReachableFromEntry(NodeT* A) {
257     assert (!this->isPostDominator() 
258             && "This is not implemented for post dominators");
259     return dominates(&A->getParent()->getEntryBlock(), A);
260   }
261   
262   /// dominates - Returns true iff A dominates B.  Note that this is not a
263   /// constant time operation!
264   ///
265   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
266                         DomTreeNodeBase<NodeT> *B) {
267     if (B == A) 
268       return true;  // A node trivially dominates itself.
269
270     if (A == 0 || B == 0)
271       return false;
272
273     if (DFSInfoValid)
274       return B->DominatedBy(A);
275
276     // If we end up with too many slow queries, just update the
277     // DFS numbers on the theory that we are going to keep querying.
278     SlowQueries++;
279     if (SlowQueries > 32) {
280       updateDFSNumbers();
281       return B->DominatedBy(A);
282     }
283
284     return dominatedBySlowTreeWalk(A, B);
285   }
286
287   inline bool dominates(NodeT *A, NodeT *B) {
288     if (A == B) 
289       return true;
290     
291     return dominates(getNode(A), getNode(B));
292   }
293
294   /// findNearestCommonDominator - Find nearest common dominator basic block
295   /// for basic block A and B. If there is no such block then return NULL.
296   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
297
298     assert (!this->isPostDominator() 
299             && "This is not implemented for post dominators");
300     assert (A->getParent() == B->getParent() 
301             && "Two blocks are not in same function");
302
303     // If either A or B is a entry block then it is nearest common dominator.
304     NodeT &Entry  = A->getParent()->getEntryBlock();
305     if (A == &Entry || B == &Entry)
306       return &Entry;
307
308     // If B dominates A then B is nearest common dominator.
309     if (dominates(B, A))
310       return B;
311
312     // If A dominates B then A is nearest common dominator.
313     if (dominates(A, B))
314       return A;
315
316     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
317     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
318
319     // Collect NodeA dominators set.
320     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
321     NodeADoms.insert(NodeA);
322     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
323     while (IDomA) {
324       NodeADoms.insert(IDomA);
325       IDomA = IDomA->getIDom();
326     }
327
328     // Walk NodeB immediate dominators chain and find common dominator node.
329     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
330     while(IDomB) {
331       if (NodeADoms.count(IDomB) != 0)
332         return IDomB->getBlock();
333
334       IDomB = IDomB->getIDom();
335     }
336
337     return NULL;
338   }
339
340   // dominates - Return true if A dominates B. This performs the
341   // special checks necessary if A and B are in the same basic block.
342   bool dominates(Instruction *A, Instruction *B) {
343     NodeT *BBA = A->getParent(), *BBB = B->getParent();
344     if (BBA != BBB) return this->dominates(BBA, BBB);
345
346     // It is not possible to determine dominance between two PHI nodes 
347     // based on their ordering.
348     if (isa<PHINode>(A) && isa<PHINode>(B)) 
349       return false;
350
351     // Loop through the basic block until we find A or B.
352     typename NodeT::iterator I = BBA->begin();
353     for (; &*I != A && &*I != B; ++I) /*empty*/;
354
355     if(!this->IsPostDominators) {
356       // A dominates B if it is found first in the basic block.
357       return &*I == A;
358     } else {
359       // A post-dominates B if B is found first in the basic block.
360       return &*I == B;
361     }
362   }
363
364   //===--------------------------------------------------------------------===//
365   // API to update (Post)DominatorTree information based on modifications to
366   // the CFG...
367
368   /// addNewBlock - Add a new node to the dominator tree information.  This
369   /// creates a new node as a child of DomBB dominator node,linking it into 
370   /// the children list of the immediate dominator.
371   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
372     assert(getNode(BB) == 0 && "Block already in dominator tree!");
373     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
374     assert(IDomNode && "Not immediate dominator specified for block!");
375     DFSInfoValid = false;
376     return DomTreeNodes[BB] = 
377       IDomNode->addChild(new DomTreeNode(BB, IDomNode));
378   }
379
380   /// changeImmediateDominator - This method is used to update the dominator
381   /// tree information when a node's immediate dominator changes.
382   ///
383   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
384                                 DomTreeNodeBase<NodeT> *NewIDom) {
385     assert(N && NewIDom && "Cannot change null node pointers!");
386     DFSInfoValid = false;
387     N->setIDom(NewIDom);
388   }
389
390   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
391     changeImmediateDominator(getNode(BB), getNode(NewBB));
392   }
393
394   /// eraseNode - Removes a node from  the dominator tree. Block must not
395   /// domiante any other blocks. Removes node from its immediate dominator's
396   /// children list. Deletes dominator node associated with basic block BB.
397   void eraseNode(NodeT *BB) {
398     DomTreeNodeBase<NodeT> *Node = getNode(BB);
399     assert (Node && "Removing node that isn't in dominator tree.");
400     assert (Node->getChildren().empty() && "Node is not a leaf node.");
401
402       // Remove node from immediate dominator's children list.
403     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
404     if (IDom) {
405       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
406         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
407       assert(I != IDom->Children.end() &&
408              "Not in immediate dominator children set!");
409       // I am no longer your child...
410       IDom->Children.erase(I);
411     }
412
413     DomTreeNodes.erase(BB);
414     delete Node;
415   }
416
417   /// removeNode - Removes a node from the dominator tree.  Block must not
418   /// dominate any other blocks.  Invalidates any node pointing to removed
419   /// block.
420   void removeNode(NodeT *BB) {
421     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
422     DomTreeNodes.erase(BB);
423   }
424
425   /// print - Convert to human readable form
426   ///
427   virtual void print(std::ostream &o, const Module* ) const {
428     o << "=============================--------------------------------\n";
429     o << "Inorder Dominator Tree: ";
430     if (this->DFSInfoValid)
431       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
432     o << "\n";
433
434     PrintDomTree<NodeT>(getRootNode(), o, 1);
435   }
436   
437   void print(std::ostream *OS, const Module* M = 0) const {
438     if (OS) print(*OS, M);
439   }
440   
441   virtual void dump() {
442     print(llvm::cerr);
443   }
444   
445 protected:
446   template<class GraphT>
447   friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
448                        typename GraphT::NodeType* VIn);
449
450   template<class GraphT>
451   friend typename GraphT::NodeType* Eval(
452                                DominatorTreeBase<typename GraphT::NodeType>& DT,
453                                          typename GraphT::NodeType* V);
454
455   template<class GraphT>
456   friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
457                    typename GraphT::NodeType* V,
458                    typename GraphT::NodeType* W,
459          typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
460   
461   template<class GraphT>
462   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
463                           typename GraphT::NodeType* V,
464                           unsigned N);
465   
466   template<class N, class GraphT>
467   friend void Calculate(DominatorTreeBase<typename GraphT::NodeType>& DT,
468                         Function& F);
469   
470   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
471   /// dominator tree in dfs order.
472   void updateDFSNumbers() {
473     unsigned DFSNum = 0;
474
475     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
476                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
477
478     for (unsigned i = 0, e = this->Roots.size(); i != e; ++i) {
479       DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
480       WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
481       ThisRoot->DFSNumIn = DFSNum++;
482
483       while (!WorkStack.empty()) {
484         DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
485         typename DomTreeNodeBase<NodeT>::iterator ChildIt =
486                                                         WorkStack.back().second;
487
488         // If we visited all of the children of this node, "recurse" back up the
489         // stack setting the DFOutNum.
490         if (ChildIt == Node->end()) {
491           Node->DFSNumOut = DFSNum++;
492           WorkStack.pop_back();
493         } else {
494           // Otherwise, recursively visit this child.
495           DomTreeNodeBase<NodeT> *Child = *ChildIt;
496           ++WorkStack.back().second;
497           
498           WorkStack.push_back(std::make_pair(Child, Child->begin()));
499           Child->DFSNumIn = DFSNum++;
500         }
501       }
502     }
503     
504     SlowQueries = 0;
505     DFSInfoValid = true;
506   }
507   
508   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
509     if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
510       return BBNode;
511
512     // Haven't calculated this node yet?  Get or calculate the node for the
513     // immediate dominator.
514     NodeT *IDom = getIDom(BB);
515     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
516
517     // Add a new tree node for this BasicBlock, and link it as a child of
518     // IDomNode
519     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
520     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
521   }
522   
523   inline NodeT *getIDom(NodeT *BB) const {
524     typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
525     return I != IDoms.end() ? I->second : 0;
526   }
527 };
528
529 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
530
531 //===-------------------------------------
532 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
533 /// compute a normal dominator tree.
534 ///
535 class DominatorTree : public DominatorTreeBase<BasicBlock> {
536 public:
537   static char ID; // Pass ID, replacement for typeid
538   DominatorTree() : DominatorTreeBase<BasicBlock>(intptr_t(&ID), false) {}
539   
540   BasicBlock *getRoot() const {
541     assert(Roots.size() == 1 && "Should always have entry node!");
542     return Roots[0];
543   }
544   
545   virtual bool runOnFunction(Function &F);
546   
547   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
548     AU.setPreservesAll();
549   }
550
551   /// splitBlock
552   /// BB is split and now it has one successor. Update dominator tree to
553   /// reflect this change.
554   void splitBlock(BasicBlock *BB);
555 };
556
557 //===-------------------------------------
558 /// DominatorTree GraphTraits specialization so the DominatorTree can be
559 /// iterable by generic graph iterators.
560 ///
561 template <> struct GraphTraits<DomTreeNode *> {
562   typedef DomTreeNode NodeType;
563   typedef NodeType::iterator  ChildIteratorType;
564   
565   static NodeType *getEntryNode(NodeType *N) {
566     return N;
567   }
568   static inline ChildIteratorType child_begin(NodeType* N) {
569     return N->begin();
570   }
571   static inline ChildIteratorType child_end(NodeType* N) {
572     return N->end();
573   }
574 };
575
576 template <> struct GraphTraits<DominatorTree*>
577   : public GraphTraits<DomTreeNode *> {
578   static NodeType *getEntryNode(DominatorTree *DT) {
579     return DT->getRootNode();
580   }
581 };
582
583
584 //===----------------------------------------------------------------------===//
585 /// DominanceFrontierBase - Common base class for computing forward and inverse
586 /// dominance frontiers for a function.
587 ///
588 class DominanceFrontierBase : public DominatorBase<BasicBlock> {
589 public:
590   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
591   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
592 protected:
593   DomSetMapType Frontiers;
594 public:
595   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
596     : DominatorBase<BasicBlock>(ID, isPostDom) {}
597
598   virtual void releaseMemory() { Frontiers.clear(); }
599
600   // Accessor interface:
601   typedef DomSetMapType::iterator iterator;
602   typedef DomSetMapType::const_iterator const_iterator;
603   iterator       begin()       { return Frontiers.begin(); }
604   const_iterator begin() const { return Frontiers.begin(); }
605   iterator       end()         { return Frontiers.end(); }
606   const_iterator end()   const { return Frontiers.end(); }
607   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
608   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
609
610   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
611     assert(find(BB) == end() && "Block already in DominanceFrontier!");
612     Frontiers.insert(std::make_pair(BB, frontier));
613   }
614
615   /// removeBlock - Remove basic block BB's frontier.
616   void removeBlock(BasicBlock *BB) {
617     assert(find(BB) != end() && "Block is not in DominanceFrontier!");
618     for (iterator I = begin(), E = end(); I != E; ++I)
619       I->second.erase(BB);
620     Frontiers.erase(BB);
621   }
622
623   void addToFrontier(iterator I, BasicBlock *Node) {
624     assert(I != end() && "BB is not in DominanceFrontier!");
625     I->second.insert(Node);
626   }
627
628   void removeFromFrontier(iterator I, BasicBlock *Node) {
629     assert(I != end() && "BB is not in DominanceFrontier!");
630     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
631     I->second.erase(Node);
632   }
633
634   /// print - Convert to human readable form
635   ///
636   virtual void print(std::ostream &OS, const Module* = 0) const;
637   void print(std::ostream *OS, const Module* M = 0) const {
638     if (OS) print(*OS, M);
639   }
640   virtual void dump();
641 };
642
643
644 //===-------------------------------------
645 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
646 /// used to compute a forward dominator frontiers.
647 ///
648 class DominanceFrontier : public DominanceFrontierBase {
649 public:
650   static char ID; // Pass ID, replacement for typeid
651   DominanceFrontier() : 
652     DominanceFrontierBase(intptr_t(&ID), false) {}
653
654   BasicBlock *getRoot() const {
655     assert(Roots.size() == 1 && "Should always have entry node!");
656     return Roots[0];
657   }
658
659   virtual bool runOnFunction(Function &) {
660     Frontiers.clear();
661     DominatorTree &DT = getAnalysis<DominatorTree>();
662     Roots = DT.getRoots();
663     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
664     calculate(DT, DT[Roots[0]]);
665     return false;
666   }
667
668   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
669     AU.setPreservesAll();
670     AU.addRequired<DominatorTree>();
671   }
672
673   /// splitBlock - BB is split and now it has one successor. Update dominance
674   /// frontier to reflect this change.
675   void splitBlock(BasicBlock *BB);
676
677   /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
678   /// to reflect this change.
679   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
680                                 DominatorTree *DT) {
681     // NewBB is now  dominating BB. Which means BB's dominance
682     // frontier is now part of NewBB's dominance frontier. However, BB
683     // itself is not member of NewBB's dominance frontier.
684     DominanceFrontier::iterator NewDFI = find(NewBB);
685     DominanceFrontier::iterator DFI = find(BB);
686     DominanceFrontier::DomSetType BBSet = DFI->second;
687     for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
688            BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
689       BasicBlock *DFMember = *BBSetI;
690       // Insert only if NewBB dominates DFMember.
691       if (!DT->dominates(NewBB, DFMember))
692         NewDFI->second.insert(DFMember);
693     }
694     NewDFI->second.erase(BB);
695   }
696
697 private:
698   const DomSetType &calculate(const DominatorTree &DT,
699                               const DomTreeNode *Node);
700 };
701
702
703 } // End llvm namespace
704
705 #endif