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