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