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