Fix DFS number calculation for postdominators
[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/DepthFirstIterator.h"
29 #include "llvm/ADT/GraphTraits.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <map>
38 #include <set>
39
40 namespace llvm {
41
42 //===----------------------------------------------------------------------===//
43 /// DominatorBase - Base class that other, more interesting dominator analyses
44 /// inherit from.
45 ///
46 template <class NodeT>
47 class DominatorBase {
48 protected:
49   std::vector<NodeT*> Roots;
50   const bool IsPostDominators;
51   inline explicit DominatorBase(bool isPostDom) :
52     Roots(), IsPostDominators(isPostDom) {}
53 public:
54
55   /// getRoots -  Return the root blocks of the current CFG.  This may include
56   /// multiple blocks if we are computing post dominators.  For forward
57   /// dominators, this will always be a single block (the entry node).
58   ///
59   inline const std::vector<NodeT*> &getRoots() const { return Roots; }
60
61   /// isPostDominator - Returns true if analysis based of postdoms
62   ///
63   bool isPostDominator() const { return IsPostDominators; }
64 };
65
66
67 //===----------------------------------------------------------------------===//
68 // DomTreeNode - Dominator Tree Node
69 template<class NodeT> class DominatorTreeBase;
70 struct PostDominatorTree;
71 class MachineBasicBlock;
72
73 template <class NodeT>
74 class DomTreeNodeBase {
75   NodeT *TheBB;
76   DomTreeNodeBase<NodeT> *IDom;
77   std::vector<DomTreeNodeBase<NodeT> *> Children;
78   int DFSNumIn, DFSNumOut;
79
80   template<class N> friend class DominatorTreeBase;
81   friend struct PostDominatorTree;
82 public:
83   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
84   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
85                    const_iterator;
86
87   iterator begin()             { return Children.begin(); }
88   iterator end()               { return Children.end(); }
89   const_iterator begin() const { return Children.begin(); }
90   const_iterator end()   const { return Children.end(); }
91
92   NodeT *getBlock() const { return TheBB; }
93   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
94   const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
95     return Children;
96   }
97
98   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
99     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
100
101   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
102     Children.push_back(C);
103     return C;
104   }
105
106   size_t getNumChildren() const {
107     return Children.size();
108   }
109
110   void clearAllChildren() {
111     Children.clear();
112   }
113
114   bool compare(DomTreeNodeBase<NodeT> *Other) {
115     if (getNumChildren() != Other->getNumChildren())
116       return true;
117
118     SmallPtrSet<NodeT *, 4> OtherChildren;
119     for(iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
120       NodeT *Nd = (*I)->getBlock();
121       OtherChildren.insert(Nd);
122     }
123
124     for(iterator I = begin(), E = end(); I != E; ++I) {
125       NodeT *N = (*I)->getBlock();
126       if (OtherChildren.count(N) == 0)
127         return true;
128     }
129     return false;
130   }
131
132   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
133     assert(IDom && "No immediate dominator?");
134     if (IDom != NewIDom) {
135       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
136                   std::find(IDom->Children.begin(), IDom->Children.end(), this);
137       assert(I != IDom->Children.end() &&
138              "Not in immediate dominator children set!");
139       // I am no longer your child...
140       IDom->Children.erase(I);
141
142       // Switch to new dominator
143       IDom = NewIDom;
144       IDom->Children.push_back(this);
145     }
146   }
147
148   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
149   /// not call them.
150   unsigned getDFSNumIn() const { return DFSNumIn; }
151   unsigned getDFSNumOut() const { return DFSNumOut; }
152 private:
153   // Return true if this node is dominated by other. Use this only if DFS info
154   // is valid.
155   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
156     return this->DFSNumIn >= other->DFSNumIn &&
157       this->DFSNumOut <= other->DFSNumOut;
158   }
159 };
160
161 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
162 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
163
164 template<class NodeT>
165 static raw_ostream &operator<<(raw_ostream &o,
166                                const DomTreeNodeBase<NodeT> *Node) {
167   if (Node->getBlock())
168     WriteAsOperand(o, Node->getBlock(), false);
169   else
170     o << " <<exit node>>";
171
172   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
173
174   return o << "\n";
175 }
176
177 template<class NodeT>
178 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
179                          unsigned Lev) {
180   o.indent(2*Lev) << "[" << Lev << "] " << N;
181   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
182        E = N->end(); I != E; ++I)
183     PrintDomTree<NodeT>(*I, o, Lev+1);
184 }
185
186 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
187
188 //===----------------------------------------------------------------------===//
189 /// DominatorTree - Calculate the immediate dominator tree for a function.
190 ///
191
192 template<class FuncT, class N>
193 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
194                FuncT& F);
195
196 template<class NodeT>
197 class DominatorTreeBase : public DominatorBase<NodeT> {
198 protected:
199   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
200   DomTreeNodeMapType DomTreeNodes;
201   DomTreeNodeBase<NodeT> *RootNode;
202
203   bool DFSInfoValid;
204   unsigned int SlowQueries;
205   // Information record used during immediate dominators computation.
206   struct InfoRec {
207     unsigned DFSNum;
208     unsigned Semi;
209     unsigned Size;
210     NodeT *Label, *Child;
211     unsigned Parent, Ancestor;
212
213     std::vector<NodeT*> Bucket;
214
215     InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
216                 Ancestor(0) {}
217   };
218
219   DenseMap<NodeT*, NodeT*> IDoms;
220
221   // Vertex - Map the DFS number to the BasicBlock*
222   std::vector<NodeT*> Vertex;
223
224   // Info - Collection of information used during the computation of idoms.
225   DenseMap<NodeT*, InfoRec> Info;
226
227   void reset() {
228     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(), 
229            E = DomTreeNodes.end(); I != E; ++I)
230       delete I->second;
231     DomTreeNodes.clear();
232     IDoms.clear();
233     this->Roots.clear();
234     Vertex.clear();
235     RootNode = 0;
236   }
237
238   // NewBB is split and now it has one successor. Update dominator tree to
239   // reflect this change.
240   template<class N, class GraphT>
241   void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
242              typename GraphT::NodeType* NewBB) {
243     assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
244            && "NewBB should have a single successor!");
245     typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
246
247     std::vector<typename GraphT::NodeType*> PredBlocks;
248     for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
249          GraphTraits<Inverse<N> >::child_begin(NewBB),
250          PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
251       PredBlocks.push_back(*PI);  
252
253     assert(!PredBlocks.empty() && "No predblocks??");
254
255     bool NewBBDominatesNewBBSucc = true;
256     for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
257          GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
258          E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
259       if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI) &&
260           DT.isReachableFromEntry(*PI)) {
261         NewBBDominatesNewBBSucc = false;
262         break;
263       }
264
265     // Find NewBB's immediate dominator and create new dominator tree node for
266     // NewBB.
267     NodeT *NewBBIDom = 0;
268     unsigned i = 0;
269     for (i = 0; i < PredBlocks.size(); ++i)
270       if (DT.isReachableFromEntry(PredBlocks[i])) {
271         NewBBIDom = PredBlocks[i];
272         break;
273       }
274
275     // It's possible that none of the predecessors of NewBB are reachable;
276     // in that case, NewBB itself is unreachable, so nothing needs to be
277     // changed.
278     if (!NewBBIDom)
279       return;
280
281     for (i = i + 1; i < PredBlocks.size(); ++i) {
282       if (DT.isReachableFromEntry(PredBlocks[i]))
283         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
284     }
285
286     // Create the new dominator tree node... and set the idom of NewBB.
287     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
288
289     // If NewBB strictly dominates other blocks, then it is now the immediate
290     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
291     if (NewBBDominatesNewBBSucc) {
292       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
293       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
294     }
295   }
296
297 public:
298   explicit DominatorTreeBase(bool isPostDom)
299     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
300   virtual ~DominatorTreeBase() { reset(); }
301
302   // FIXME: Should remove this
303   virtual bool runOnFunction(Function &F) { return false; }
304
305   /// compare - Return false if the other dominator tree base matches this
306   /// dominator tree base. Otherwise return true.
307   bool compare(DominatorTreeBase &Other) const {
308
309     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
310     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
311       return true;
312
313     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     // The postdom tree can have a null root if there are no returns.
552     if (getRootNode())
553       PrintDomTree<NodeT>(getRootNode(), o, 1);
554   }
555
556 protected:
557   template<class GraphT>
558   friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
559                        typename GraphT::NodeType* VIn);
560
561   template<class GraphT>
562   friend typename GraphT::NodeType* Eval(
563                                DominatorTreeBase<typename GraphT::NodeType>& DT,
564                                          typename GraphT::NodeType* V);
565
566   template<class GraphT>
567   friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
568                    unsigned DFSNumV, typename GraphT::NodeType* W,
569          typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
570
571   template<class GraphT>
572   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
573                           typename GraphT::NodeType* V,
574                           unsigned N);
575
576   template<class FuncT, class N>
577   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
578                         FuncT& F);
579
580   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
581   /// dominator tree in dfs order.
582   void updateDFSNumbers() {
583     unsigned DFSNum = 0;
584
585     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
586                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
587
588     DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
589
590     if (!ThisRoot)
591       return;
592
593     // Even in the case of multiple exits that form the post dominator root
594     // nodes, do not iterate over all exits, but start from the virtual root
595     // node. Otherwise bbs, that are not post dominated by any exit but by the
596     // virtual root node, will never be assigned a DFS number.
597     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
598     ThisRoot->DFSNumIn = DFSNum++;
599
600     while (!WorkStack.empty()) {
601       DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
602       typename DomTreeNodeBase<NodeT>::iterator ChildIt =
603         WorkStack.back().second;
604
605       // If we visited all of the children of this node, "recurse" back up the
606       // stack setting the DFOutNum.
607       if (ChildIt == Node->end()) {
608         Node->DFSNumOut = DFSNum++;
609         WorkStack.pop_back();
610       } else {
611         // Otherwise, recursively visit this child.
612         DomTreeNodeBase<NodeT> *Child = *ChildIt;
613         ++WorkStack.back().second;
614
615         WorkStack.push_back(std::make_pair(Child, Child->begin()));
616         Child->DFSNumIn = DFSNum++;
617       }
618     }
619
620     SlowQueries = 0;
621     DFSInfoValid = true;
622   }
623
624   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
625     typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
626     if (I != this->DomTreeNodes.end() && I->second)
627       return I->second;
628
629     // Haven't calculated this node yet?  Get or calculate the node for the
630     // immediate dominator.
631     NodeT *IDom = getIDom(BB);
632
633     assert(IDom || this->DomTreeNodes[NULL]);
634     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
635
636     // Add a new tree node for this BasicBlock, and link it as a child of
637     // IDomNode
638     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
639     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
640   }
641
642   inline NodeT *getIDom(NodeT *BB) const {
643     typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
644     return I != IDoms.end() ? I->second : 0;
645   }
646
647   inline void addRoot(NodeT* BB) {
648     this->Roots.push_back(BB);
649   }
650
651 public:
652   /// recalculate - compute a dominator tree for the given function
653   template<class FT>
654   void recalculate(FT& F) {
655     if (!this->IsPostDominators) {
656       reset();
657
658       // Initialize roots
659       this->Roots.push_back(&F.front());
660       this->IDoms[&F.front()] = 0;
661       this->DomTreeNodes[&F.front()] = 0;
662       this->Vertex.push_back(0);
663
664       Calculate<FT, NodeT*>(*this, F);
665
666       updateDFSNumbers();
667     } else {
668       reset();     // Reset from the last time we were run...
669
670       // Initialize the roots list
671       for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
672         if (std::distance(GraphTraits<FT*>::child_begin(I),
673                           GraphTraits<FT*>::child_end(I)) == 0)
674           addRoot(I);
675
676         // Prepopulate maps so that we don't get iterator invalidation issues later.
677         this->IDoms[I] = 0;
678         this->DomTreeNodes[I] = 0;
679       }
680
681       this->Vertex.push_back(0);
682
683       Calculate<FT, Inverse<NodeT*> >(*this, F);
684     }
685   }
686 };
687
688 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
689
690 //===-------------------------------------
691 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
692 /// compute a normal dominator tree.
693 ///
694 class DominatorTree : public FunctionPass {
695 public:
696   static char ID; // Pass ID, replacement for typeid
697   DominatorTreeBase<BasicBlock>* DT;
698
699   DominatorTree() : FunctionPass(&ID) {
700     DT = new DominatorTreeBase<BasicBlock>(false);
701   }
702
703   ~DominatorTree() {
704     DT->releaseMemory();
705     delete DT;
706   }
707
708   DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
709
710   /// getRoots -  Return the root blocks of the current CFG.  This may include
711   /// multiple blocks if we are computing post dominators.  For forward
712   /// dominators, this will always be a single block (the entry node).
713   ///
714   inline const std::vector<BasicBlock*> &getRoots() const {
715     return DT->getRoots();
716   }
717
718   inline BasicBlock *getRoot() const {
719     return DT->getRoot();
720   }
721
722   inline DomTreeNode *getRootNode() const {
723     return DT->getRootNode();
724   }
725
726   /// compare - Return false if the other dominator tree matches this
727   /// dominator tree. Otherwise return true.
728   inline bool compare(DominatorTree &Other) const {
729     DomTreeNode *R = getRootNode();
730     DomTreeNode *OtherR = Other.getRootNode();
731
732     if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
733       return true;
734
735     if (DT->compare(Other.getBase()))
736       return true;
737
738     return false;
739   }
740
741   virtual bool runOnFunction(Function &F);
742
743   virtual void verifyAnalysis() const;
744
745   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
746     AU.setPreservesAll();
747   }
748
749   inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
750     return DT->dominates(A, B);
751   }
752
753   inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
754     return DT->dominates(A, B);
755   }
756
757   // dominates - Return true if A dominates B. This performs the
758   // special checks necessary if A and B are in the same basic block.
759   bool dominates(const Instruction *A, const Instruction *B) const;
760
761   bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
762     return DT->properlyDominates(A, B);
763   }
764
765   bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
766     return DT->properlyDominates(A, B);
767   }
768
769   /// findNearestCommonDominator - Find nearest common dominator basic block
770   /// for basic block A and B. If there is no such block then return NULL.
771   inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
772     return DT->findNearestCommonDominator(A, B);
773   }
774
775   inline DomTreeNode *operator[](BasicBlock *BB) const {
776     return DT->getNode(BB);
777   }
778
779   /// getNode - return the (Post)DominatorTree node for the specified basic
780   /// block.  This is the same as using operator[] on this class.
781   ///
782   inline DomTreeNode *getNode(BasicBlock *BB) const {
783     return DT->getNode(BB);
784   }
785
786   /// addNewBlock - Add a new node to the dominator tree information.  This
787   /// creates a new node as a child of DomBB dominator node,linking it into 
788   /// the children list of the immediate dominator.
789   inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
790     return DT->addNewBlock(BB, DomBB);
791   }
792
793   /// changeImmediateDominator - This method is used to update the dominator
794   /// tree information when a node's immediate dominator changes.
795   ///
796   inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
797     DT->changeImmediateDominator(N, NewIDom);
798   }
799
800   inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
801     DT->changeImmediateDominator(N, NewIDom);
802   }
803
804   /// eraseNode - Removes a node from  the dominator tree. Block must not
805   /// domiante any other blocks. Removes node from its immediate dominator's
806   /// children list. Deletes dominator node associated with basic block BB.
807   inline void eraseNode(BasicBlock *BB) {
808     DT->eraseNode(BB);
809   }
810
811   /// splitBlock - BB is split and now it has one successor. Update dominator
812   /// tree to reflect this change.
813   inline void splitBlock(BasicBlock* NewBB) {
814     DT->splitBlock(NewBB);
815   }
816
817   bool isReachableFromEntry(BasicBlock* A) {
818     return DT->isReachableFromEntry(A);
819   }
820
821
822   virtual void releaseMemory() { 
823     DT->releaseMemory();
824   }
825
826   virtual void print(raw_ostream &OS, const Module* M= 0) const;
827 };
828
829 //===-------------------------------------
830 /// DominatorTree GraphTraits specialization so the DominatorTree can be
831 /// iterable by generic graph iterators.
832 ///
833 template <> struct GraphTraits<DomTreeNode*> {
834   typedef DomTreeNode NodeType;
835   typedef NodeType::iterator  ChildIteratorType;
836
837   static NodeType *getEntryNode(NodeType *N) {
838     return N;
839   }
840   static inline ChildIteratorType child_begin(NodeType *N) {
841     return N->begin();
842   }
843   static inline ChildIteratorType child_end(NodeType *N) {
844     return N->end();
845   }
846
847   typedef df_iterator<DomTreeNode*> nodes_iterator;
848
849   static nodes_iterator nodes_begin(DomTreeNode *N) {
850     return df_begin(getEntryNode(N));
851   }
852
853   static nodes_iterator nodes_end(DomTreeNode *N) {
854     return df_end(getEntryNode(N));
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   static nodes_iterator nodes_begin(DominatorTree *N) {
865     return df_begin(getEntryNode(N));
866   }
867
868   static nodes_iterator nodes_end(DominatorTree *N) {
869     return df_end(getEntryNode(N));
870   }
871 };
872
873
874 //===----------------------------------------------------------------------===//
875 /// DominanceFrontierBase - Common base class for computing forward and inverse
876 /// dominance frontiers for a function.
877 ///
878 class DominanceFrontierBase : public FunctionPass {
879 public:
880   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
881   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
882 protected:
883   DomSetMapType Frontiers;
884   std::vector<BasicBlock*> Roots;
885   const bool IsPostDominators;
886
887 public:
888   DominanceFrontierBase(void *ID, bool isPostDom) 
889     : FunctionPass(ID), IsPostDominators(isPostDom) {}
890
891   /// getRoots -  Return the root blocks of the current CFG.  This may include
892   /// multiple blocks if we are computing post dominators.  For forward
893   /// dominators, this will always be a single block (the entry node).
894   ///
895   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
896
897   /// isPostDominator - Returns true if analysis based of postdoms
898   ///
899   bool isPostDominator() const { return IsPostDominators; }
900
901   virtual void releaseMemory() { Frontiers.clear(); }
902
903   // Accessor interface:
904   typedef DomSetMapType::iterator iterator;
905   typedef DomSetMapType::const_iterator const_iterator;
906   iterator       begin()       { return Frontiers.begin(); }
907   const_iterator begin() const { return Frontiers.begin(); }
908   iterator       end()         { return Frontiers.end(); }
909   const_iterator end()   const { return Frontiers.end(); }
910   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
911   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
912
913   iterator addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
914     assert(find(BB) == end() && "Block already in DominanceFrontier!");
915     return Frontiers.insert(std::make_pair(BB, frontier)).first;
916   }
917
918   /// removeBlock - Remove basic block BB's frontier.
919   void removeBlock(BasicBlock *BB) {
920     assert(find(BB) != end() && "Block is not in DominanceFrontier!");
921     for (iterator I = begin(), E = end(); I != E; ++I)
922       I->second.erase(BB);
923     Frontiers.erase(BB);
924   }
925
926   void addToFrontier(iterator I, BasicBlock *Node) {
927     assert(I != end() && "BB is not in DominanceFrontier!");
928     I->second.insert(Node);
929   }
930
931   void removeFromFrontier(iterator I, BasicBlock *Node) {
932     assert(I != end() && "BB is not in DominanceFrontier!");
933     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
934     I->second.erase(Node);
935   }
936
937   /// compareDomSet - Return false if two domsets match. Otherwise
938   /// return true;
939   bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
940     std::set<BasicBlock *> tmpSet;
941     for (DomSetType::const_iterator I = DS2.begin(),
942            E = DS2.end(); I != E; ++I) 
943       tmpSet.insert(*I);
944
945     for (DomSetType::const_iterator I = DS1.begin(),
946            E = DS1.end(); I != E; ) {
947       BasicBlock *Node = *I++;
948
949       if (tmpSet.erase(Node) == 0)
950         // Node is in DS1 but not in DS2.
951         return true;
952     }
953
954     if(!tmpSet.empty())
955       // There are nodes that are in DS2 but not in DS1.
956       return true;
957
958     // DS1 and DS2 matches.
959     return false;
960   }
961
962   /// compare - Return true if the other dominance frontier base matches
963   /// this dominance frontier base. Otherwise return false.
964   bool compare(DominanceFrontierBase &Other) const {
965     DomSetMapType tmpFrontiers;
966     for (DomSetMapType::const_iterator I = Other.begin(),
967            E = Other.end(); I != E; ++I) 
968       tmpFrontiers.insert(std::make_pair(I->first, I->second));
969
970     for (DomSetMapType::iterator I = tmpFrontiers.begin(),
971            E = tmpFrontiers.end(); I != E; ) {
972       BasicBlock *Node = I->first;
973       const_iterator DFI = find(Node);
974       if (DFI == end()) 
975         return true;
976
977       if (compareDomSet(I->second, DFI->second))
978         return true;
979
980       ++I;
981       tmpFrontiers.erase(Node);
982     }
983
984     if (!tmpFrontiers.empty())
985       return true;
986
987     return false;
988   }
989
990   /// print - Convert to human readable form
991   ///
992   virtual void print(raw_ostream &OS, const Module* = 0) const;
993 };
994
995
996 //===-------------------------------------
997 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
998 /// used to compute a forward dominator frontiers.
999 ///
1000 class DominanceFrontier : public DominanceFrontierBase {
1001 public:
1002   static char ID; // Pass ID, replacement for typeid
1003   DominanceFrontier() : 
1004     DominanceFrontierBase(&ID, false) {}
1005
1006   BasicBlock *getRoot() const {
1007     assert(Roots.size() == 1 && "Should always have entry node!");
1008     return Roots[0];
1009   }
1010
1011   virtual bool runOnFunction(Function &) {
1012     Frontiers.clear();
1013     DominatorTree &DT = getAnalysis<DominatorTree>();
1014     Roots = DT.getRoots();
1015     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1016     calculate(DT, DT[Roots[0]]);
1017     return false;
1018   }
1019
1020   virtual void verifyAnalysis() const;
1021
1022   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1023     AU.setPreservesAll();
1024     AU.addRequired<DominatorTree>();
1025   }
1026
1027   /// splitBlock - BB is split and now it has one successor. Update dominance
1028   /// frontier to reflect this change.
1029   void splitBlock(BasicBlock *BB);
1030
1031   /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1032   /// to reflect this change.
1033   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1034                                 DominatorTree *DT) {
1035     // NewBB is now  dominating BB. Which means BB's dominance
1036     // frontier is now part of NewBB's dominance frontier. However, BB
1037     // itself is not member of NewBB's dominance frontier.
1038     DominanceFrontier::iterator NewDFI = find(NewBB);
1039     DominanceFrontier::iterator DFI = find(BB);
1040     // If BB was an entry block then its frontier is empty.
1041     if (DFI == end())
1042       return;
1043     DominanceFrontier::DomSetType BBSet = DFI->second;
1044     for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1045            BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1046       BasicBlock *DFMember = *BBSetI;
1047       // Insert only if NewBB dominates DFMember.
1048       if (!DT->dominates(NewBB, DFMember))
1049         NewDFI->second.insert(DFMember);
1050     }
1051     NewDFI->second.erase(BB);
1052   }
1053
1054   const DomSetType &calculate(const DominatorTree &DT,
1055                               const DomTreeNode *Node);
1056 };
1057
1058
1059 } // End llvm namespace
1060
1061 #endif