Dominators.h revision 0e7f728ad1ac25b0ed450fe0f8b86a38d3c2a93a
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 dominators as an explicit tree structure.
12//  2. ETForest: Efficient data structure for dominance comparisons and
13//     nearest-common-ancestor queries.
14//  3. DominanceFrontier: Calculate and hold the dominance frontier for a
15//     function.
16//
17//  These data structures are listed in increasing order of complexity.  It
18//  takes longer to calculate the dominator frontier, for example, than the
19//  DominatorTree mapping.
20//
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_ANALYSIS_DOMINATORS_H
24#define LLVM_ANALYSIS_DOMINATORS_H
25
26#include "llvm/Analysis/ET-Forest.h"
27#include "llvm/Pass.h"
28#include <set>
29
30namespace llvm {
31
32class Instruction;
33
34template <typename GraphType> struct GraphTraits;
35
36//===----------------------------------------------------------------------===//
37/// DominatorBase - Base class that other, more interesting dominator analyses
38/// inherit from.
39///
40class DominatorBase : public FunctionPass {
41protected:
42  std::vector<BasicBlock*> Roots;
43  const bool IsPostDominators;
44  inline DominatorBase(intptr_t ID, bool isPostDom) :
45    FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
46public:
47
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//===----------------------------------------------------------------------===//
61// DomTreeNode - Dominator Tree Node
62class DominatorTreeBase;
63class PostDominatorTree;
64class DomTreeNode {
65  BasicBlock *TheBB;
66  DomTreeNode *IDom;
67  std::vector<DomTreeNode*> Children;
68  int DFSNumIn, DFSNumOut;
69
70  friend class DominatorTreeBase;
71  friend class PostDominatorTree;
72public:
73  typedef std::vector<DomTreeNode*>::iterator iterator;
74  typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
75
76  iterator begin()             { return Children.begin(); }
77  iterator end()               { return Children.end(); }
78  const_iterator begin() const { return Children.begin(); }
79  const_iterator end()   const { return Children.end(); }
80
81  inline BasicBlock *getBlock() const { return TheBB; }
82  inline DomTreeNode *getIDom() const { return IDom; }
83  inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
84
85  inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
86    : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
87  inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
88  void setIDom(DomTreeNode *NewIDom);
89
90private:
91  // Return true if this node is dominated by other. Use this only if DFS info is valid.
92  bool DominatedBy(const DomTreeNode *other) const {
93    return this->DFSNumIn >= other->DFSNumIn &&
94      this->DFSNumOut <= other->DFSNumOut;
95  }
96
97  /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
98  /// in dfs order.
99  void assignDFSNumber(int num);
100};
101
102//===----------------------------------------------------------------------===//
103/// DominatorTree - Calculate the immediate dominator tree for a function.
104///
105class DominatorTreeBase : public DominatorBase {
106
107protected:
108  void reset();
109  typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
110  DomTreeNodeMapType DomTreeNodes;
111  DomTreeNode *RootNode;
112
113  bool DFSInfoValid;
114  unsigned int SlowQueries;
115  // Information record used during immediate dominators computation.
116  struct InfoRec {
117    unsigned Semi;
118    unsigned Size;
119    BasicBlock *Label, *Parent, *Child, *Ancestor;
120
121    std::vector<BasicBlock*> Bucket;
122
123    InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
124  };
125
126  std::map<BasicBlock*, BasicBlock*> IDoms;
127
128  // Vertex - Map the DFS number to the BasicBlock*
129  std::vector<BasicBlock*> Vertex;
130
131  // Info - Collection of information used during the computation of idoms.
132  std::map<BasicBlock*, InfoRec> Info;
133
134  void updateDFSNumbers();
135
136  public:
137  DominatorTreeBase(intptr_t ID, bool isPostDom)
138    : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
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 DomTreeNode *getNode(BasicBlock *BB) const {
147    DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
148    return (i != DomTreeNodes.end()) ? i->second : 0;
149  }
150
151  inline DomTreeNode *operator[](BasicBlock *BB) const {
152    return getNode(BB);
153  }
154
155  /// getIDomBlock - return basic block BB's immediate dominator basic block.
156  ///
157  BasicBlock *getIDomBlock(BasicBlock *BB) {
158    DomTreeNode *N = getNode(BB);
159    assert (N && "Missing dominator tree node");
160    DomTreeNode *I = N->getIDom();
161    assert (N && "Missing immediate dominator");
162    return I->getBlock();
163  }
164
165  /// getRootNode - This returns the entry node for the CFG of the function.  If
166  /// this tree represents the post-dominance relations for a function, however,
167  /// this root may be a node with the block == NULL.  This is the case when
168  /// there are multiple exit nodes from a particular function.  Consumers of
169  /// post-dominance information must be capable of dealing with this
170  /// possibility.
171  ///
172  DomTreeNode *getRootNode() { return RootNode; }
173  const DomTreeNode *getRootNode() const { return RootNode; }
174
175  /// properlyDominates - Returns true iff this dominates N and this != N.
176  /// Note that this is not a constant time operation!
177  ///
178  bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
179    if (A == 0 || B == 0) return false;
180    return dominatedBySlowTreeWalk(A, B);
181  }
182
183  inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
184    return properlyDominates(getNode(A), getNode(B));
185  }
186
187  bool dominatedBySlowTreeWalk(const DomTreeNode *A,
188                               const DomTreeNode *B) const {
189    const DomTreeNode *IDom;
190    if (A == 0 || B == 0) return false;
191    while ((IDom = B->getIDom()) != 0 && IDom != A)
192      B = IDom;   // Walk up the tree
193    return IDom != 0;
194  }
195
196
197  /// isReachableFromEntry - Return true if A is dominated by the entry
198  /// block of the function containing it.
199  const bool isReachableFromEntry(BasicBlock* A);
200
201  /// dominates - Returns true iff A dominates B.  Note that this is not a
202  /// constant time operation!
203  ///
204  inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
205    if (B == A)
206      return true;  // A node trivially dominates itself.
207
208    if (A == 0 || B == 0)
209      return false;
210
211    if (DFSInfoValid)
212      return B->DominatedBy(A);
213
214    // If we end up with too many slow queries, just update the
215    // DFS numbers on the theory that we are going to keep querying.
216    SlowQueries++;
217    if (SlowQueries > 32) {
218      updateDFSNumbers();
219      return B->DominatedBy(A);
220    }
221
222    return dominatedBySlowTreeWalk(A, B);
223  }
224
225  inline bool dominates(BasicBlock *A, BasicBlock *B) {
226    if (A == B)
227      return true;
228
229    return dominates(getNode(A), getNode(B));
230  }
231
232  /// findNearestCommonDominator - Find nearest common dominator basic block
233  /// for basic block A and B. If there is no such block then return NULL.
234  BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
235
236  // dominates - Return true if A dominates B. This performs the
237  // special checks necessary if A and B are in the same basic block.
238  bool dominates(Instruction *A, Instruction *B);
239
240  //===--------------------------------------------------------------------===//
241  // API to update (Post)DominatorTree information based on modifications to
242  // the CFG...
243
244  /// addNewBlock - Add a new node to the dominator tree information.  This
245  /// creates a new node as a child of DomBB dominator node,linking it into
246  /// the children list of the immediate dominator.
247  DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
248    assert(getNode(BB) == 0 && "Block already in dominator tree!");
249    DomTreeNode *IDomNode = getNode(DomBB);
250    assert(IDomNode && "Not immediate dominator specified for block!");
251    DFSInfoValid = false;
252    return DomTreeNodes[BB] =
253      IDomNode->addChild(new DomTreeNode(BB, IDomNode));
254  }
255
256  /// changeImmediateDominator - This method is used to update the dominator
257  /// tree information when a node's immediate dominator changes.
258  ///
259  void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
260    assert(N && NewIDom && "Cannot change null node pointers!");
261    DFSInfoValid = false;
262    N->setIDom(NewIDom);
263  }
264
265  void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
266    changeImmediateDominator(getNode(BB), getNode(NewBB));
267  }
268
269  /// removeNode - Removes a node from the dominator tree.  Block must not
270  /// dominate any other blocks.  Invalidates any node pointing to removed
271  /// block.
272  void removeNode(BasicBlock *BB) {
273    assert(getNode(BB) && "Removing node that isn't in dominator tree.");
274    DomTreeNodes.erase(BB);
275  }
276
277  /// print - Convert to human readable form
278  ///
279  virtual void print(std::ostream &OS, const Module* = 0) const;
280  void print(std::ostream *OS, const Module* M = 0) const {
281    if (OS) print(*OS, M);
282  }
283  virtual void dump();
284};
285
286//===-------------------------------------
287/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
288/// compute a normal dominator tree.
289///
290class DominatorTree : public DominatorTreeBase {
291public:
292  static char ID; // Pass ID, replacement for typeid
293  DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
294
295  BasicBlock *getRoot() const {
296    assert(Roots.size() == 1 && "Should always have entry node!");
297    return Roots[0];
298  }
299
300  virtual bool runOnFunction(Function &F);
301
302  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
303    AU.setPreservesAll();
304  }
305
306  /// splitBlock
307  /// BB is split and now it has one successor. Update dominator tree to
308  /// reflect this change.
309  void splitBlock(BasicBlock *BB);
310private:
311  void calculate(Function& F);
312  DomTreeNode *getNodeForBlock(BasicBlock *BB);
313  unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
314  void Compress(BasicBlock *V);
315  BasicBlock *Eval(BasicBlock *v);
316  void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
317  inline BasicBlock *getIDom(BasicBlock *BB) const {
318      std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
319      return I != IDoms.end() ? I->second : 0;
320    }
321};
322
323//===-------------------------------------
324/// DominatorTree GraphTraits specialization so the DominatorTree can be
325/// iterable by generic graph iterators.
326///
327template <> struct GraphTraits<DomTreeNode*> {
328  typedef DomTreeNode NodeType;
329  typedef NodeType::iterator  ChildIteratorType;
330
331  static NodeType *getEntryNode(NodeType *N) {
332    return N;
333  }
334  static inline ChildIteratorType child_begin(NodeType* N) {
335    return N->begin();
336  }
337  static inline ChildIteratorType child_end(NodeType* N) {
338    return N->end();
339  }
340};
341
342template <> struct GraphTraits<DominatorTree*>
343  : public GraphTraits<DomTreeNode*> {
344  static NodeType *getEntryNode(DominatorTree *DT) {
345    return DT->getRootNode();
346  }
347};
348
349
350//===-------------------------------------
351/// ET-Forest Class - Class used to construct forwards and backwards
352/// ET-Forests
353///
354class ETForestBase : public DominatorBase {
355public:
356  ETForestBase(intptr_t ID, bool isPostDom)
357    : DominatorBase(ID, isPostDom), Nodes(),
358      DFSInfoValid(false), SlowQueries(0) {}
359
360  virtual void releaseMemory() { reset(); }
361
362  typedef std::map<BasicBlock*, ETNode*> ETMapType;
363
364  // FIXME : There is no need to make this interface public.
365  // Fix predicate simplifier.
366  void updateDFSNumbers();
367
368  /// dominates - Return true if A dominates B.
369  ///
370  inline bool dominates(BasicBlock *A, BasicBlock *B) {
371    if (A == B)
372      return true;
373
374    ETNode *NodeA = getNode(A);
375    ETNode *NodeB = getNode(B);
376
377    if (DFSInfoValid)
378      return NodeB->DominatedBy(NodeA);
379    else {
380      // If we end up with too many slow queries, just update the
381      // DFS numbers on the theory that we are going to keep querying.
382      SlowQueries++;
383      if (SlowQueries > 32) {
384        updateDFSNumbers();
385        return NodeB->DominatedBy(NodeA);
386      }
387      return NodeB->DominatedBySlow(NodeA);
388    }
389  }
390
391  // dominates - Return true if A dominates B. This performs the
392  // special checks necessary if A and B are in the same basic block.
393  bool dominates(Instruction *A, Instruction *B);
394
395  /// properlyDominates - Return true if A dominates B and A != B.
396  ///
397  bool properlyDominates(BasicBlock *A, BasicBlock *B) {
398    return dominates(A, B) && A != B;
399  }
400
401  /// isReachableFromEntry - Return true if A is dominated by the entry
402  /// block of the function containing it.
403  const bool isReachableFromEntry(BasicBlock* A);
404
405  /// Return the nearest common dominator of A and B.
406  BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const  {
407    ETNode *NodeA = getNode(A);
408    ETNode *NodeB = getNode(B);
409
410    ETNode *Common = NodeA->NCA(NodeB);
411    if (!Common)
412      return NULL;
413    return Common->getData<BasicBlock>();
414  }
415
416  /// Return the immediate dominator of A.
417  BasicBlock *getIDom(BasicBlock *A) const {
418    ETNode *NodeA = getNode(A);
419    if (!NodeA) return 0;
420    const ETNode *idom = NodeA->getFather();
421    return idom ? idom->getData<BasicBlock>() : 0;
422  }
423
424  void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
425    ETNode *NodeA = getNode(A);
426    if (!NodeA) return;
427    const ETNode* son = NodeA->getSon();
428
429    if (!son) return;
430    children.push_back(son->getData<BasicBlock>());
431
432    const ETNode* brother = son->getBrother();
433    while (brother != son) {
434      children.push_back(brother->getData<BasicBlock>());
435      brother = brother->getBrother();
436    }
437  }
438
439  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
440    AU.setPreservesAll();
441    AU.addRequired<DominatorTree>();
442  }
443  //===--------------------------------------------------------------------===//
444  // API to update Forest information based on modifications
445  // to the CFG...
446
447  /// addNewBlock - Add a new block to the CFG, with the specified immediate
448  /// dominator.
449  ///
450  void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
451
452  /// setImmediateDominator - Update the immediate dominator information to
453  /// change the current immediate dominator for the specified block
454  /// to another block.  This method requires that BB for NewIDom
455  /// already have an ETNode, otherwise just use addNewBlock.
456  ///
457  void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
458  /// print - Convert to human readable form
459  ///
460  virtual void print(std::ostream &OS, const Module* = 0) const;
461  void print(std::ostream *OS, const Module* M = 0) const {
462    if (OS) print(*OS, M);
463  }
464  virtual void dump();
465protected:
466  /// getNode - return the (Post)DominatorTree node for the specified basic
467  /// block.  This is the same as using operator[] on this class.
468  ///
469  inline ETNode *getNode(BasicBlock *BB) const {
470    ETMapType::const_iterator i = Nodes.find(BB);
471    return (i != Nodes.end()) ? i->second : 0;
472  }
473
474  inline ETNode *operator[](BasicBlock *BB) const {
475    return getNode(BB);
476  }
477
478  void reset();
479  ETMapType Nodes;
480  bool DFSInfoValid;
481  unsigned int SlowQueries;
482
483};
484
485//==-------------------------------------
486/// ETForest Class - Concrete subclass of ETForestBase that is used to
487/// compute a forwards ET-Forest.
488
489class ETForest : public ETForestBase {
490public:
491  static char ID; // Pass identification, replacement for typeid
492
493  ETForest() : ETForestBase((intptr_t)&ID, false) {}
494
495  BasicBlock *getRoot() const {
496    assert(Roots.size() == 1 && "Should always have entry node!");
497    return Roots[0];
498  }
499
500  virtual bool runOnFunction(Function &F) {
501    reset();     // Reset from the last time we were run...
502    DominatorTree &DT = getAnalysis<DominatorTree>();
503    Roots = DT.getRoots();
504    calculate(DT);
505    return false;
506  }
507
508  void calculate(const DominatorTree &DT);
509  // FIXME : There is no need to make getNodeForBlock public. Fix
510  // predicate simplifier.
511  ETNode *getNodeForBlock(BasicBlock *BB);
512};
513
514//===----------------------------------------------------------------------===//
515/// DominanceFrontierBase - Common base class for computing forward and inverse
516/// dominance frontiers for a function.
517///
518class DominanceFrontierBase : public DominatorBase {
519public:
520  typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
521  typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
522protected:
523  DomSetMapType Frontiers;
524public:
525  DominanceFrontierBase(intptr_t ID, bool isPostDom)
526    : DominatorBase(ID, isPostDom) {}
527
528  virtual void releaseMemory() { Frontiers.clear(); }
529
530  // Accessor interface:
531  typedef DomSetMapType::iterator iterator;
532  typedef DomSetMapType::const_iterator const_iterator;
533  iterator       begin()       { return Frontiers.begin(); }
534  const_iterator begin() const { return Frontiers.begin(); }
535  iterator       end()         { return Frontiers.end(); }
536  const_iterator end()   const { return Frontiers.end(); }
537  iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
538  const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
539
540  void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
541    assert(find(BB) == end() && "Block already in DominanceFrontier!");
542    Frontiers.insert(std::make_pair(BB, frontier));
543  }
544
545  void addToFrontier(iterator I, BasicBlock *Node) {
546    assert(I != end() && "BB is not in DominanceFrontier!");
547    I->second.insert(Node);
548  }
549
550  void removeFromFrontier(iterator I, BasicBlock *Node) {
551    assert(I != end() && "BB is not in DominanceFrontier!");
552    assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
553    I->second.erase(Node);
554  }
555
556  /// print - Convert to human readable form
557  ///
558  virtual void print(std::ostream &OS, const Module* = 0) const;
559  void print(std::ostream *OS, const Module* M = 0) const {
560    if (OS) print(*OS, M);
561  }
562  virtual void dump();
563};
564
565
566//===-------------------------------------
567/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
568/// used to compute a forward dominator frontiers.
569///
570class DominanceFrontier : public DominanceFrontierBase {
571public:
572  static char ID; // Pass ID, replacement for typeid
573  DominanceFrontier() :
574    DominanceFrontierBase((intptr_t)& ID, false) {}
575
576  BasicBlock *getRoot() const {
577    assert(Roots.size() == 1 && "Should always have entry node!");
578    return Roots[0];
579  }
580
581  virtual bool runOnFunction(Function &) {
582    Frontiers.clear();
583    DominatorTree &DT = getAnalysis<DominatorTree>();
584    Roots = DT.getRoots();
585    assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
586    calculate(DT, DT[Roots[0]]);
587    return false;
588  }
589
590  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
591    AU.setPreservesAll();
592    AU.addRequired<DominatorTree>();
593  }
594
595  /// splitBlock
596  /// BB is split and now it has one successor. Update dominace frontier to
597  /// reflect this change.
598  void splitBlock(BasicBlock *BB);
599
600private:
601  const DomSetType &calculate(const DominatorTree &DT,
602                              const DomTreeNode *Node);
603};
604
605
606} // End llvm namespace
607
608#endif
609