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