eliminate the std::ostream form of WriteAsOperand and update clients.
[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 is distributed under the University of Illinois Open Source
6 // 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/BasicBlock.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/GraphTraits.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <map>
38 #include <set>
39
40 namespace llvm {
41
42 //===----------------------------------------------------------------------===//
43 /// DominatorBase - Base class that other, more interesting dominator analyses
44 /// inherit from.
45 ///
46 template <class NodeT>
47 class DominatorBase {
48 protected:
49   std::vector<NodeT*> Roots;
50   const bool IsPostDominators;
51   inline explicit DominatorBase(bool isPostDom) :
52     Roots(), IsPostDominators(isPostDom) {}
53 public:
54
55   /// getRoots -  Return the root blocks of the current CFG.  This may include
56   /// multiple blocks if we are computing post dominators.  For forward
57   /// dominators, this will always be a single block (the entry node).
58   ///
59   inline const std::vector<NodeT*> &getRoots() const { return Roots; }
60
61   /// isPostDominator - Returns true if analysis based of postdoms
62   ///
63   bool isPostDominator() const { return IsPostDominators; }
64 };
65
66
67 //===----------------------------------------------------------------------===//
68 // DomTreeNode - Dominator Tree Node
69 template<class NodeT> class DominatorTreeBase;
70 struct PostDominatorTree;
71 class MachineBasicBlock;
72
73 template <class NodeT>
74 class DomTreeNodeBase {
75   NodeT *TheBB;
76   DomTreeNodeBase<NodeT> *IDom;
77   std::vector<DomTreeNodeBase<NodeT> *> Children;
78   int DFSNumIn, DFSNumOut;
79
80   template<class N> friend class DominatorTreeBase;
81   friend struct PostDominatorTree;
82 public:
83   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
84   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
85                    const_iterator;
86   
87   iterator begin()             { return Children.begin(); }
88   iterator end()               { return Children.end(); }
89   const_iterator begin() const { return Children.begin(); }
90   const_iterator end()   const { return Children.end(); }
91   
92   NodeT *getBlock() const { return TheBB; }
93   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
94   const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
95     return Children;
96   }
97
98   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
99     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
100   
101   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
102     Children.push_back(C);
103     return C;
104   }
105
106   size_t getNumChildren() const {
107     return Children.size();
108   }
109
110   void clearAllChildren() {
111     Children.clear();
112   }
113   
114   bool compare(DomTreeNodeBase<NodeT> *Other) {
115     if (getNumChildren() != Other->getNumChildren())
116       return true;
117
118     SmallPtrSet<NodeT *, 4> OtherChildren;
119     for(iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
120       NodeT *Nd = (*I)->getBlock();
121       OtherChildren.insert(Nd);
122     }
123
124     for(iterator I = begin(), E = end(); I != E; ++I) {
125       NodeT *N = (*I)->getBlock();
126       if (OtherChildren.count(N) == 0)
127         return true;
128     }
129     return false;
130   }
131
132   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
133     assert(IDom && "No immediate dominator?");
134     if (IDom != NewIDom) {
135       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
136                   std::find(IDom->Children.begin(), IDom->Children.end(), this);
137       assert(I != IDom->Children.end() &&
138              "Not in immediate dominator children set!");
139       // I am no longer your child...
140       IDom->Children.erase(I);
141
142       // Switch to new dominator
143       IDom = NewIDom;
144       IDom->Children.push_back(this);
145     }
146   }
147   
148   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
149   /// not call them.
150   unsigned getDFSNumIn() const { return DFSNumIn; }
151   unsigned getDFSNumOut() const { return DFSNumOut; }
152 private:
153   // Return true if this node is dominated by other. Use this only if DFS info
154   // is valid.
155   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
156     return this->DFSNumIn >= other->DFSNumIn &&
157       this->DFSNumOut <= other->DFSNumOut;
158   }
159 };
160
161 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
162 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
163
164 template<class NodeT>
165 static raw_ostream &operator<<(raw_ostream &o,
166                                const DomTreeNodeBase<NodeT> *Node) {
167   if (Node->getBlock())
168     WriteAsOperand(o, Node->getBlock(), false);
169   else
170     o << " <<exit node>>";
171   
172   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
173   
174   return o << "\n";
175 }
176
177 template<class NodeT>
178 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
179                          unsigned Lev) {
180   o.indent(2*Lev) << "[" << Lev << "] " << N;
181   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
182        E = N->end(); I != E; ++I)
183     PrintDomTree<NodeT>(*I, o, Lev+1);
184 }
185
186 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
187
188 //===----------------------------------------------------------------------===//
189 /// DominatorTree - Calculate the immediate dominator tree for a function.
190 ///
191
192 template<class FuncT, class N>
193 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
194                FuncT& F);
195
196 template<class NodeT>
197 class DominatorTreeBase : public DominatorBase<NodeT> {
198 protected:
199   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
200   DomTreeNodeMapType DomTreeNodes;
201   DomTreeNodeBase<NodeT> *RootNode;
202
203   bool DFSInfoValid;
204   unsigned int SlowQueries;
205   // Information record used during immediate dominators computation.
206   struct InfoRec {
207     unsigned DFSNum;
208     unsigned Semi;
209     unsigned Size;
210     NodeT *Label, *Child;
211     unsigned Parent, Ancestor;
212
213     std::vector<NodeT*> Bucket;
214
215     InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
216                 Ancestor(0) {}
217   };
218
219   DenseMap<NodeT*, NodeT*> IDoms;
220
221   // Vertex - Map the DFS number to the BasicBlock*
222   std::vector<NodeT*> Vertex;
223
224   // Info - Collection of information used during the computation of idoms.
225   DenseMap<NodeT*, InfoRec> Info;
226
227   void reset() {
228     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(), 
229            E = DomTreeNodes.end(); I != E; ++I)
230       delete I->second;
231     DomTreeNodes.clear();
232     IDoms.clear();
233     this->Roots.clear();
234     Vertex.clear();
235     RootNode = 0;
236   }
237   
238   // NewBB is split and now it has one successor. Update dominator tree to
239   // reflect this change.
240   template<class N, class GraphT>
241   void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
242              typename GraphT::NodeType* NewBB) {
243     assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
244            && "NewBB should have a single successor!");
245     typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
246
247     std::vector<typename GraphT::NodeType*> PredBlocks;
248     for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
249          GraphTraits<Inverse<N> >::child_begin(NewBB),
250          PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
251       PredBlocks.push_back(*PI);  
252
253     assert(!PredBlocks.empty() && "No predblocks??");
254
255     bool NewBBDominatesNewBBSucc = true;
256     for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
257          GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
258          E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
259       if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI) &&
260           DT.isReachableFromEntry(*PI)) {
261         NewBBDominatesNewBBSucc = false;
262         break;
263       }
264
265     // Find NewBB's immediate dominator and create new dominator tree node for
266     // NewBB.
267     NodeT *NewBBIDom = 0;
268     unsigned i = 0;
269     for (i = 0; i < PredBlocks.size(); ++i)
270       if (DT.isReachableFromEntry(PredBlocks[i])) {
271         NewBBIDom = PredBlocks[i];
272         break;
273       }
274
275     // It's possible that none of the predecessors of NewBB are reachable;
276     // in that case, NewBB itself is unreachable, so nothing needs to be
277     // changed.
278     if (!NewBBIDom)
279       return;
280
281     for (i = i + 1; i < PredBlocks.size(); ++i) {
282       if (DT.isReachableFromEntry(PredBlocks[i]))
283         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
284     }
285
286     // Create the new dominator tree node... and set the idom of NewBB.
287     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
288
289     // If NewBB strictly dominates other blocks, then it is now the immediate
290     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
291     if (NewBBDominatesNewBBSucc) {
292       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
293       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
294     }
295   }
296
297 public:
298   explicit DominatorTreeBase(bool isPostDom)
299     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
300   virtual ~DominatorTreeBase() { reset(); }
301
302   // FIXME: Should remove this
303   virtual bool runOnFunction(Function &F) { return false; }
304
305   /// compare - Return false if the other dominator tree base matches this
306   /// dominator tree base. Otherwise return true.
307   bool compare(DominatorTreeBase &Other) const {
308
309     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
310     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
311       return true;
312
313     SmallPtrSet<const NodeT *,4> MyBBs;
314     for (typename DomTreeNodeMapType::const_iterator 
315            I = this->DomTreeNodes.begin(),
316            E = this->DomTreeNodes.end(); I != E; ++I) {
317       NodeT *BB = I->first;
318       typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
319       if (OI == OtherDomTreeNodes.end())
320         return true;
321
322       DomTreeNodeBase<NodeT>* MyNd = I->second;
323       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
324       
325       if (MyNd->compare(OtherNd))
326         return true;
327     }
328
329     return false;
330   }
331
332   virtual void releaseMemory() { reset(); }
333
334   /// getNode - return the (Post)DominatorTree node for the specified basic
335   /// block.  This is the same as using operator[] on this class.
336   ///
337   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
338     typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
339     return I != DomTreeNodes.end() ? I->second : 0;
340   }
341
342   /// getRootNode - This returns the entry node for the CFG of the function.  If
343   /// this tree represents the post-dominance relations for a function, however,
344   /// this root may be a node with the block == NULL.  This is the case when
345   /// there are multiple exit nodes from a particular function.  Consumers of
346   /// post-dominance information must be capable of dealing with this
347   /// possibility.
348   ///
349   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
350   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
351
352   /// properlyDominates - Returns true iff this dominates N and this != N.
353   /// Note that this is not a constant time operation!
354   ///
355   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
356                          DomTreeNodeBase<NodeT> *B) const {
357     if (A == 0 || B == 0) return false;
358     return dominatedBySlowTreeWalk(A, B);
359   }
360
361   inline bool properlyDominates(NodeT *A, NodeT *B) {
362     return properlyDominates(getNode(A), getNode(B));
363   }
364
365   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, 
366                                const DomTreeNodeBase<NodeT> *B) const {
367     const DomTreeNodeBase<NodeT> *IDom;
368     if (A == 0 || B == 0) return false;
369     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
370       B = IDom;   // Walk up the tree
371     return IDom != 0;
372   }
373
374
375   /// isReachableFromEntry - Return true if A is dominated by the entry
376   /// block of the function containing it.
377   bool isReachableFromEntry(NodeT* A) {
378     assert (!this->isPostDominator() 
379             && "This is not implemented for post dominators");
380     return dominates(&A->getParent()->front(), A);
381   }
382   
383   /// dominates - Returns true iff A dominates B.  Note that this is not a
384   /// constant time operation!
385   ///
386   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
387                         DomTreeNodeBase<NodeT> *B) {
388     if (B == A) 
389       return true;  // A node trivially dominates itself.
390
391     if (A == 0 || B == 0)
392       return false;
393
394     if (DFSInfoValid)
395       return B->DominatedBy(A);
396
397     // If we end up with too many slow queries, just update the
398     // DFS numbers on the theory that we are going to keep querying.
399     SlowQueries++;
400     if (SlowQueries > 32) {
401       updateDFSNumbers();
402       return B->DominatedBy(A);
403     }
404
405     return dominatedBySlowTreeWalk(A, B);
406   }
407
408   inline bool dominates(NodeT *A, NodeT *B) {
409     if (A == B) 
410       return true;
411     
412     return dominates(getNode(A), getNode(B));
413   }
414   
415   NodeT *getRoot() const {
416     assert(this->Roots.size() == 1 && "Should always have entry node!");
417     return this->Roots[0];
418   }
419
420   /// findNearestCommonDominator - Find nearest common dominator basic block
421   /// for basic block A and B. If there is no such block then return NULL.
422   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
423
424     assert (!this->isPostDominator() 
425             && "This is not implemented for post dominators");
426     assert (A->getParent() == B->getParent() 
427             && "Two blocks are not in same function");
428
429     // If either A or B is a entry block then it is nearest common dominator.
430     NodeT &Entry  = A->getParent()->front();
431     if (A == &Entry || B == &Entry)
432       return &Entry;
433
434     // If B dominates A then B is nearest common dominator.
435     if (dominates(B, A))
436       return B;
437
438     // If A dominates B then A is nearest common dominator.
439     if (dominates(A, B))
440       return A;
441
442     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
443     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
444
445     // Collect NodeA dominators set.
446     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
447     NodeADoms.insert(NodeA);
448     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
449     while (IDomA) {
450       NodeADoms.insert(IDomA);
451       IDomA = IDomA->getIDom();
452     }
453
454     // Walk NodeB immediate dominators chain and find common dominator node.
455     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
456     while(IDomB) {
457       if (NodeADoms.count(IDomB) != 0)
458         return IDomB->getBlock();
459
460       IDomB = IDomB->getIDom();
461     }
462
463     return NULL;
464   }
465
466   //===--------------------------------------------------------------------===//
467   // API to update (Post)DominatorTree information based on modifications to
468   // the CFG...
469
470   /// addNewBlock - Add a new node to the dominator tree information.  This
471   /// creates a new node as a child of DomBB dominator node,linking it into 
472   /// the children list of the immediate dominator.
473   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
474     assert(getNode(BB) == 0 && "Block already in dominator tree!");
475     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
476     assert(IDomNode && "Not immediate dominator specified for block!");
477     DFSInfoValid = false;
478     return DomTreeNodes[BB] = 
479       IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
480   }
481
482   /// changeImmediateDominator - This method is used to update the dominator
483   /// tree information when a node's immediate dominator changes.
484   ///
485   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
486                                 DomTreeNodeBase<NodeT> *NewIDom) {
487     assert(N && NewIDom && "Cannot change null node pointers!");
488     DFSInfoValid = false;
489     N->setIDom(NewIDom);
490   }
491
492   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
493     changeImmediateDominator(getNode(BB), getNode(NewBB));
494   }
495
496   /// eraseNode - Removes a node from  the dominator tree. Block must not
497   /// domiante any other blocks. Removes node from its immediate dominator's
498   /// children list. Deletes dominator node associated with basic block BB.
499   void eraseNode(NodeT *BB) {
500     DomTreeNodeBase<NodeT> *Node = getNode(BB);
501     assert (Node && "Removing node that isn't in dominator tree.");
502     assert (Node->getChildren().empty() && "Node is not a leaf node.");
503
504       // Remove node from immediate dominator's children list.
505     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
506     if (IDom) {
507       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
508         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
509       assert(I != IDom->Children.end() &&
510              "Not in immediate dominator children set!");
511       // I am no longer your child...
512       IDom->Children.erase(I);
513     }
514
515     DomTreeNodes.erase(BB);
516     delete Node;
517   }
518
519   /// removeNode - Removes a node from the dominator tree.  Block must not
520   /// dominate any other blocks.  Invalidates any node pointing to removed
521   /// block.
522   void removeNode(NodeT *BB) {
523     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
524     DomTreeNodes.erase(BB);
525   }
526   
527   /// splitBlock - BB is split and now it has one successor. Update dominator
528   /// tree to reflect this change.
529   void splitBlock(NodeT* NewBB) {
530     if (this->IsPostDominators)
531       this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
532     else
533       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
534   }
535
536   /// print - Convert to human readable form
537   ///
538   void print(raw_ostream &o) const {
539     o << "=============================--------------------------------\n";
540     if (this->isPostDominator())
541       o << "Inorder PostDominator Tree: ";
542     else
543       o << "Inorder Dominator Tree: ";
544     if (this->DFSInfoValid)
545       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
546     o << "\n";
547
548     PrintDomTree<NodeT>(getRootNode(), o, 1);
549   }
550   
551 protected:
552   template<class GraphT>
553   friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
554                        typename GraphT::NodeType* VIn);
555
556   template<class GraphT>
557   friend typename GraphT::NodeType* Eval(
558                                DominatorTreeBase<typename GraphT::NodeType>& DT,
559                                          typename GraphT::NodeType* V);
560
561   template<class GraphT>
562   friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
563                    unsigned DFSNumV, typename GraphT::NodeType* W,
564          typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
565   
566   template<class GraphT>
567   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
568                           typename GraphT::NodeType* V,
569                           unsigned N);
570   
571   template<class FuncT, class N>
572   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
573                         FuncT& F);
574   
575   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
576   /// dominator tree in dfs order.
577   void updateDFSNumbers() {
578     unsigned DFSNum = 0;
579
580     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
581                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
582
583     for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
584       DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
585       WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
586       ThisRoot->DFSNumIn = DFSNum++;
587
588       while (!WorkStack.empty()) {
589         DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
590         typename DomTreeNodeBase<NodeT>::iterator ChildIt =
591                                                         WorkStack.back().second;
592
593         // If we visited all of the children of this node, "recurse" back up the
594         // stack setting the DFOutNum.
595         if (ChildIt == Node->end()) {
596           Node->DFSNumOut = DFSNum++;
597           WorkStack.pop_back();
598         } else {
599           // Otherwise, recursively visit this child.
600           DomTreeNodeBase<NodeT> *Child = *ChildIt;
601           ++WorkStack.back().second;
602           
603           WorkStack.push_back(std::make_pair(Child, Child->begin()));
604           Child->DFSNumIn = DFSNum++;
605         }
606       }
607     }
608     
609     SlowQueries = 0;
610     DFSInfoValid = true;
611   }
612   
613   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
614     typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
615     if (I != this->DomTreeNodes.end() && I->second)
616       return I->second;
617
618     // Haven't calculated this node yet?  Get or calculate the node for the
619     // immediate dominator.
620     NodeT *IDom = getIDom(BB);
621
622     assert(IDom || this->DomTreeNodes[NULL]);
623     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
624
625     // Add a new tree node for this BasicBlock, and link it as a child of
626     // IDomNode
627     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
628     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
629   }
630   
631   inline NodeT *getIDom(NodeT *BB) const {
632     typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
633     return I != IDoms.end() ? I->second : 0;
634   }
635   
636   inline void addRoot(NodeT* BB) {
637     this->Roots.push_back(BB);
638   }
639   
640 public:
641   /// recalculate - compute a dominator tree for the given function
642   template<class FT>
643   void recalculate(FT& F) {
644     if (!this->IsPostDominators) {
645       reset();
646       
647       // Initialize roots
648       this->Roots.push_back(&F.front());
649       this->IDoms[&F.front()] = 0;
650       this->DomTreeNodes[&F.front()] = 0;
651       this->Vertex.push_back(0);
652       
653       Calculate<FT, NodeT*>(*this, F);
654       
655       updateDFSNumbers();
656     } else {
657       reset();     // Reset from the last time we were run...
658
659       // Initialize the roots list
660       for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
661         if (std::distance(GraphTraits<FT*>::child_begin(I),
662                           GraphTraits<FT*>::child_end(I)) == 0)
663           addRoot(I);
664
665         // Prepopulate maps so that we don't get iterator invalidation issues later.
666         this->IDoms[I] = 0;
667         this->DomTreeNodes[I] = 0;
668       }
669
670       this->Vertex.push_back(0);
671       
672       Calculate<FT, Inverse<NodeT*> >(*this, F);
673     }
674   }
675 };
676
677 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
678
679 //===-------------------------------------
680 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
681 /// compute a normal dominator tree.
682 ///
683 class DominatorTree : public FunctionPass {
684 public:
685   static char ID; // Pass ID, replacement for typeid
686   DominatorTreeBase<BasicBlock>* DT;
687   
688   DominatorTree() : FunctionPass(&ID) {
689     DT = new DominatorTreeBase<BasicBlock>(false);
690   }
691   
692   ~DominatorTree() {
693     DT->releaseMemory();
694     delete DT;
695   }
696   
697   DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
698   
699   /// getRoots -  Return the root blocks of the current CFG.  This may include
700   /// multiple blocks if we are computing post dominators.  For forward
701   /// dominators, this will always be a single block (the entry node).
702   ///
703   inline const std::vector<BasicBlock*> &getRoots() const {
704     return DT->getRoots();
705   }
706   
707   inline BasicBlock *getRoot() const {
708     return DT->getRoot();
709   }
710   
711   inline DomTreeNode *getRootNode() const {
712     return DT->getRootNode();
713   }
714
715   /// compare - Return false if the other dominator tree matches this
716   /// dominator tree. Otherwise return true.
717   inline bool compare(DominatorTree &Other) const {
718     DomTreeNode *R = getRootNode();
719     DomTreeNode *OtherR = Other.getRootNode();
720     
721     if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
722       return true;
723     
724     if (DT->compare(Other.getBase()))
725       return true;
726
727     return false;
728   }
729
730   virtual bool runOnFunction(Function &F);
731   
732   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
733     AU.setPreservesAll();
734   }
735   
736   inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
737     return DT->dominates(A, B);
738   }
739   
740   inline bool dominates(BasicBlock* A, BasicBlock* B) const {
741     return DT->dominates(A, B);
742   }
743   
744   // dominates - Return true if A dominates B. This performs the
745   // special checks necessary if A and B are in the same basic block.
746   bool dominates(Instruction *A, Instruction *B) const {
747     BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
748     if (BBA != BBB) return DT->dominates(BBA, BBB);
749
750     // It is not possible to determine dominance between two PHI nodes 
751     // based on their ordering.
752     if (isa<PHINode>(A) && isa<PHINode>(B)) 
753       return false;
754
755     // Loop through the basic block until we find A or B.
756     BasicBlock::iterator I = BBA->begin();
757     for (; &*I != A && &*I != B; ++I) /*empty*/;
758
759     //if(!DT.IsPostDominators) {
760       // A dominates B if it is found first in the basic block.
761       return &*I == A;
762     //} else {
763     //  // A post-dominates B if B is found first in the basic block.
764     //  return &*I == B;
765     //}
766   }
767   
768   inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
769     return DT->properlyDominates(A, B);
770   }
771   
772   inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
773     return DT->properlyDominates(A, B);
774   }
775   
776   /// findNearestCommonDominator - Find nearest common dominator basic block
777   /// for basic block A and B. If there is no such block then return NULL.
778   inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
779     return DT->findNearestCommonDominator(A, B);
780   }
781   
782   inline DomTreeNode *operator[](BasicBlock *BB) const {
783     return DT->getNode(BB);
784   }
785   
786   /// getNode - return the (Post)DominatorTree node for the specified basic
787   /// block.  This is the same as using operator[] on this class.
788   ///
789   inline DomTreeNode *getNode(BasicBlock *BB) const {
790     return DT->getNode(BB);
791   }
792   
793   /// addNewBlock - Add a new node to the dominator tree information.  This
794   /// creates a new node as a child of DomBB dominator node,linking it into 
795   /// the children list of the immediate dominator.
796   inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
797     return DT->addNewBlock(BB, DomBB);
798   }
799   
800   /// changeImmediateDominator - This method is used to update the dominator
801   /// tree information when a node's immediate dominator changes.
802   ///
803   inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
804     DT->changeImmediateDominator(N, NewIDom);
805   }
806   
807   inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
808     DT->changeImmediateDominator(N, NewIDom);
809   }
810   
811   /// eraseNode - Removes a node from  the dominator tree. Block must not
812   /// domiante any other blocks. Removes node from its immediate dominator's
813   /// children list. Deletes dominator node associated with basic block BB.
814   inline void eraseNode(BasicBlock *BB) {
815     DT->eraseNode(BB);
816   }
817   
818   /// splitBlock - BB is split and now it has one successor. Update dominator
819   /// tree to reflect this change.
820   inline void splitBlock(BasicBlock* NewBB) {
821     DT->splitBlock(NewBB);
822   }
823   
824   bool isReachableFromEntry(BasicBlock* A) {
825     return DT->isReachableFromEntry(A);
826   }
827   
828   
829   virtual void releaseMemory() { 
830     DT->releaseMemory();
831   }
832   
833   virtual void print(std::ostream &OS, const Module* M= 0) const;
834 };
835
836 //===-------------------------------------
837 /// DominatorTree GraphTraits specialization so the DominatorTree can be
838 /// iterable by generic graph iterators.
839 ///
840 template <> struct GraphTraits<DomTreeNode *> {
841   typedef DomTreeNode NodeType;
842   typedef NodeType::iterator  ChildIteratorType;
843   
844   static NodeType *getEntryNode(NodeType *N) {
845     return N;
846   }
847   static inline ChildIteratorType child_begin(NodeType* N) {
848     return N->begin();
849   }
850   static inline ChildIteratorType child_end(NodeType* N) {
851     return N->end();
852   }
853 };
854
855 template <> struct GraphTraits<DominatorTree*>
856   : public GraphTraits<DomTreeNode *> {
857   static NodeType *getEntryNode(DominatorTree *DT) {
858     return DT->getRootNode();
859   }
860 };
861
862
863 //===----------------------------------------------------------------------===//
864 /// DominanceFrontierBase - Common base class for computing forward and inverse
865 /// dominance frontiers for a function.
866 ///
867 class DominanceFrontierBase : public FunctionPass {
868 public:
869   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
870   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
871 protected:
872   DomSetMapType Frontiers;
873   std::vector<BasicBlock*> Roots;
874   const bool IsPostDominators;
875   
876 public:
877   DominanceFrontierBase(void *ID, bool isPostDom) 
878     : FunctionPass(ID), IsPostDominators(isPostDom) {}
879
880   /// getRoots -  Return the root blocks of the current CFG.  This may include
881   /// multiple blocks if we are computing post dominators.  For forward
882   /// dominators, this will always be a single block (the entry node).
883   ///
884   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
885   
886   /// isPostDominator - Returns true if analysis based of postdoms
887   ///
888   bool isPostDominator() const { return IsPostDominators; }
889
890   virtual void releaseMemory() { Frontiers.clear(); }
891
892   // Accessor interface:
893   typedef DomSetMapType::iterator iterator;
894   typedef DomSetMapType::const_iterator const_iterator;
895   iterator       begin()       { return Frontiers.begin(); }
896   const_iterator begin() const { return Frontiers.begin(); }
897   iterator       end()         { return Frontiers.end(); }
898   const_iterator end()   const { return Frontiers.end(); }
899   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
900   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
901
902   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
903     assert(find(BB) == end() && "Block already in DominanceFrontier!");
904     Frontiers.insert(std::make_pair(BB, frontier));
905   }
906
907   /// removeBlock - Remove basic block BB's frontier.
908   void removeBlock(BasicBlock *BB) {
909     assert(find(BB) != end() && "Block is not in DominanceFrontier!");
910     for (iterator I = begin(), E = end(); I != E; ++I)
911       I->second.erase(BB);
912     Frontiers.erase(BB);
913   }
914
915   void addToFrontier(iterator I, BasicBlock *Node) {
916     assert(I != end() && "BB is not in DominanceFrontier!");
917     I->second.insert(Node);
918   }
919
920   void removeFromFrontier(iterator I, BasicBlock *Node) {
921     assert(I != end() && "BB is not in DominanceFrontier!");
922     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
923     I->second.erase(Node);
924   }
925
926   /// compareDomSet - Return false if two domsets match. Otherwise
927   /// return true;
928   bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
929     std::set<BasicBlock *> tmpSet;
930     for (DomSetType::const_iterator I = DS2.begin(),
931            E = DS2.end(); I != E; ++I) 
932       tmpSet.insert(*I);
933
934     for (DomSetType::const_iterator I = DS1.begin(),
935            E = DS1.end(); I != E; ) {
936       BasicBlock *Node = *I++;
937
938       if (tmpSet.erase(Node) == 0)
939         // Node is in DS1 but not in DS2.
940         return true;
941     }
942
943     if(!tmpSet.empty())
944       // There are nodes that are in DS2 but not in DS1.
945       return true;
946
947     // DS1 and DS2 matches.
948     return false;
949   }
950
951   /// compare - Return true if the other dominance frontier base matches
952   /// this dominance frontier base. Otherwise return false.
953   bool compare(DominanceFrontierBase &Other) const {
954     DomSetMapType tmpFrontiers;
955     for (DomSetMapType::const_iterator I = Other.begin(),
956            E = Other.end(); I != E; ++I) 
957       tmpFrontiers.insert(std::make_pair(I->first, I->second));
958
959     for (DomSetMapType::iterator I = tmpFrontiers.begin(),
960            E = tmpFrontiers.end(); I != E; ) {
961       BasicBlock *Node = I->first;
962       const_iterator DFI = find(Node);
963       if (DFI == end()) 
964         return true;
965
966       if (compareDomSet(I->second, DFI->second))
967         return true;
968
969       ++I;
970       tmpFrontiers.erase(Node);
971     }
972
973     if (!tmpFrontiers.empty())
974       return true;
975
976     return false;
977   }
978
979   /// print - Convert to human readable form
980   ///
981   virtual void print(std::ostream &OS, const Module* = 0) const;
982 };
983
984
985 //===-------------------------------------
986 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
987 /// used to compute a forward dominator frontiers.
988 ///
989 class DominanceFrontier : public DominanceFrontierBase {
990 public:
991   static char ID; // Pass ID, replacement for typeid
992   DominanceFrontier() : 
993     DominanceFrontierBase(&ID, false) {}
994
995   BasicBlock *getRoot() const {
996     assert(Roots.size() == 1 && "Should always have entry node!");
997     return Roots[0];
998   }
999
1000   virtual bool runOnFunction(Function &) {
1001     Frontiers.clear();
1002     DominatorTree &DT = getAnalysis<DominatorTree>();
1003     Roots = DT.getRoots();
1004     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1005     calculate(DT, DT[Roots[0]]);
1006     return false;
1007   }
1008
1009   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1010     AU.setPreservesAll();
1011     AU.addRequired<DominatorTree>();
1012   }
1013
1014   /// splitBlock - BB is split and now it has one successor. Update dominance
1015   /// frontier to reflect this change.
1016   void splitBlock(BasicBlock *BB);
1017
1018   /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1019   /// to reflect this change.
1020   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1021                                 DominatorTree *DT) {
1022     // NewBB is now  dominating BB. Which means BB's dominance
1023     // frontier is now part of NewBB's dominance frontier. However, BB
1024     // itself is not member of NewBB's dominance frontier.
1025     DominanceFrontier::iterator NewDFI = find(NewBB);
1026     DominanceFrontier::iterator DFI = find(BB);
1027     // If BB was an entry block then its frontier is empty.
1028     if (DFI == end())
1029       return;
1030     DominanceFrontier::DomSetType BBSet = DFI->second;
1031     for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1032            BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1033       BasicBlock *DFMember = *BBSetI;
1034       // Insert only if NewBB dominates DFMember.
1035       if (!DT->dominates(NewBB, DFMember))
1036         NewDFI->second.insert(DFMember);
1037     }
1038     NewDFI->second.erase(BB);
1039   }
1040
1041   const DomSetType &calculate(const DominatorTree &DT,
1042                               const DomTreeNode *Node);
1043 };
1044
1045
1046 } // End llvm namespace
1047
1048 #endif