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