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