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