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