LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Dominators.h
Go to the documentation of this file.
1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the DominatorTree class, which provides fast and efficient
11 // dominance queries.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_ANALYSIS_DOMINATORS_H
16 #define LLVM_ANALYSIS_DOMINATORS_H
17 
18 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/GraphTraits.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/Compiler.h"
28 #include <algorithm>
29 
30 namespace llvm {
31 
32 //===----------------------------------------------------------------------===//
33 /// DominatorBase - Base class that other, more interesting dominator analyses
34 /// inherit from.
35 ///
36 template <class NodeT>
38 protected:
39  std::vector<NodeT*> Roots;
40  const bool IsPostDominators;
41  inline explicit DominatorBase(bool isPostDom) :
42  Roots(), IsPostDominators(isPostDom) {}
43 public:
44 
45  /// getRoots - Return the root blocks of the current CFG. This may include
46  /// multiple blocks if we are computing post dominators. For forward
47  /// dominators, this will always be a single block (the entry node).
48  ///
49  inline const std::vector<NodeT*> &getRoots() const { return Roots; }
50 
51  /// isPostDominator - Returns true if analysis based of postdoms
52  ///
53  bool isPostDominator() const { return IsPostDominators; }
54 };
55 
56 
57 //===----------------------------------------------------------------------===//
58 // DomTreeNode - Dominator Tree Node
59 template<class NodeT> class DominatorTreeBase;
60 struct PostDominatorTree;
61 class MachineBasicBlock;
62 
63 template <class NodeT>
65  NodeT *TheBB;
67  std::vector<DomTreeNodeBase<NodeT> *> Children;
68  int DFSNumIn, DFSNumOut;
69 
70  template<class N> friend class DominatorTreeBase;
71  friend struct PostDominatorTree;
72 public:
73  typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
74  typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
76 
77  iterator begin() { return Children.begin(); }
78  iterator end() { return Children.end(); }
79  const_iterator begin() const { return Children.begin(); }
80  const_iterator end() const { return Children.end(); }
81 
82  NodeT *getBlock() const { return TheBB; }
83  DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
84  const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
85  return Children;
86  }
87 
89  : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
90 
92  Children.push_back(C);
93  return C;
94  }
95 
96  size_t getNumChildren() const {
97  return Children.size();
98  }
99 
101  Children.clear();
102  }
103 
104  bool compare(const DomTreeNodeBase<NodeT> *Other) const {
105  if (getNumChildren() != Other->getNumChildren())
106  return true;
107 
108  SmallPtrSet<const NodeT *, 4> OtherChildren;
109  for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
110  const NodeT *Nd = (*I)->getBlock();
111  OtherChildren.insert(Nd);
112  }
113 
114  for (const_iterator I = begin(), E = end(); I != E; ++I) {
115  const NodeT *N = (*I)->getBlock();
116  if (OtherChildren.count(N) == 0)
117  return true;
118  }
119  return false;
120  }
121 
123  assert(IDom && "No immediate dominator?");
124  if (IDom != NewIDom) {
125  typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
126  std::find(IDom->Children.begin(), IDom->Children.end(), this);
127  assert(I != IDom->Children.end() &&
128  "Not in immediate dominator children set!");
129  // I am no longer your child...
130  IDom->Children.erase(I);
131 
132  // Switch to new dominator
133  IDom = NewIDom;
134  IDom->Children.push_back(this);
135  }
136  }
137 
138  /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
139  /// not call them.
140  unsigned getDFSNumIn() const { return DFSNumIn; }
141  unsigned getDFSNumOut() const { return DFSNumOut; }
142 private:
143  // Return true if this node is dominated by other. Use this only if DFS info
144  // is valid.
145  bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
146  return this->DFSNumIn >= other->DFSNumIn &&
147  this->DFSNumOut <= other->DFSNumOut;
148  }
149 };
150 
151 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
152 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
153 
154 template<class NodeT>
156  const DomTreeNodeBase<NodeT> *Node) {
157  if (Node->getBlock())
158  WriteAsOperand(o, Node->getBlock(), false);
159  else
160  o << " <<exit node>>";
161 
162  o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
163 
164  return o << "\n";
165 }
166 
167 template<class NodeT>
169  unsigned Lev) {
170  o.indent(2*Lev) << "[" << Lev << "] " << N;
171  for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
172  E = N->end(); I != E; ++I)
173  PrintDomTree<NodeT>(*I, o, Lev+1);
174 }
175 
177 
178 //===----------------------------------------------------------------------===//
179 /// DominatorTree - Calculate the immediate dominator tree for a function.
180 ///
181 
182 template<class FuncT, class N>
184  FuncT& F);
185 
186 template<class NodeT>
187 class DominatorTreeBase : public DominatorBase<NodeT> {
188  bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
189  const DomTreeNodeBase<NodeT> *B) const {
190  assert(A != B);
191  assert(isReachableFromEntry(B));
192  assert(isReachableFromEntry(A));
193 
194  const DomTreeNodeBase<NodeT> *IDom;
195  while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
196  B = IDom; // Walk up the tree
197  return IDom != 0;
198  }
199 
200 protected:
204 
206  unsigned int SlowQueries;
207  // Information record used during immediate dominators computation.
208  struct InfoRec {
209  unsigned DFSNum;
210  unsigned Parent;
211  unsigned Semi;
212  NodeT *Label;
213 
214  InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(0) {}
215  };
216 
218 
219  // Vertex - Map the DFS number to the BasicBlock*
220  std::vector<NodeT*> Vertex;
221 
222  // Info - Collection of information used during the computation of idoms.
224 
225  void reset() {
226  for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
227  E = DomTreeNodes.end(); I != E; ++I)
228  delete I->second;
230  IDoms.clear();
231  this->Roots.clear();
232  Vertex.clear();
233  RootNode = 0;
234  }
235 
236  // NewBB is split and now it has one successor. Update dominator tree to
237  // reflect this change.
238  template<class N, class GraphT>
240  typename GraphT::NodeType* NewBB) {
241  assert(std::distance(GraphT::child_begin(NewBB),
242  GraphT::child_end(NewBB)) == 1 &&
243  "NewBB should have a single successor!");
244  typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
245 
246  std::vector<typename GraphT::NodeType*> PredBlocks;
247  typedef GraphTraits<Inverse<N> > InvTraits;
248  for (typename InvTraits::ChildIteratorType PI =
249  InvTraits::child_begin(NewBB),
250  PE = InvTraits::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 InvTraits::ChildIteratorType PI =
257  InvTraits::child_begin(NewBBSucc),
258  E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
259  typename InvTraits::NodeType *ND = *PI;
260  if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
261  DT.isReachableFromEntry(ND)) {
262  NewBBDominatesNewBBSucc = false;
263  break;
264  }
265  }
266 
267  // Find NewBB's immediate dominator and create new dominator tree node for
268  // NewBB.
269  NodeT *NewBBIDom = 0;
270  unsigned i = 0;
271  for (i = 0; i < PredBlocks.size(); ++i)
272  if (DT.isReachableFromEntry(PredBlocks[i])) {
273  NewBBIDom = PredBlocks[i];
274  break;
275  }
276 
277  // It's possible that none of the predecessors of NewBB are reachable;
278  // in that case, NewBB itself is unreachable, so nothing needs to be
279  // changed.
280  if (!NewBBIDom)
281  return;
282 
283  for (i = i + 1; i < PredBlocks.size(); ++i) {
284  if (DT.isReachableFromEntry(PredBlocks[i]))
285  NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
286  }
287 
288  // Create the new dominator tree node... and set the idom of NewBB.
289  DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
290 
291  // If NewBB strictly dominates other blocks, then it is now the immediate
292  // dominator of NewBBSucc. Update the dominator tree as appropriate.
293  if (NewBBDominatesNewBBSucc) {
294  DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
295  DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
296  }
297  }
298 
299 public:
300  explicit DominatorTreeBase(bool isPostDom)
301  : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
302  virtual ~DominatorTreeBase() { reset(); }
303 
304  /// compare - Return false if the other dominator tree base matches this
305  /// dominator tree base. Otherwise return true.
306  bool compare(DominatorTreeBase &Other) const {
307 
308  const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
309  if (DomTreeNodes.size() != OtherDomTreeNodes.size())
310  return true;
311 
313  I = this->DomTreeNodes.begin(),
314  E = this->DomTreeNodes.end(); I != E; ++I) {
315  NodeT *BB = I->first;
316  typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
317  if (OI == OtherDomTreeNodes.end())
318  return true;
319 
320  DomTreeNodeBase<NodeT>* MyNd = I->second;
321  DomTreeNodeBase<NodeT>* OtherNd = OI->second;
322 
323  if (MyNd->compare(OtherNd))
324  return true;
325  }
326 
327  return false;
328  }
329 
330  virtual void releaseMemory() { reset(); }
331 
332  /// getNode - return the (Post)DominatorTree node for the specified basic
333  /// block. This is the same as using operator[] on this class.
334  ///
335  inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
336  return DomTreeNodes.lookup(BB);
337  }
338 
339  /// getRootNode - This returns the entry node for the CFG of the function. If
340  /// this tree represents the post-dominance relations for a function, however,
341  /// this root may be a node with the block == NULL. This is the case when
342  /// there are multiple exit nodes from a particular function. Consumers of
343  /// post-dominance information must be capable of dealing with this
344  /// possibility.
345  ///
347  const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
348 
349  /// Get all nodes dominated by R, including R itself. Return true on success.
350  void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
351  const DomTreeNodeBase<NodeT> *RN = getNode(R);
353  WL.push_back(RN);
354  Result.clear();
355 
356  while (!WL.empty()) {
357  const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
358  Result.push_back(N->getBlock());
359  WL.append(N->begin(), N->end());
360  }
361  }
362 
363  /// properlyDominates - Returns true iff A dominates B and A != B.
364  /// Note that this is not a constant time operation!
365  ///
367  const DomTreeNodeBase<NodeT> *B) {
368  if (A == 0 || B == 0)
369  return false;
370  if (A == B)
371  return false;
372  return dominates(A, B);
373  }
374 
375  bool properlyDominates(const NodeT *A, const NodeT *B);
376 
377  /// isReachableFromEntry - Return true if A is dominated by the entry
378  /// block of the function containing it.
379  bool isReachableFromEntry(const NodeT* A) const {
380  assert(!this->isPostDominator() &&
381  "This is not implemented for post dominators");
382  return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
383  }
384 
385  inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
386  return A;
387  }
388 
389  /// dominates - Returns true iff A dominates B. Note that this is not a
390  /// constant time operation!
391  ///
392  inline bool dominates(const DomTreeNodeBase<NodeT> *A,
393  const DomTreeNodeBase<NodeT> *B) {
394  // A node trivially dominates itself.
395  if (B == A)
396  return true;
397 
398  // An unreachable node is dominated by anything.
399  if (!isReachableFromEntry(B))
400  return true;
401 
402  // And dominates nothing.
403  if (!isReachableFromEntry(A))
404  return false;
405 
406  // Compare the result of the tree walk and the dfs numbers, if expensive
407  // checks are enabled.
408 #ifdef XDEBUG
409  assert((!DFSInfoValid ||
410  (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
411  "Tree walk disagrees with dfs numbers!");
412 #endif
413 
414  if (DFSInfoValid)
415  return B->DominatedBy(A);
416 
417  // If we end up with too many slow queries, just update the
418  // DFS numbers on the theory that we are going to keep querying.
419  SlowQueries++;
420  if (SlowQueries > 32) {
422  return B->DominatedBy(A);
423  }
424 
425  return dominatedBySlowTreeWalk(A, B);
426  }
427 
428  bool dominates(const NodeT *A, const NodeT *B);
429 
430  NodeT *getRoot() const {
431  assert(this->Roots.size() == 1 && "Should always have entry node!");
432  return this->Roots[0];
433  }
434 
435  /// findNearestCommonDominator - Find nearest common dominator basic block
436  /// for basic block A and B. If there is no such block then return NULL.
437  NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
438  assert(A->getParent() == B->getParent() &&
439  "Two blocks are not in same function");
440 
441  // If either A or B is a entry block then it is nearest common dominator
442  // (for forward-dominators).
443  if (!this->isPostDominator()) {
444  NodeT &Entry = A->getParent()->front();
445  if (A == &Entry || B == &Entry)
446  return &Entry;
447  }
448 
449  // If B dominates A then B is nearest common dominator.
450  if (dominates(B, A))
451  return B;
452 
453  // If A dominates B then A is nearest common dominator.
454  if (dominates(A, B))
455  return A;
456 
457  DomTreeNodeBase<NodeT> *NodeA = getNode(A);
458  DomTreeNodeBase<NodeT> *NodeB = getNode(B);
459 
460  // Collect NodeA dominators set.
461  SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
462  NodeADoms.insert(NodeA);
463  DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
464  while (IDomA) {
465  NodeADoms.insert(IDomA);
466  IDomA = IDomA->getIDom();
467  }
468 
469  // Walk NodeB immediate dominators chain and find common dominator node.
470  DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
471  while (IDomB) {
472  if (NodeADoms.count(IDomB) != 0)
473  return IDomB->getBlock();
474 
475  IDomB = IDomB->getIDom();
476  }
477 
478  return NULL;
479  }
480 
481  const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
482  // Cast away the const qualifiers here. This is ok since
483  // const is re-introduced on the return type.
484  return findNearestCommonDominator(const_cast<NodeT *>(A),
485  const_cast<NodeT *>(B));
486  }
487 
488  //===--------------------------------------------------------------------===//
489  // API to update (Post)DominatorTree information based on modifications to
490  // the CFG...
491 
492  /// addNewBlock - Add a new node to the dominator tree information. This
493  /// creates a new node as a child of DomBB dominator node,linking it into
494  /// the children list of the immediate dominator.
495  DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
496  assert(getNode(BB) == 0 && "Block already in dominator tree!");
497  DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
498  assert(IDomNode && "Not immediate dominator specified for block!");
499  DFSInfoValid = false;
500  return DomTreeNodes[BB] =
501  IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
502  }
503 
504  /// changeImmediateDominator - This method is used to update the dominator
505  /// tree information when a node's immediate dominator changes.
506  ///
508  DomTreeNodeBase<NodeT> *NewIDom) {
509  assert(N && NewIDom && "Cannot change null node pointers!");
510  DFSInfoValid = false;
511  N->setIDom(NewIDom);
512  }
513 
514  void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
516  }
517 
518  /// eraseNode - Removes a node from the dominator tree. Block must not
519  /// dominate any other blocks. Removes node from its immediate dominator's
520  /// children list. Deletes dominator node associated with basic block BB.
521  void eraseNode(NodeT *BB) {
522  DomTreeNodeBase<NodeT> *Node = getNode(BB);
523  assert(Node && "Removing node that isn't in dominator tree.");
524  assert(Node->getChildren().empty() && "Node is not a leaf node.");
525 
526  // Remove node from immediate dominator's children list.
527  DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
528  if (IDom) {
529  typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
530  std::find(IDom->Children.begin(), IDom->Children.end(), Node);
531  assert(I != IDom->Children.end() &&
532  "Not in immediate dominator children set!");
533  // I am no longer your child...
534  IDom->Children.erase(I);
535  }
536 
537  DomTreeNodes.erase(BB);
538  delete Node;
539  }
540 
541  /// removeNode - Removes a node from the dominator tree. Block must not
542  /// dominate any other blocks. Invalidates any node pointing to removed
543  /// block.
544  void removeNode(NodeT *BB) {
545  assert(getNode(BB) && "Removing node that isn't in dominator tree.");
546  DomTreeNodes.erase(BB);
547  }
548 
549  /// splitBlock - BB is split and now it has one successor. Update dominator
550  /// tree to reflect this change.
551  void splitBlock(NodeT* NewBB) {
552  if (this->IsPostDominators)
553  this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
554  else
555  this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
556  }
557 
558  /// print - Convert to human readable form
559  ///
560  void print(raw_ostream &o) const {
561  o << "=============================--------------------------------\n";
562  if (this->isPostDominator())
563  o << "Inorder PostDominator Tree: ";
564  else
565  o << "Inorder Dominator Tree: ";
566  if (!this->DFSInfoValid)
567  o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
568  o << "\n";
569 
570  // The postdom tree can have a null root if there are no returns.
571  if (getRootNode())
572  PrintDomTree<NodeT>(getRootNode(), o, 1);
573  }
574 
575 protected:
576  template<class GraphT>
577  friend typename GraphT::NodeType* Eval(
579  typename GraphT::NodeType* V,
580  unsigned LastLinked);
581 
582  template<class GraphT>
584  typename GraphT::NodeType* V,
585  unsigned N);
586 
587  template<class FuncT, class N>
588  friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
589  FuncT& F);
590 
591  /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
592  /// dominator tree in dfs order.
594  unsigned DFSNum = 0;
595 
597  typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
598 
599  DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
600 
601  if (!ThisRoot)
602  return;
603 
604  // Even in the case of multiple exits that form the post dominator root
605  // nodes, do not iterate over all exits, but start from the virtual root
606  // node. Otherwise bbs, that are not post dominated by any exit but by the
607  // virtual root node, will never be assigned a DFS number.
608  WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
609  ThisRoot->DFSNumIn = DFSNum++;
610 
611  while (!WorkStack.empty()) {
612  DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
613  typename DomTreeNodeBase<NodeT>::iterator ChildIt =
614  WorkStack.back().second;
615 
616  // If we visited all of the children of this node, "recurse" back up the
617  // stack setting the DFOutNum.
618  if (ChildIt == Node->end()) {
619  Node->DFSNumOut = DFSNum++;
620  WorkStack.pop_back();
621  } else {
622  // Otherwise, recursively visit this child.
623  DomTreeNodeBase<NodeT> *Child = *ChildIt;
624  ++WorkStack.back().second;
625 
626  WorkStack.push_back(std::make_pair(Child, Child->begin()));
627  Child->DFSNumIn = DFSNum++;
628  }
629  }
630 
631  SlowQueries = 0;
632  DFSInfoValid = true;
633  }
634 
636  if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
637  return Node;
638 
639  // Haven't calculated this node yet? Get or calculate the node for the
640  // immediate dominator.
641  NodeT *IDom = getIDom(BB);
642 
643  assert(IDom || this->DomTreeNodes[NULL]);
644  DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
645 
646  // Add a new tree node for this BasicBlock, and link it as a child of
647  // IDomNode
648  DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
649  return this->DomTreeNodes[BB] = IDomNode->addChild(C);
650  }
651 
652  inline NodeT *getIDom(NodeT *BB) const {
653  return IDoms.lookup(BB);
654  }
655 
656  inline void addRoot(NodeT* BB) {
657  this->Roots.push_back(BB);
658  }
659 
660 public:
661  /// recalculate - compute a dominator tree for the given function
662  template<class FT>
663  void recalculate(FT& F) {
664  typedef GraphTraits<FT*> TraitsTy;
665  reset();
666  this->Vertex.push_back(0);
667 
668  if (!this->IsPostDominators) {
669  // Initialize root
670  NodeT *entry = TraitsTy::getEntryNode(&F);
671  this->Roots.push_back(entry);
672  this->IDoms[entry] = 0;
673  this->DomTreeNodes[entry] = 0;
674 
675  Calculate<FT, NodeT*>(*this, F);
676  } else {
677  // Initialize the roots list
678  for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
679  E = TraitsTy::nodes_end(&F); I != E; ++I) {
680  if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
681  addRoot(I);
682 
683  // Prepopulate maps so that we don't get iterator invalidation issues later.
684  this->IDoms[I] = 0;
685  this->DomTreeNodes[I] = 0;
686  }
687 
688  Calculate<FT, Inverse<NodeT*> >(*this, F);
689  }
690  }
691 };
692 
693 // These two functions are declared out of line as a workaround for building
694 // with old (< r147295) versions of clang because of pr11642.
695 template<class NodeT>
696 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) {
697  if (A == B)
698  return true;
699 
700  // Cast away the const qualifiers here. This is ok since
701  // this function doesn't actually return the values returned
702  // from getNode.
703  return dominates(getNode(const_cast<NodeT *>(A)),
704  getNode(const_cast<NodeT *>(B)));
705 }
706 template<class NodeT>
707 bool
708 DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B) {
709  if (A == B)
710  return false;
711 
712  // Cast away the const qualifiers here. This is ok since
713  // this function doesn't actually return the values returned
714  // from getNode.
715  return dominates(getNode(const_cast<NodeT *>(A)),
716  getNode(const_cast<NodeT *>(B)));
717 }
718 
720 
722  const BasicBlock *Start;
723  const BasicBlock *End;
724 public:
725  BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) :
726  Start(Start_), End(End_) { }
727  const BasicBlock *getStart() const {
728  return Start;
729  }
730  const BasicBlock *getEnd() const {
731  return End;
732  }
733  bool isSingleEdge() const;
734 };
735 
736 //===-------------------------------------
737 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
738 /// compute a normal dominator tree.
739 ///
740 class DominatorTree : public FunctionPass {
741 public:
742  static char ID; // Pass ID, replacement for typeid
744 
747  DT = new DominatorTreeBase<BasicBlock>(false);
748  }
749 
751  delete DT;
752  }
753 
755 
756  /// getRoots - Return the root blocks of the current CFG. This may include
757  /// multiple blocks if we are computing post dominators. For forward
758  /// dominators, this will always be a single block (the entry node).
759  ///
760  inline const std::vector<BasicBlock*> &getRoots() const {
761  return DT->getRoots();
762  }
763 
764  inline BasicBlock *getRoot() const {
765  return DT->getRoot();
766  }
767 
768  inline DomTreeNode *getRootNode() const {
769  return DT->getRootNode();
770  }
771 
772  /// Get all nodes dominated by R, including R itself. Return true on success.
774  SmallVectorImpl<BasicBlock *> &Result) const {
775  DT->getDescendants(R, Result);
776  }
777 
778  /// compare - Return false if the other dominator tree matches this
779  /// dominator tree. Otherwise return true.
780  inline bool compare(DominatorTree &Other) const {
781  DomTreeNode *R = getRootNode();
782  DomTreeNode *OtherR = Other.getRootNode();
783 
784  if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
785  return true;
786 
787  if (DT->compare(Other.getBase()))
788  return true;
789 
790  return false;
791  }
792 
793  virtual bool runOnFunction(Function &F);
794 
795  virtual void verifyAnalysis() const;
796 
797  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
798  AU.setPreservesAll();
799  }
800 
801  inline bool dominates(const DomTreeNode* A, const DomTreeNode* B) const {
802  return DT->dominates(A, B);
803  }
804 
805  inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
806  return DT->dominates(A, B);
807  }
808 
809  // dominates - Return true if Def dominates a use in User. This performs
810  // the special checks necessary if Def and User are in the same basic block.
811  // Note that Def doesn't dominate a use in Def itself!
812  bool dominates(const Instruction *Def, const Use &U) const;
813  bool dominates(const Instruction *Def, const Instruction *User) const;
814  bool dominates(const Instruction *Def, const BasicBlock *BB) const;
815  bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
816  bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
817 
818  bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
819  return DT->properlyDominates(A, B);
820  }
821 
822  bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const {
823  return DT->properlyDominates(A, B);
824  }
825 
826  /// findNearestCommonDominator - Find nearest common dominator basic block
827  /// for basic block A and B. If there is no such block then return NULL.
829  return DT->findNearestCommonDominator(A, B);
830  }
831 
833  const BasicBlock *B) {
834  return DT->findNearestCommonDominator(A, B);
835  }
836 
837  inline DomTreeNode *operator[](BasicBlock *BB) const {
838  return DT->getNode(BB);
839  }
840 
841  /// getNode - return the (Post)DominatorTree node for the specified basic
842  /// block. This is the same as using operator[] on this class.
843  ///
844  inline DomTreeNode *getNode(BasicBlock *BB) const {
845  return DT->getNode(BB);
846  }
847 
848  /// addNewBlock - Add a new node to the dominator tree information. This
849  /// creates a new node as a child of DomBB dominator node,linking it into
850  /// the children list of the immediate dominator.
852  return DT->addNewBlock(BB, DomBB);
853  }
854 
855  /// changeImmediateDominator - This method is used to update the dominator
856  /// tree information when a node's immediate dominator changes.
857  ///
859  DT->changeImmediateDominator(N, NewIDom);
860  }
861 
863  DT->changeImmediateDominator(N, NewIDom);
864  }
865 
866  /// eraseNode - Removes a node from the dominator tree. Block must not
867  /// dominate any other blocks. Removes node from its immediate dominator's
868  /// children list. Deletes dominator node associated with basic block BB.
869  inline void eraseNode(BasicBlock *BB) {
870  DT->eraseNode(BB);
871  }
872 
873  /// splitBlock - BB is split and now it has one successor. Update dominator
874  /// tree to reflect this change.
875  inline void splitBlock(BasicBlock* NewBB) {
876  DT->splitBlock(NewBB);
877  }
878 
879  bool isReachableFromEntry(const BasicBlock* A) const {
880  return DT->isReachableFromEntry(A);
881  }
882 
883  bool isReachableFromEntry(const Use &U) const;
884 
885 
886  virtual void releaseMemory() {
887  DT->releaseMemory();
888  }
889 
890  virtual void print(raw_ostream &OS, const Module* M= 0) const;
891 };
892 
893 //===-------------------------------------
894 /// DominatorTree GraphTraits specialization so the DominatorTree can be
895 /// iterable by generic graph iterators.
896 ///
897 template <> struct GraphTraits<DomTreeNode*> {
900 
901  static NodeType *getEntryNode(NodeType *N) {
902  return N;
903  }
904  static inline ChildIteratorType child_begin(NodeType *N) {
905  return N->begin();
906  }
907  static inline ChildIteratorType child_end(NodeType *N) {
908  return N->end();
909  }
910 
912 
913  static nodes_iterator nodes_begin(DomTreeNode *N) {
914  return df_begin(getEntryNode(N));
915  }
916 
917  static nodes_iterator nodes_end(DomTreeNode *N) {
918  return df_end(getEntryNode(N));
919  }
920 };
921 
922 template <> struct GraphTraits<DominatorTree*>
923  : public GraphTraits<DomTreeNode*> {
925  return DT->getRootNode();
926  }
927 
929  return df_begin(getEntryNode(N));
930  }
931 
933  return df_end(getEntryNode(N));
934  }
935 };
936 
937 
938 } // End llvm namespace
939 
940 #endif
DenseMap< NodeT *, InfoRec > Info
Definition: Dominators.h:223
DomTreeNode * getNode(BasicBlock *BB) const
Definition: Dominators.h:844
const MachineFunction * getParent() const
virtual ~DominatorTreeBase()
Definition: Dominators.h:302
static PassRegistry * getPassRegistry()
DominatorTreeBase< BasicBlock > * DT
Definition: Dominators.h:743
std::vector< NodeT * > Roots
Definition: Dominators.h:39
const BasicBlock * findNearestCommonDominator(const BasicBlock *A, const BasicBlock *B)
Definition: Dominators.h:832
const_iterator end() const
Definition: Dominators.h:80
The main container class for the LLVM Intermediate Representation.
Definition: Module.h:112
bool isReachableFromEntry(const BasicBlock *A) const
Definition: Dominators.h:879
const BasicBlock * getStart() const
Definition: Dominators.h:727
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase< BasicBlock >)
bool insert(PtrType Ptr)
Definition: SmallPtrSet.h:253
void splitBlock(BasicBlock *NewBB)
Definition: Dominators.h:875
const_iterator begin() const
Definition: Dominators.h:79
bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const
Definition: Dominators.h:818
DomTreeNodeMapType DomTreeNodes
Definition: Dominators.h:202
F(f)
DomTreeNodeBase< NodeT > * getRootNode()
Definition: Dominators.h:346
bool isPostDominator() const
Definition: Dominators.h:53
void initializeDominatorTreePass(PassRegistry &)
NodeType::iterator ChildIteratorType
Definition: Dominators.h:899
friend GraphT::NodeType * Eval(DominatorTreeBase< typename GraphT::NodeType > &DT, typename GraphT::NodeType *V, unsigned LastLinked)
virtual void releaseMemory()
Definition: Dominators.h:330
std::vector< NodeT * > Vertex
Definition: Dominators.h:220
static nodes_iterator nodes_begin(DominatorTree *N)
Definition: Dominators.h:928
DomTreeNodeBase< NodeT > * getIDom() const
Definition: Dominators.h:83
void WriteAsOperand(raw_ostream &, const Value *, bool PrintTy=true, const Module *Context=0)
Definition: AsmWriter.cpp:1179
virtual void getAnalysisUsage(AnalysisUsage &AU) const
Definition: Dominators.h:797
void Split(DominatorTreeBase< typename GraphT::NodeType > &DT, typename GraphT::NodeType *NewBB)
Definition: Dominators.h:239
unsigned int SlowQueries
Definition: Dominators.h:206
void changeImmediateDominator(NodeT *BB, NodeT *NewBB)
Definition: Dominators.h:514
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:430
bool isReachableFromEntry(const DomTreeNodeBase< NodeT > *A) const
Definition: Dominators.h:385
Definition: Use.h:60
void changeImmediateDominator(BasicBlock *N, BasicBlock *NewIDom)
Definition: Dominators.h:858
DominatorTreeBase< BasicBlock > & getBase()
Definition: Dominators.h:754
static ChildIteratorType child_begin(NodeType *N)
Definition: Dominators.h:904
#define false
Definition: ConvertUTF.c:64
const bool IsPostDominators
Definition: Dominators.h:40
const MachineBasicBlock & front() const
DominatorBase(bool isPostDom)
Definition: Dominators.h:41
bool count(PtrType Ptr) const
count - Return true if the specified pointer is in the set.
Definition: SmallPtrSet.h:264
void eraseNode(BasicBlock *BB)
Definition: Dominators.h:869
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:56
static nodes_iterator nodes_end(DominatorTree *N)
Definition: Dominators.h:932
void print(raw_ostream &o) const
Definition: Dominators.h:560
friend void Calculate(DominatorTreeBase< typename GraphTraits< N >::NodeType > &DT, FuncT &F)
NodeT * getBlock() const
Definition: Dominators.h:82
DominatorTreeBase(bool isPostDom)
Definition: Dominators.h:300
DenseMap< NodeT *, DomTreeNodeBase< NodeT > * > DomTreeNodeMapType
Definition: Dominators.h:201
bool compare(const DomTreeNodeBase< NodeT > *Other) const
Definition: Dominators.h:104
LLVM Basic Block Representation.
Definition: BasicBlock.h:72
DenseMap< NodeT *, NodeT * > IDoms
Definition: Dominators.h:217
static NodeType * getEntryNode(DominatorTree *DT)
Definition: Dominators.h:924
df_iterator< T > df_end(const T &G)
void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom)
Definition: Dominators.h:862
unsigned getDFSNumIn() const
Definition: Dominators.h:140
static ChildIteratorType child_end(NodeType *N)
Definition: Dominators.h:907
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
Definition: Dominators.h:507
iterator end()
Definition: DenseMap.h:57
static NodeType * getEntryNode(NodeType *N)
Definition: Dominators.h:901
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B)
Definition: Dominators.h:366
bool dominates(const DomTreeNode *A, const DomTreeNode *B) const
Definition: Dominators.h:801
void append(in_iter in_start, in_iter in_end)
Definition: SmallVector.h:445
void recalculate(FT &F)
recalculate - compute a dominator tree for the given function
Definition: Dominators.h:663
void Calculate(DominatorTreeBase< typename GraphTraits< NodeT >::NodeType > &DT, FuncT &F)
static nodes_iterator nodes_end(DomTreeNode *N)
Definition: Dominators.h:917
NodeT * getRoot() const
Definition: Dominators.h:430
const BasicBlock * getEnd() const
Definition: Dominators.h:730
virtual bool runOnFunction(Function &F)
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Definition: Dominators.h:495
const std::vector< DomTreeNodeBase< NodeT > * > & getChildren() const
Definition: Dominators.h:84
void addRoot(NodeT *BB)
Definition: Dominators.h:656
void PrintDomTree(const DomTreeNodeBase< NodeT > *N, raw_ostream &o, unsigned Lev)
Definition: Dominators.h:168
void setIDom(DomTreeNodeBase< NodeT > *NewIDom)
Definition: Dominators.h:122
GraphType::UnknownGraphTypeError NodeType
Definition: GraphTraits.h:60
DomTreeNodeBase< NodeT > * getNodeForBlock(NodeT *BB)
Definition: Dominators.h:635
df_iterator< DomTreeNode * > nodes_iterator
Definition: Dominators.h:911
virtual void print(raw_ostream &OS, const Module *M=0) const
Definition: Dominators.cpp:92
bool erase(const KeyT &Val)
Definition: DenseMap.h:190
BasicBlock * getRoot() const
Definition: Dominators.h:764
std::vector< DomTreeNodeBase< llvm::MachineBasicBlock > * >::const_iterator const_iterator
Definition: Dominators.h:75
NodeT * getIDom(NodeT *BB) const
Definition: Dominators.h:652
DomTreeNode * getRootNode() const
Definition: Dominators.h:768
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition: Dominators.h:176
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
Definition: Dominators.h:335
df_iterator< T > df_begin(const T &G)
virtual void releaseMemory()
Definition: Dominators.h:886
unsigned size() const
Definition: DenseMap.h:70
DomTreeNodeBase< NodeT > * RootNode
Definition: Dominators.h:203
iterator begin()
Definition: DenseMap.h:53
DomTreeNodeBase< NodeT > * addChild(DomTreeNodeBase< NodeT > *C)
Definition: Dominators.h:91
bool compare(DominatorTree &Other) const
Definition: Dominators.h:780
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B)
Definition: Dominators.h:392
unsigned getDFSNumOut() const
Definition: Dominators.h:141
bool compare(DominatorTreeBase &Other) const
Definition: Dominators.h:306
bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const
Definition: Dominators.h:822
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B)
Definition: Dominators.h:437
void eraseNode(NodeT *BB)
Definition: Dominators.h:521
BasicBlock * findNearestCommonDominator(BasicBlock *A, BasicBlock *B)
Definition: Dominators.h:828
DomTreeNode * addNewBlock(BasicBlock *BB, BasicBlock *DomBB)
Definition: Dominators.h:851
void getDescendants(BasicBlock *R, SmallVectorImpl< BasicBlock * > &Result) const
Get all nodes dominated by R, including R itself. Return true on success.
Definition: Dominators.h:773
DomTreeNodeBase(NodeT *BB, DomTreeNodeBase< NodeT > *iDom)
Definition: Dominators.h:88
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:1688
virtual void verifyAnalysis() const
Definition: Dominators.cpp:76
bool isSingleEdge() const
Definition: Dominators.cpp:42
BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_)
Definition: Dominators.h:725
static char ID
Definition: Dominators.h:742
std::vector< DomTreeNodeBase< llvm::MachineBasicBlock > * >::iterator iterator
Definition: Dominators.h:73
const NodeT * findNearestCommonDominator(const NodeT *A, const NodeT *B)
Definition: Dominators.h:481
ValueT lookup(const KeyT &Val) const
Definition: DenseMap.h:143
bool isReachableFromEntry(const NodeT *A) const
Definition: Dominators.h:379
bool dominates(const BasicBlock *A, const BasicBlock *B) const
Definition: Dominators.h:805
static nodes_iterator nodes_begin(DomTreeNode *N)
Definition: Dominators.h:913
void removeNode(NodeT *BB)
Definition: Dominators.h:544
const std::vector< NodeT * > & getRoots() const
Definition: Dominators.h:49
const std::vector< BasicBlock * > & getRoots() const
Definition: Dominators.h:760
void getDescendants(NodeT *R, SmallVectorImpl< NodeT * > &Result) const
Get all nodes dominated by R, including R itself. Return true on success.
Definition: Dominators.h:350
iterator find(const KeyT &Val)
Definition: DenseMap.h:108
friend unsigned DFSPass(DominatorTreeBase< typename GraphT::NodeType > &DT, typename GraphT::NodeType *V, unsigned N)
const DomTreeNodeBase< NodeT > * getRootNode() const
Definition: Dominators.h:347
DomTreeNode * operator[](BasicBlock *BB) const
Definition: Dominators.h:837
size_t getNumChildren() const
Definition: Dominators.h:96
void splitBlock(NodeT *NewBB)
Definition: Dominators.h:551