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