Dominators.h revision 9e7919785ee375540a67622fa19f7d10592c3351
1//===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the following classes:
11//  1. DominatorTree: Represent the ImmediateDominator as an explicit tree
12//     structure.
13//  2. ETForest: Efficient data structure for dominance comparisons and
14//     nearest-common-ancestor queries.
15//  3. DominanceFrontier: Calculate and hold the dominance frontier for a
16//     function.
17//
18//  These data structures are listed in increasing order of complexity.  It
19//  takes longer to calculate the dominator frontier, for example, than the
20//  ImmediateDominator mapping.
21//
22//===----------------------------------------------------------------------===//
23
24#ifndef LLVM_ANALYSIS_DOMINATORS_H
25#define LLVM_ANALYSIS_DOMINATORS_H
26
27#include "llvm/Analysis/ET-Forest.h"
28#include "llvm/Pass.h"
29#include <set>
30
31namespace llvm {
32
33class Instruction;
34
35template <typename GraphType> struct GraphTraits;
36
37//===----------------------------------------------------------------------===//
38/// DominatorBase - Base class that other, more interesting dominator analyses
39/// inherit from.
40///
41class DominatorBase : public FunctionPass {
42protected:
43  std::vector<BasicBlock*> Roots;
44  const bool IsPostDominators;
45
46  inline DominatorBase(bool isPostDom) : Roots(), IsPostDominators(isPostDom) {}
47public:
48  /// getRoots -  Return the root blocks of the current CFG.  This may include
49  /// multiple blocks if we are computing post dominators.  For forward
50  /// dominators, this will always be a single block (the entry node).
51  ///
52  inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
53
54  /// isPostDominator - Returns true if analysis based of postdoms
55  ///
56  bool isPostDominator() const { return IsPostDominators; }
57};
58
59//===----------------------------------------------------------------------===//
60/// DominatorTree - Calculate the immediate dominator tree for a function.
61///
62class DominatorTreeBase : public DominatorBase {
63public:
64  class Node;
65protected:
66  std::map<BasicBlock*, Node*> Nodes;
67  void reset();
68  typedef std::map<BasicBlock*, Node*> NodeMapType;
69
70  Node *RootNode;
71
72  struct InfoRec {
73    unsigned Semi;
74    unsigned Size;
75    BasicBlock *Label, *Parent, *Child, *Ancestor;
76
77    std::vector<BasicBlock*> Bucket;
78
79    InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
80  };
81
82  std::map<BasicBlock*, BasicBlock*> IDoms;
83
84  // Vertex - Map the DFS number to the BasicBlock*
85  std::vector<BasicBlock*> Vertex;
86
87  // Info - Collection of information used during the computation of idoms.
88  std::map<BasicBlock*, InfoRec> Info;
89
90public:
91  class Node {
92    friend class DominatorTree;
93    friend struct PostDominatorTree;
94    friend class DominatorTreeBase;
95    BasicBlock *TheBB;
96    Node *IDom;
97    std::vector<Node*> Children;
98  public:
99    typedef std::vector<Node*>::iterator iterator;
100    typedef std::vector<Node*>::const_iterator const_iterator;
101
102    iterator begin()             { return Children.begin(); }
103    iterator end()               { return Children.end(); }
104    const_iterator begin() const { return Children.begin(); }
105    const_iterator end()   const { return Children.end(); }
106
107    inline BasicBlock *getBlock() const { return TheBB; }
108    inline Node *getIDom() const { return IDom; }
109    inline const std::vector<Node*> &getChildren() const { return Children; }
110
111    /// properlyDominates - Returns true iff this dominates N and this != N.
112    /// Note that this is not a constant time operation!
113    ///
114    bool properlyDominates(const Node *N) const {
115      const Node *IDom;
116      if (this == 0 || N == 0) return false;
117      while ((IDom = N->getIDom()) != 0 && IDom != this)
118        N = IDom;   // Walk up the tree
119      return IDom != 0;
120    }
121
122    /// dominates - Returns true iff this dominates N.  Note that this is not a
123    /// constant time operation!
124    ///
125    inline bool dominates(const Node *N) const {
126      if (N == this) return true;  // A node trivially dominates itself.
127      return properlyDominates(N);
128    }
129
130  private:
131    inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
132    inline Node *addChild(Node *C) { Children.push_back(C); return C; }
133
134    void setIDom(Node *NewIDom);
135  };
136
137public:
138  DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
139  ~DominatorTreeBase() { reset(); }
140
141  virtual void releaseMemory() { reset(); }
142
143  /// getNode - return the (Post)DominatorTree node for the specified basic
144  /// block.  This is the same as using operator[] on this class.
145  ///
146  inline Node *getNode(BasicBlock *BB) const {
147    NodeMapType::const_iterator i = Nodes.find(BB);
148    return (i != Nodes.end()) ? i->second : 0;
149  }
150
151  inline Node *operator[](BasicBlock *BB) const {
152    return getNode(BB);
153  }
154
155  /// getRootNode - This returns the entry node for the CFG of the function.  If
156  /// this tree represents the post-dominance relations for a function, however,
157  /// this root may be a node with the block == NULL.  This is the case when
158  /// there are multiple exit nodes from a particular function.  Consumers of
159  /// post-dominance information must be capable of dealing with this
160  /// possibility.
161  ///
162  Node *getRootNode() { return RootNode; }
163  const Node *getRootNode() const { return RootNode; }
164
165  //===--------------------------------------------------------------------===//
166  // API to update (Post)DominatorTree information based on modifications to
167  // the CFG...
168
169  /// createNewNode - Add a new node to the dominator tree information.  This
170  /// creates a new node as a child of IDomNode, linking it into the children
171  /// list of the immediate dominator.
172  ///
173  Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
174    assert(getNode(BB) == 0 && "Block already in dominator tree!");
175    assert(IDomNode && "Not immediate dominator specified for block!");
176    return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
177  }
178
179  /// changeImmediateDominator - This method is used to update the dominator
180  /// tree information when a node's immediate dominator changes.
181  ///
182  void changeImmediateDominator(Node *N, Node *NewIDom) {
183    assert(N && NewIDom && "Cannot change null node pointers!");
184    N->setIDom(NewIDom);
185  }
186
187  /// removeNode - Removes a node from the dominator tree.  Block must not
188  /// dominate any other blocks.  Invalidates any node pointing to removed
189  /// block.
190  void removeNode(BasicBlock *BB) {
191    assert(getNode(BB) && "Removing node that isn't in dominator tree.");
192    Nodes.erase(BB);
193  }
194
195  /// print - Convert to human readable form
196  ///
197  virtual void print(std::ostream &OS, const Module* = 0) const;
198  void print(std::ostream *OS, const Module* M = 0) const {
199    if (OS) print(*OS, M);
200  }
201};
202
203//===-------------------------------------
204/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
205/// compute a normal dominator tree.
206///
207class DominatorTree : public DominatorTreeBase {
208public:
209  DominatorTree() : DominatorTreeBase(false) {}
210
211  BasicBlock *getRoot() const {
212    assert(Roots.size() == 1 && "Should always have entry node!");
213    return Roots[0];
214  }
215
216  virtual bool runOnFunction(Function &F);
217
218  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
219    AU.setPreservesAll();
220  }
221private:
222  void calculate(Function& F);
223  Node *getNodeForBlock(BasicBlock *BB);
224  unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
225  void Compress(BasicBlock *V, InfoRec &VInfo);
226  BasicBlock *Eval(BasicBlock *v);
227  void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
228  inline BasicBlock *getIDom(BasicBlock *BB) const {
229      std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
230      return I != IDoms.end() ? I->second : 0;
231    }
232};
233
234//===-------------------------------------
235/// DominatorTree GraphTraits specialization so the DominatorTree can be
236/// iterable by generic graph iterators.
237///
238template <> struct GraphTraits<DominatorTree::Node*> {
239  typedef DominatorTree::Node NodeType;
240  typedef NodeType::iterator  ChildIteratorType;
241
242  static NodeType *getEntryNode(NodeType *N) {
243    return N;
244  }
245  static inline ChildIteratorType child_begin(NodeType* N) {
246    return N->begin();
247  }
248  static inline ChildIteratorType child_end(NodeType* N) {
249    return N->end();
250  }
251};
252
253template <> struct GraphTraits<DominatorTree*>
254  : public GraphTraits<DominatorTree::Node*> {
255  static NodeType *getEntryNode(DominatorTree *DT) {
256    return DT->getRootNode();
257  }
258};
259
260
261//===-------------------------------------
262/// ET-Forest Class - Class used to construct forwards and backwards
263/// ET-Forests
264///
265class ETForestBase : public DominatorBase {
266public:
267  ETForestBase(bool isPostDom) : DominatorBase(isPostDom), Nodes(),
268                                 DFSInfoValid(false), SlowQueries(0) {}
269
270  virtual void releaseMemory() { reset(); }
271
272  typedef std::map<BasicBlock*, ETNode*> ETMapType;
273
274  void updateDFSNumbers();
275
276  /// dominates - Return true if A dominates B.
277  ///
278  inline bool dominates(BasicBlock *A, BasicBlock *B) {
279    if (A == B)
280      return true;
281
282    ETNode *NodeA = getNode(A);
283    ETNode *NodeB = getNode(B);
284
285    if (DFSInfoValid)
286      return NodeB->DominatedBy(NodeA);
287    else {
288      // If we end up with too many slow queries, just update the
289      // DFS numbers on the theory that we are going to keep querying.
290      SlowQueries++;
291      if (SlowQueries > 32) {
292        updateDFSNumbers();
293        return NodeB->DominatedBy(NodeA);
294      }
295      return NodeB->DominatedBySlow(NodeA);
296    }
297  }
298
299  // dominates - Return true if A dominates B. This performs the
300  // special checks necessary if A and B are in the same basic block.
301  bool dominates(Instruction *A, Instruction *B);
302
303  /// properlyDominates - Return true if A dominates B and A != B.
304  ///
305  bool properlyDominates(BasicBlock *A, BasicBlock *B) {
306    return dominates(A, B) && A != B;
307  }
308
309  /// isReachableFromEntry - Return true if A is dominated by the entry
310  /// block of the function containing it.
311  const bool isReachableFromEntry(BasicBlock* A);
312
313  /// Return the nearest common dominator of A and B.
314  BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const  {
315    ETNode *NodeA = getNode(A);
316    ETNode *NodeB = getNode(B);
317
318    ETNode *Common = NodeA->NCA(NodeB);
319    if (!Common)
320      return NULL;
321    return Common->getData<BasicBlock>();
322  }
323
324  /// Return the immediate dominator of A.
325  BasicBlock *getIDom(BasicBlock *A) {
326    ETNode *NodeA = getNode(A);
327    const ETNode *idom = NodeA->getFather();
328    return idom ? idom->getData<BasicBlock>() : 0;
329  }
330
331  void getChildren(BasicBlock *A, std::vector<BasicBlock*>& children) {
332    ETNode *NodeA = getNode(A);
333    const ETNode* son = NodeA->getSon();
334
335    if (!son) return;
336    children.push_back(son->getData<BasicBlock>());
337
338    const ETNode* brother = son->getBrother();
339    while (brother != son) {
340      children.push_back(brother->getData<BasicBlock>());
341      brother = brother->getBrother();
342    }
343  }
344
345  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
346    AU.setPreservesAll();
347    AU.addRequired<DominatorTree>();
348  }
349  //===--------------------------------------------------------------------===//
350  // API to update Forest information based on modifications
351  // to the CFG...
352
353  /// addNewBlock - Add a new block to the CFG, with the specified immediate
354  /// dominator.
355  ///
356  void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
357
358  /// setImmediateDominator - Update the immediate dominator information to
359  /// change the current immediate dominator for the specified block
360  /// to another block.  This method requires that BB for NewIDom
361  /// already have an ETNode, otherwise just use addNewBlock.
362  ///
363  void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
364  /// print - Convert to human readable form
365  ///
366  virtual void print(std::ostream &OS, const Module* = 0) const;
367  void print(std::ostream *OS, const Module* M = 0) const {
368    if (OS) print(*OS, M);
369  }
370protected:
371  /// getNode - return the (Post)DominatorTree node for the specified basic
372  /// block.  This is the same as using operator[] on this class.
373  ///
374  inline ETNode *getNode(BasicBlock *BB) const {
375    ETMapType::const_iterator i = Nodes.find(BB);
376    return (i != Nodes.end()) ? i->second : 0;
377  }
378
379  inline ETNode *operator[](BasicBlock *BB) const {
380    return getNode(BB);
381  }
382
383  void reset();
384  ETMapType Nodes;
385  bool DFSInfoValid;
386  unsigned int SlowQueries;
387
388};
389
390//==-------------------------------------
391/// ETForest Class - Concrete subclass of ETForestBase that is used to
392/// compute a forwards ET-Forest.
393
394class ETForest : public ETForestBase {
395public:
396  ETForest() : ETForestBase(false) {}
397
398  BasicBlock *getRoot() const {
399    assert(Roots.size() == 1 && "Should always have entry node!");
400    return Roots[0];
401  }
402
403  virtual bool runOnFunction(Function &F) {
404    reset();     // Reset from the last time we were run...
405    DominatorTree &DT = getAnalysis<DominatorTree>();
406    Roots = DT.getRoots();
407    calculate(DT);
408    return false;
409  }
410
411  void calculate(const DominatorTree &DT);
412  ETNode *getNodeForBlock(BasicBlock *BB);
413};
414
415//===----------------------------------------------------------------------===//
416/// DominanceFrontierBase - Common base class for computing forward and inverse
417/// dominance frontiers for a function.
418///
419class DominanceFrontierBase : public DominatorBase {
420public:
421  typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
422  typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
423protected:
424  DomSetMapType Frontiers;
425public:
426  DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
427
428  virtual void releaseMemory() { Frontiers.clear(); }
429
430  // Accessor interface:
431  typedef DomSetMapType::iterator iterator;
432  typedef DomSetMapType::const_iterator const_iterator;
433  iterator       begin()       { return Frontiers.begin(); }
434  const_iterator begin() const { return Frontiers.begin(); }
435  iterator       end()         { return Frontiers.end(); }
436  const_iterator end()   const { return Frontiers.end(); }
437  iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
438  const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
439
440  void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
441    assert(find(BB) == end() && "Block already in DominanceFrontier!");
442    Frontiers.insert(std::make_pair(BB, frontier));
443  }
444
445  void addToFrontier(iterator I, BasicBlock *Node) {
446    assert(I != end() && "BB is not in DominanceFrontier!");
447    I->second.insert(Node);
448  }
449
450  void removeFromFrontier(iterator I, BasicBlock *Node) {
451    assert(I != end() && "BB is not in DominanceFrontier!");
452    assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
453    I->second.erase(Node);
454  }
455
456  /// print - Convert to human readable form
457  ///
458  virtual void print(std::ostream &OS, const Module* = 0) const;
459  void print(std::ostream *OS, const Module* M = 0) const {
460    if (OS) print(*OS, M);
461  }
462};
463
464
465//===-------------------------------------
466/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
467/// used to compute a forward dominator frontiers.
468///
469class DominanceFrontier : public DominanceFrontierBase {
470public:
471  DominanceFrontier() : DominanceFrontierBase(false) {}
472
473  BasicBlock *getRoot() const {
474    assert(Roots.size() == 1 && "Should always have entry node!");
475    return Roots[0];
476  }
477
478  virtual bool runOnFunction(Function &) {
479    Frontiers.clear();
480    DominatorTree &DT = getAnalysis<DominatorTree>();
481    Roots = DT.getRoots();
482    assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
483    calculate(DT, DT[Roots[0]]);
484    return false;
485  }
486
487  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
488    AU.setPreservesAll();
489    AU.addRequired<DominatorTree>();
490  }
491private:
492  const DomSetType &calculate(const DominatorTree &DT,
493                              const DominatorTree::Node *Node);
494};
495
496
497} // End llvm namespace
498
499#endif
500