Change ConstantFoldConstantExpression to accept a null
[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 <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 std::ostream &operator<<(std::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, std::ostream &o,
178                          unsigned Lev) {
179   o << std::string(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     assert(i != PredBlocks.size() && "No reachable preds?");
274     for (i = i + 1; i < PredBlocks.size(); ++i) {
275       if (DT.isReachableFromEntry(PredBlocks[i]))
276         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
277     }
278     assert(NewBBIDom && "No immediate dominator found??");
279
280     // Create the new dominator tree node... and set the idom of NewBB.
281     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
282
283     // If NewBB strictly dominates other blocks, then it is now the immediate
284     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
285     if (NewBBDominatesNewBBSucc) {
286       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
287       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
288     }
289   }
290
291 public:
292   explicit DominatorTreeBase(bool isPostDom)
293     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
294   virtual ~DominatorTreeBase() { reset(); }
295
296   // FIXME: Should remove this
297   virtual bool runOnFunction(Function &F) { return false; }
298
299   /// compare - Return false if the other dominator tree base matches this
300   /// dominator tree base. Otherwise return true.
301   bool compare(DominatorTreeBase &Other) const {
302
303     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
304     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
305       return true;
306
307     SmallPtrSet<const NodeT *,4> MyBBs;
308     for (typename DomTreeNodeMapType::const_iterator 
309            I = this->DomTreeNodes.begin(),
310            E = this->DomTreeNodes.end(); I != E; ++I) {
311       NodeT *BB = I->first;
312       typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
313       if (OI == OtherDomTreeNodes.end())
314         return true;
315
316       DomTreeNodeBase<NodeT>* MyNd = I->second;
317       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
318       
319       if (MyNd->compare(OtherNd))
320         return true;
321     }
322
323     return false;
324   }
325
326   virtual void releaseMemory() { reset(); }
327
328   /// getNode - return the (Post)DominatorTree node for the specified basic
329   /// block.  This is the same as using operator[] on this class.
330   ///
331   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
332     typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
333     return I != DomTreeNodes.end() ? I->second : 0;
334   }
335
336   /// getRootNode - This returns the entry node for the CFG of the function.  If
337   /// this tree represents the post-dominance relations for a function, however,
338   /// this root may be a node with the block == NULL.  This is the case when
339   /// there are multiple exit nodes from a particular function.  Consumers of
340   /// post-dominance information must be capable of dealing with this
341   /// possibility.
342   ///
343   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
344   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
345
346   /// properlyDominates - Returns true iff this dominates N and this != N.
347   /// Note that this is not a constant time operation!
348   ///
349   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
350                          DomTreeNodeBase<NodeT> *B) const {
351     if (A == 0 || B == 0) return false;
352     return dominatedBySlowTreeWalk(A, B);
353   }
354
355   inline bool properlyDominates(NodeT *A, NodeT *B) {
356     return properlyDominates(getNode(A), getNode(B));
357   }
358
359   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, 
360                                const DomTreeNodeBase<NodeT> *B) const {
361     const DomTreeNodeBase<NodeT> *IDom;
362     if (A == 0 || B == 0) return false;
363     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
364       B = IDom;   // Walk up the tree
365     return IDom != 0;
366   }
367
368
369   /// isReachableFromEntry - Return true if A is dominated by the entry
370   /// block of the function containing it.
371   bool isReachableFromEntry(NodeT* A) {
372     assert (!this->isPostDominator() 
373             && "This is not implemented for post dominators");
374     return dominates(&A->getParent()->front(), A);
375   }
376   
377   /// dominates - Returns true iff A dominates B.  Note that this is not a
378   /// constant time operation!
379   ///
380   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
381                         DomTreeNodeBase<NodeT> *B) {
382     if (B == A) 
383       return true;  // A node trivially dominates itself.
384
385     if (A == 0 || B == 0)
386       return false;
387
388     if (DFSInfoValid)
389       return B->DominatedBy(A);
390
391     // If we end up with too many slow queries, just update the
392     // DFS numbers on the theory that we are going to keep querying.
393     SlowQueries++;
394     if (SlowQueries > 32) {
395       updateDFSNumbers();
396       return B->DominatedBy(A);
397     }
398
399     return dominatedBySlowTreeWalk(A, B);
400   }
401
402   inline bool dominates(NodeT *A, NodeT *B) {
403     if (A == B) 
404       return true;
405     
406     return dominates(getNode(A), getNode(B));
407   }
408   
409   NodeT *getRoot() const {
410     assert(this->Roots.size() == 1 && "Should always have entry node!");
411     return this->Roots[0];
412   }
413
414   /// findNearestCommonDominator - Find nearest common dominator basic block
415   /// for basic block A and B. If there is no such block then return NULL.
416   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
417
418     assert (!this->isPostDominator() 
419             && "This is not implemented for post dominators");
420     assert (A->getParent() == B->getParent() 
421             && "Two blocks are not in same function");
422
423     // If either A or B is a entry block then it is nearest common dominator.
424     NodeT &Entry  = A->getParent()->front();
425     if (A == &Entry || B == &Entry)
426       return &Entry;
427
428     // If B dominates A then B is nearest common dominator.
429     if (dominates(B, A))
430       return B;
431
432     // If A dominates B then A is nearest common dominator.
433     if (dominates(A, B))
434       return A;
435
436     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
437     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
438
439     // Collect NodeA dominators set.
440     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
441     NodeADoms.insert(NodeA);
442     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
443     while (IDomA) {
444       NodeADoms.insert(IDomA);
445       IDomA = IDomA->getIDom();
446     }
447
448     // Walk NodeB immediate dominators chain and find common dominator node.
449     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
450     while(IDomB) {
451       if (NodeADoms.count(IDomB) != 0)
452         return IDomB->getBlock();
453
454       IDomB = IDomB->getIDom();
455     }
456
457     return NULL;
458   }
459
460   //===--------------------------------------------------------------------===//
461   // API to update (Post)DominatorTree information based on modifications to
462   // the CFG...
463
464   /// addNewBlock - Add a new node to the dominator tree information.  This
465   /// creates a new node as a child of DomBB dominator node,linking it into 
466   /// the children list of the immediate dominator.
467   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
468     assert(getNode(BB) == 0 && "Block already in dominator tree!");
469     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
470     assert(IDomNode && "Not immediate dominator specified for block!");
471     DFSInfoValid = false;
472     return DomTreeNodes[BB] = 
473       IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
474   }
475
476   /// changeImmediateDominator - This method is used to update the dominator
477   /// tree information when a node's immediate dominator changes.
478   ///
479   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
480                                 DomTreeNodeBase<NodeT> *NewIDom) {
481     assert(N && NewIDom && "Cannot change null node pointers!");
482     DFSInfoValid = false;
483     N->setIDom(NewIDom);
484   }
485
486   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
487     changeImmediateDominator(getNode(BB), getNode(NewBB));
488   }
489
490   /// eraseNode - Removes a node from  the dominator tree. Block must not
491   /// domiante any other blocks. Removes node from its immediate dominator's
492   /// children list. Deletes dominator node associated with basic block BB.
493   void eraseNode(NodeT *BB) {
494     DomTreeNodeBase<NodeT> *Node = getNode(BB);
495     assert (Node && "Removing node that isn't in dominator tree.");
496     assert (Node->getChildren().empty() && "Node is not a leaf node.");
497
498       // Remove node from immediate dominator's children list.
499     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
500     if (IDom) {
501       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
502         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
503       assert(I != IDom->Children.end() &&
504              "Not in immediate dominator children set!");
505       // I am no longer your child...
506       IDom->Children.erase(I);
507     }
508
509     DomTreeNodes.erase(BB);
510     delete Node;
511   }
512
513   /// removeNode - Removes a node from the dominator tree.  Block must not
514   /// dominate any other blocks.  Invalidates any node pointing to removed
515   /// block.
516   void removeNode(NodeT *BB) {
517     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
518     DomTreeNodes.erase(BB);
519   }
520   
521   /// splitBlock - BB is split and now it has one successor. Update dominator
522   /// tree to reflect this change.
523   void splitBlock(NodeT* NewBB) {
524     if (this->IsPostDominators)
525       this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
526     else
527       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
528   }
529
530   /// print - Convert to human readable form
531   ///
532   virtual void print(std::ostream &o, const Module* ) const {
533     o << "=============================--------------------------------\n";
534     if (this->isPostDominator())
535       o << "Inorder PostDominator Tree: ";
536     else
537       o << "Inorder Dominator Tree: ";
538     if (this->DFSInfoValid)
539       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
540     o << "\n";
541
542     PrintDomTree<NodeT>(getRootNode(), o, 1);
543   }
544   
545   void print(std::ostream *OS, const Module* M = 0) const {
546     if (OS) print(*OS, M);
547   }
548   
549   virtual void dump() {
550     print(llvm::cerr);
551   }
552   
553 protected:
554   template<class GraphT>
555   friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
556                        typename GraphT::NodeType* VIn);
557
558   template<class GraphT>
559   friend typename GraphT::NodeType* Eval(
560                                DominatorTreeBase<typename GraphT::NodeType>& DT,
561                                          typename GraphT::NodeType* V);
562
563   template<class GraphT>
564   friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
565                    unsigned DFSNumV, typename GraphT::NodeType* W,
566          typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
567   
568   template<class GraphT>
569   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
570                           typename GraphT::NodeType* V,
571                           unsigned N);
572   
573   template<class FuncT, class N>
574   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
575                         FuncT& F);
576   
577   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
578   /// dominator tree in dfs order.
579   void updateDFSNumbers() {
580     unsigned DFSNum = 0;
581
582     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
583                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
584
585     for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
586       DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
587       WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
588       ThisRoot->DFSNumIn = DFSNum++;
589
590       while (!WorkStack.empty()) {
591         DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
592         typename DomTreeNodeBase<NodeT>::iterator ChildIt =
593                                                         WorkStack.back().second;
594
595         // If we visited all of the children of this node, "recurse" back up the
596         // stack setting the DFOutNum.
597         if (ChildIt == Node->end()) {
598           Node->DFSNumOut = DFSNum++;
599           WorkStack.pop_back();
600         } else {
601           // Otherwise, recursively visit this child.
602           DomTreeNodeBase<NodeT> *Child = *ChildIt;
603           ++WorkStack.back().second;
604           
605           WorkStack.push_back(std::make_pair(Child, Child->begin()));
606           Child->DFSNumIn = DFSNum++;
607         }
608       }
609     }
610     
611     SlowQueries = 0;
612     DFSInfoValid = true;
613   }
614   
615   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
616     if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
617       return BBNode;
618
619     // Haven't calculated this node yet?  Get or calculate the node for the
620     // immediate dominator.
621     NodeT *IDom = getIDom(BB);
622
623     assert(IDom || this->DomTreeNodes[NULL]);
624     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
625
626     // Add a new tree node for this BasicBlock, and link it as a child of
627     // IDomNode
628     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
629     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
630   }
631   
632   inline NodeT *getIDom(NodeT *BB) const {
633     typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
634     return I != IDoms.end() ? I->second : 0;
635   }
636   
637   inline void addRoot(NodeT* BB) {
638     this->Roots.push_back(BB);
639   }
640   
641 public:
642   /// recalculate - compute a dominator tree for the given function
643   template<class FT>
644   void recalculate(FT& F) {
645     if (!this->IsPostDominators) {
646       reset();
647       
648       // Initialize roots
649       this->Roots.push_back(&F.front());
650       this->IDoms[&F.front()] = 0;
651       this->DomTreeNodes[&F.front()] = 0;
652       this->Vertex.push_back(0);
653       
654       Calculate<FT, NodeT*>(*this, F);
655       
656       updateDFSNumbers();
657     } else {
658       reset();     // Reset from the last time we were run...
659
660       // Initialize the roots list
661       for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
662         if (std::distance(GraphTraits<FT*>::child_begin(I),
663                           GraphTraits<FT*>::child_end(I)) == 0)
664           addRoot(I);
665
666         // Prepopulate maps so that we don't get iterator invalidation issues later.
667         this->IDoms[I] = 0;
668         this->DomTreeNodes[I] = 0;
669       }
670
671       this->Vertex.push_back(0);
672       
673       Calculate<FT, Inverse<NodeT*> >(*this, F);
674     }
675   }
676 };
677
678 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
679
680 //===-------------------------------------
681 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
682 /// compute a normal dominator tree.
683 ///
684 class DominatorTree : public FunctionPass {
685 public:
686   static char ID; // Pass ID, replacement for typeid
687   DominatorTreeBase<BasicBlock>* DT;
688   
689   DominatorTree() : FunctionPass(&ID) {
690     DT = new DominatorTreeBase<BasicBlock>(false);
691   }
692   
693   ~DominatorTree() {
694     DT->releaseMemory();
695     delete DT;
696   }
697   
698   DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
699   
700   /// getRoots -  Return the root blocks of the current CFG.  This may include
701   /// multiple blocks if we are computing post dominators.  For forward
702   /// dominators, this will always be a single block (the entry node).
703   ///
704   inline const std::vector<BasicBlock*> &getRoots() const {
705     return DT->getRoots();
706   }
707   
708   inline BasicBlock *getRoot() const {
709     return DT->getRoot();
710   }
711   
712   inline DomTreeNode *getRootNode() const {
713     return DT->getRootNode();
714   }
715
716   /// compare - Return false if the other dominator tree matches this
717   /// dominator tree. Otherwise return true.
718   inline bool compare(DominatorTree &Other) const {
719     DomTreeNode *R = getRootNode();
720     DomTreeNode *OtherR = Other.getRootNode();
721     
722     if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
723       return true;
724     
725     if (DT->compare(Other.getBase()))
726       return true;
727
728     return false;
729   }
730
731   virtual bool runOnFunction(Function &F);
732   
733   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
734     AU.setPreservesAll();
735   }
736   
737   inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
738     return DT->dominates(A, B);
739   }
740   
741   inline bool dominates(BasicBlock* A, BasicBlock* B) const {
742     return DT->dominates(A, B);
743   }
744   
745   // dominates - Return true if A dominates B. This performs the
746   // special checks necessary if A and B are in the same basic block.
747   bool dominates(Instruction *A, Instruction *B) const {
748     BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
749     if (BBA != BBB) return DT->dominates(BBA, BBB);
750
751     // It is not possible to determine dominance between two PHI nodes 
752     // based on their ordering.
753     if (isa<PHINode>(A) && isa<PHINode>(B)) 
754       return false;
755
756     // Loop through the basic block until we find A or B.
757     BasicBlock::iterator I = BBA->begin();
758     for (; &*I != A && &*I != B; ++I) /*empty*/;
759
760     //if(!DT.IsPostDominators) {
761       // A dominates B if it is found first in the basic block.
762       return &*I == A;
763     //} else {
764     //  // A post-dominates B if B is found first in the basic block.
765     //  return &*I == B;
766     //}
767   }
768   
769   inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
770     return DT->properlyDominates(A, B);
771   }
772   
773   inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
774     return DT->properlyDominates(A, B);
775   }
776   
777   /// findNearestCommonDominator - Find nearest common dominator basic block
778   /// for basic block A and B. If there is no such block then return NULL.
779   inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
780     return DT->findNearestCommonDominator(A, B);
781   }
782   
783   inline DomTreeNode *operator[](BasicBlock *BB) const {
784     return DT->getNode(BB);
785   }
786   
787   /// getNode - return the (Post)DominatorTree node for the specified basic
788   /// block.  This is the same as using operator[] on this class.
789   ///
790   inline DomTreeNode *getNode(BasicBlock *BB) const {
791     return DT->getNode(BB);
792   }
793   
794   /// addNewBlock - Add a new node to the dominator tree information.  This
795   /// creates a new node as a child of DomBB dominator node,linking it into 
796   /// the children list of the immediate dominator.
797   inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
798     return DT->addNewBlock(BB, DomBB);
799   }
800   
801   /// changeImmediateDominator - This method is used to update the dominator
802   /// tree information when a node's immediate dominator changes.
803   ///
804   inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
805     DT->changeImmediateDominator(N, NewIDom);
806   }
807   
808   inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
809     DT->changeImmediateDominator(N, NewIDom);
810   }
811   
812   /// eraseNode - Removes a node from  the dominator tree. Block must not
813   /// domiante any other blocks. Removes node from its immediate dominator's
814   /// children list. Deletes dominator node associated with basic block BB.
815   inline void eraseNode(BasicBlock *BB) {
816     DT->eraseNode(BB);
817   }
818   
819   /// splitBlock - BB is split and now it has one successor. Update dominator
820   /// tree to reflect this change.
821   inline void splitBlock(BasicBlock* NewBB) {
822     DT->splitBlock(NewBB);
823   }
824   
825   bool isReachableFromEntry(BasicBlock* A) {
826     return DT->isReachableFromEntry(A);
827   }
828   
829   
830   virtual void releaseMemory() { 
831     DT->releaseMemory();
832   }
833   
834   virtual void print(std::ostream &OS, const Module* M= 0) const {
835     DT->print(OS, M);
836   }
837 };
838
839 //===-------------------------------------
840 /// DominatorTree GraphTraits specialization so the DominatorTree can be
841 /// iterable by generic graph iterators.
842 ///
843 template <> struct GraphTraits<DomTreeNode *> {
844   typedef DomTreeNode NodeType;
845   typedef NodeType::iterator  ChildIteratorType;
846   
847   static NodeType *getEntryNode(NodeType *N) {
848     return N;
849   }
850   static inline ChildIteratorType child_begin(NodeType* N) {
851     return N->begin();
852   }
853   static inline ChildIteratorType child_end(NodeType* N) {
854     return N->end();
855   }
856 };
857
858 template <> struct GraphTraits<DominatorTree*>
859   : public GraphTraits<DomTreeNode *> {
860   static NodeType *getEntryNode(DominatorTree *DT) {
861     return DT->getRootNode();
862   }
863 };
864
865
866 //===----------------------------------------------------------------------===//
867 /// DominanceFrontierBase - Common base class for computing forward and inverse
868 /// dominance frontiers for a function.
869 ///
870 class DominanceFrontierBase : public FunctionPass {
871 public:
872   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
873   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
874 protected:
875   DomSetMapType Frontiers;
876   std::vector<BasicBlock*> Roots;
877   const bool IsPostDominators;
878   
879 public:
880   DominanceFrontierBase(void *ID, bool isPostDom) 
881     : FunctionPass(ID), IsPostDominators(isPostDom) {}
882
883   /// getRoots -  Return the root blocks of the current CFG.  This may include
884   /// multiple blocks if we are computing post dominators.  For forward
885   /// dominators, this will always be a single block (the entry node).
886   ///
887   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
888   
889   /// isPostDominator - Returns true if analysis based of postdoms
890   ///
891   bool isPostDominator() const { return IsPostDominators; }
892
893   virtual void releaseMemory() { Frontiers.clear(); }
894
895   // Accessor interface:
896   typedef DomSetMapType::iterator iterator;
897   typedef DomSetMapType::const_iterator const_iterator;
898   iterator       begin()       { return Frontiers.begin(); }
899   const_iterator begin() const { return Frontiers.begin(); }
900   iterator       end()         { return Frontiers.end(); }
901   const_iterator end()   const { return Frontiers.end(); }
902   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
903   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
904
905   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
906     assert(find(BB) == end() && "Block already in DominanceFrontier!");
907     Frontiers.insert(std::make_pair(BB, frontier));
908   }
909
910   /// removeBlock - Remove basic block BB's frontier.
911   void removeBlock(BasicBlock *BB) {
912     assert(find(BB) != end() && "Block is not in DominanceFrontier!");
913     for (iterator I = begin(), E = end(); I != E; ++I)
914       I->second.erase(BB);
915     Frontiers.erase(BB);
916   }
917
918   void addToFrontier(iterator I, BasicBlock *Node) {
919     assert(I != end() && "BB is not in DominanceFrontier!");
920     I->second.insert(Node);
921   }
922
923   void removeFromFrontier(iterator I, BasicBlock *Node) {
924     assert(I != end() && "BB is not in DominanceFrontier!");
925     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
926     I->second.erase(Node);
927   }
928
929   /// compareDomSet - Return false if two domsets match. Otherwise
930   /// return true;
931   bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
932     std::set<BasicBlock *> tmpSet;
933     for (DomSetType::const_iterator I = DS2.begin(),
934            E = DS2.end(); I != E; ++I) 
935       tmpSet.insert(*I);
936
937     for (DomSetType::const_iterator I = DS1.begin(),
938            E = DS1.end(); I != E; ) {
939       BasicBlock *Node = *I++;
940
941       if (tmpSet.erase(Node) == 0)
942         // Node is in DS1 but not in DS2.
943         return true;
944     }
945
946     if(!tmpSet.empty())
947       // There are nodes that are in DS2 but not in DS1.
948       return true;
949
950     // DS1 and DS2 matches.
951     return false;
952   }
953
954   /// compare - Return true if the other dominance frontier base matches
955   /// this dominance frontier base. Otherwise return false.
956   bool compare(DominanceFrontierBase &Other) const {
957     DomSetMapType tmpFrontiers;
958     for (DomSetMapType::const_iterator I = Other.begin(),
959            E = Other.end(); I != E; ++I) 
960       tmpFrontiers.insert(std::make_pair(I->first, I->second));
961
962     for (DomSetMapType::iterator I = tmpFrontiers.begin(),
963            E = tmpFrontiers.end(); I != E; ) {
964       BasicBlock *Node = I->first;
965       const_iterator DFI = find(Node);
966       if (DFI == end()) 
967         return true;
968
969       if (compareDomSet(I->second, DFI->second))
970         return true;
971
972       ++I;
973       tmpFrontiers.erase(Node);
974     }
975
976     if (!tmpFrontiers.empty())
977       return true;
978
979     return false;
980   }
981
982   /// print - Convert to human readable form
983   ///
984   virtual void print(std::ostream &OS, const Module* = 0) const;
985   void print(std::ostream *OS, const Module* M = 0) const {
986     if (OS) print(*OS, M);
987   }
988   virtual void dump();
989 };
990
991
992 //===-------------------------------------
993 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
994 /// used to compute a forward dominator frontiers.
995 ///
996 class DominanceFrontier : public DominanceFrontierBase {
997 public:
998   static char ID; // Pass ID, replacement for typeid
999   DominanceFrontier() : 
1000     DominanceFrontierBase(&ID, false) {}
1001
1002   BasicBlock *getRoot() const {
1003     assert(Roots.size() == 1 && "Should always have entry node!");
1004     return Roots[0];
1005   }
1006
1007   virtual bool runOnFunction(Function &) {
1008     Frontiers.clear();
1009     DominatorTree &DT = getAnalysis<DominatorTree>();
1010     Roots = DT.getRoots();
1011     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1012     calculate(DT, DT[Roots[0]]);
1013     return false;
1014   }
1015
1016   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1017     AU.setPreservesAll();
1018     AU.addRequired<DominatorTree>();
1019   }
1020
1021   /// splitBlock - BB is split and now it has one successor. Update dominance
1022   /// frontier to reflect this change.
1023   void splitBlock(BasicBlock *BB);
1024
1025   /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1026   /// to reflect this change.
1027   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1028                                 DominatorTree *DT) {
1029     // NewBB is now  dominating BB. Which means BB's dominance
1030     // frontier is now part of NewBB's dominance frontier. However, BB
1031     // itself is not member of NewBB's dominance frontier.
1032     DominanceFrontier::iterator NewDFI = find(NewBB);
1033     DominanceFrontier::iterator DFI = find(BB);
1034     // If BB was an entry block then its frontier is empty.
1035     if (DFI == end())
1036       return;
1037     DominanceFrontier::DomSetType BBSet = DFI->second;
1038     for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1039            BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1040       BasicBlock *DFMember = *BBSetI;
1041       // Insert only if NewBB dominates DFMember.
1042       if (!DT->dominates(NewBB, DFMember))
1043         NewDFI->second.insert(DFMember);
1044     }
1045     NewDFI->second.erase(BB);
1046   }
1047
1048   const DomSetType &calculate(const DominatorTree &DT,
1049                               const DomTreeNode *Node);
1050 };
1051
1052
1053 } // End llvm namespace
1054
1055 #endif