LLVM  5.0.0
GenericDomTree.h
Go to the documentation of this file.
1 //===- GenericDomTree.h - Generic dominator trees for graphs ----*- 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 /// \file
10 ///
11 /// This file defines a set of templates that efficiently compute a dominator
12 /// tree over a generic graph. This is used typically in LLVM for fast
13 /// dominance queries on the CFG, but is fully generic w.r.t. the underlying
14 /// graph types.
15 ///
16 /// Unlike ADT/* graph algorithms, generic dominator tree has more requirements
17 /// on the graph's NodeRef. The NodeRef should be a pointer and, depending on
18 /// the implementation, e.g. NodeRef->getParent() return the parent node.
19 ///
20 /// FIXME: Maybe GenericDomTree needs a TreeTraits, instead of GraphTraits.
21 ///
22 //===----------------------------------------------------------------------===//
23 
24 #ifndef LLVM_SUPPORT_GENERICDOMTREE_H
25 #define LLVM_SUPPORT_GENERICDOMTREE_H
26 
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/GraphTraits.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <cstddef>
36 #include <iterator>
37 #include <memory>
38 #include <type_traits>
39 #include <utility>
40 #include <vector>
41 
42 namespace llvm {
43 
44 template <typename NodeT, bool IsPostDom>
45 class DominatorTreeBase;
46 
47 namespace DomTreeBuilder {
48 template <class DomTreeT>
49 struct SemiNCAInfo;
50 } // namespace DomTreeBuilder
51 
52 /// \brief Base class for the actual dominator tree node.
53 template <class NodeT> class DomTreeNodeBase {
54  friend struct PostDominatorTree;
55  friend class DominatorTreeBase<NodeT, false>;
56  friend class DominatorTreeBase<NodeT, true>;
59 
60  NodeT *TheBB;
61  DomTreeNodeBase *IDom;
62  unsigned Level;
63  std::vector<DomTreeNodeBase *> Children;
64  mutable unsigned DFSNumIn = ~0;
65  mutable unsigned DFSNumOut = ~0;
66 
67  public:
68  DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom)
69  : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {}
70 
71  using iterator = typename std::vector<DomTreeNodeBase *>::iterator;
72  using const_iterator =
73  typename std::vector<DomTreeNodeBase *>::const_iterator;
74 
75  iterator begin() { return Children.begin(); }
76  iterator end() { return Children.end(); }
77  const_iterator begin() const { return Children.begin(); }
78  const_iterator end() const { return Children.end(); }
79 
80  NodeT *getBlock() const { return TheBB; }
81  DomTreeNodeBase *getIDom() const { return IDom; }
82  unsigned getLevel() const { return Level; }
83 
84  const std::vector<DomTreeNodeBase *> &getChildren() const { return Children; }
85 
86  std::unique_ptr<DomTreeNodeBase> addChild(
87  std::unique_ptr<DomTreeNodeBase> C) {
88  Children.push_back(C.get());
89  return C;
90  }
91 
92  size_t getNumChildren() const { return Children.size(); }
93 
94  void clearAllChildren() { Children.clear(); }
95 
96  bool compare(const DomTreeNodeBase *Other) const {
97  if (getNumChildren() != Other->getNumChildren())
98  return true;
99 
100  if (Level != Other->Level) return true;
101 
102  SmallPtrSet<const NodeT *, 4> OtherChildren;
103  for (const DomTreeNodeBase *I : *Other) {
104  const NodeT *Nd = I->getBlock();
105  OtherChildren.insert(Nd);
106  }
107 
108  for (const DomTreeNodeBase *I : *this) {
109  const NodeT *N = I->getBlock();
110  if (OtherChildren.count(N) == 0)
111  return true;
112  }
113  return false;
114  }
115 
116  void setIDom(DomTreeNodeBase *NewIDom) {
117  assert(IDom && "No immediate dominator?");
118  if (IDom == NewIDom) return;
119 
120  auto I = find(IDom->Children, this);
121  assert(I != IDom->Children.end() &&
122  "Not in immediate dominator children set!");
123  // I am no longer your child...
124  IDom->Children.erase(I);
125 
126  // Switch to new dominator
127  IDom = NewIDom;
128  IDom->Children.push_back(this);
129 
130  UpdateLevel();
131  }
132 
133  /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
134  /// in the dominator tree. They are only guaranteed valid if
135  /// updateDFSNumbers() has been called.
136  unsigned getDFSNumIn() const { return DFSNumIn; }
137  unsigned getDFSNumOut() const { return DFSNumOut; }
138 
139 private:
140  // Return true if this node is dominated by other. Use this only if DFS info
141  // is valid.
142  bool DominatedBy(const DomTreeNodeBase *other) const {
143  return this->DFSNumIn >= other->DFSNumIn &&
144  this->DFSNumOut <= other->DFSNumOut;
145  }
146 
147  void UpdateLevel() {
148  assert(IDom);
149  if (Level == IDom->Level + 1) return;
150 
151  SmallVector<DomTreeNodeBase *, 64> WorkStack = {this};
152 
153  while (!WorkStack.empty()) {
154  DomTreeNodeBase *Current = WorkStack.pop_back_val();
155  Current->Level = Current->IDom->Level + 1;
156 
157  for (DomTreeNodeBase *C : *Current) {
158  assert(C->IDom);
159  if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C);
160  }
161  }
162  }
163 };
164 
165 template <class NodeT>
166 raw_ostream &operator<<(raw_ostream &O, const DomTreeNodeBase<NodeT> *Node) {
167  if (Node->getBlock())
168  Node->getBlock()->printAsOperand(O, false);
169  else
170  O << " <<exit node>>";
171 
172  O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} ["
173  << Node->getLevel() << "]\n";
174 
175  return O;
176 }
177 
178 template <class NodeT>
180  unsigned Lev) {
181  O.indent(2 * Lev) << "[" << Lev << "] " << N;
182  for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
183  E = N->end();
184  I != E; ++I)
185  PrintDomTree<NodeT>(*I, O, Lev + 1);
186 }
187 
188 namespace DomTreeBuilder {
189 // The routines below are provided in a separate header but referenced here.
190 template <typename DomTreeT, typename FuncT>
191 void Calculate(DomTreeT &DT, FuncT &F);
192 
193 template <class DomTreeT>
194 void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
195  typename DomTreeT::NodePtr To);
196 
197 template <class DomTreeT>
198 void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
199  typename DomTreeT::NodePtr To);
200 
201 template <typename DomTreeT>
202 bool Verify(const DomTreeT &DT);
203 } // namespace DomTreeBuilder
204 
205 /// \brief Core dominator tree base class.
206 ///
207 /// This class is a generic template over graph nodes. It is instantiated for
208 /// various graphs in the LLVM IR or in the code generator.
209 template <typename NodeT, bool IsPostDom>
210 class DominatorTreeBase {
211  protected:
212  std::vector<NodeT *> Roots;
213 
214  using DomTreeNodeMapType =
218  using ParentPtr = decltype(std::declval<NodeT *>()->getParent());
219  ParentPtr Parent = nullptr;
220 
221  mutable bool DFSInfoValid = false;
222  mutable unsigned int SlowQueries = 0;
223 
225 
226  public:
227  static_assert(std::is_pointer<typename GraphTraits<NodeT *>::NodeRef>::value,
228  "Currently DominatorTreeBase supports only pointer nodes");
229  using NodeType = NodeT;
230  using NodePtr = NodeT *;
231  static constexpr bool IsPostDominator = IsPostDom;
232 
234 
236  : Roots(std::move(Arg.Roots)),
237  DomTreeNodes(std::move(Arg.DomTreeNodes)),
238  RootNode(Arg.RootNode),
239  Parent(Arg.Parent),
241  SlowQueries(Arg.SlowQueries) {
242  Arg.wipe();
243  }
244 
246  Roots = std::move(RHS.Roots);
247  DomTreeNodes = std::move(RHS.DomTreeNodes);
248  RootNode = RHS.RootNode;
249  Parent = RHS.Parent;
250  DFSInfoValid = RHS.DFSInfoValid;
251  SlowQueries = RHS.SlowQueries;
252  RHS.wipe();
253  return *this;
254  }
255 
256  DominatorTreeBase(const DominatorTreeBase &) = delete;
257  DominatorTreeBase &operator=(const DominatorTreeBase &) = delete;
258 
259  /// getRoots - Return the root blocks of the current CFG. This may include
260  /// multiple blocks if we are computing post dominators. For forward
261  /// dominators, this will always be a single block (the entry node).
262  ///
263  const std::vector<NodeT *> &getRoots() const { return Roots; }
264 
265  /// isPostDominator - Returns true if analysis based of postdoms
266  ///
267  bool isPostDominator() const { return IsPostDominator; }
268 
269  /// compare - Return false if the other dominator tree base matches this
270  /// dominator tree base. Otherwise return true.
271  bool compare(const DominatorTreeBase &Other) const {
272  if (Parent != Other.Parent) return true;
273 
274  const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
275  if (DomTreeNodes.size() != OtherDomTreeNodes.size())
276  return true;
277 
278  for (const auto &DomTreeNode : DomTreeNodes) {
279  NodeT *BB = DomTreeNode.first;
280  typename DomTreeNodeMapType::const_iterator OI =
281  OtherDomTreeNodes.find(BB);
282  if (OI == OtherDomTreeNodes.end())
283  return true;
284 
285  DomTreeNodeBase<NodeT> &MyNd = *DomTreeNode.second;
286  DomTreeNodeBase<NodeT> &OtherNd = *OI->second;
287 
288  if (MyNd.compare(&OtherNd))
289  return true;
290  }
291 
292  return false;
293  }
294 
295  void releaseMemory() { reset(); }
296 
297  /// getNode - return the (Post)DominatorTree node for the specified basic
298  /// block. This is the same as using operator[] on this class. The result
299  /// may (but is not required to) be null for a forward (backwards)
300  /// statically unreachable block.
301  DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
302  auto I = DomTreeNodes.find(BB);
303  if (I != DomTreeNodes.end())
304  return I->second.get();
305  return nullptr;
306  }
307 
308  /// See getNode.
309  DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const { return getNode(BB); }
310 
311  /// getRootNode - This returns the entry node for the CFG of the function. If
312  /// this tree represents the post-dominance relations for a function, however,
313  /// this root may be a node with the block == NULL. This is the case when
314  /// there are multiple exit nodes from a particular function. Consumers of
315  /// post-dominance information must be capable of dealing with this
316  /// possibility.
317  ///
319  const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
320 
321  /// Get all nodes dominated by R, including R itself.
322  void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
323  Result.clear();
324  const DomTreeNodeBase<NodeT> *RN = getNode(R);
325  if (!RN)
326  return; // If R is unreachable, it will not be present in the DOM tree.
328  WL.push_back(RN);
329 
330  while (!WL.empty()) {
331  const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
332  Result.push_back(N->getBlock());
333  WL.append(N->begin(), N->end());
334  }
335  }
336 
337  /// properlyDominates - Returns true iff A dominates B and A != B.
338  /// Note that this is not a constant time operation!
339  ///
341  const DomTreeNodeBase<NodeT> *B) const {
342  if (!A || !B)
343  return false;
344  if (A == B)
345  return false;
346  return dominates(A, B);
347  }
348 
349  bool properlyDominates(const NodeT *A, const NodeT *B) const;
350 
351  /// isReachableFromEntry - Return true if A is dominated by the entry
352  /// block of the function containing it.
353  bool isReachableFromEntry(const NodeT *A) const {
354  assert(!this->isPostDominator() &&
355  "This is not implemented for post dominators");
356  return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
357  }
358 
359  bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
360 
361  /// dominates - Returns true iff A dominates B. Note that this is not a
362  /// constant time operation!
363  ///
365  const DomTreeNodeBase<NodeT> *B) const {
366  // A node trivially dominates itself.
367  if (B == A)
368  return true;
369 
370  // An unreachable node is dominated by anything.
371  if (!isReachableFromEntry(B))
372  return true;
373 
374  // And dominates nothing.
375  if (!isReachableFromEntry(A))
376  return false;
377 
378  if (B->getIDom() == A) return true;
379 
380  if (A->getIDom() == B) return false;
381 
382  // A can only dominate B if it is higher in the tree.
383  if (A->getLevel() >= B->getLevel()) return false;
384 
385  // Compare the result of the tree walk and the dfs numbers, if expensive
386  // checks are enabled.
387 #ifdef EXPENSIVE_CHECKS
388  assert((!DFSInfoValid ||
389  (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
390  "Tree walk disagrees with dfs numbers!");
391 #endif
392 
393  if (DFSInfoValid)
394  return B->DominatedBy(A);
395 
396  // If we end up with too many slow queries, just update the
397  // DFS numbers on the theory that we are going to keep querying.
398  SlowQueries++;
399  if (SlowQueries > 32) {
401  return B->DominatedBy(A);
402  }
403 
404  return dominatedBySlowTreeWalk(A, B);
405  }
406 
407  bool dominates(const NodeT *A, const NodeT *B) const;
408 
409  NodeT *getRoot() const {
410  assert(this->Roots.size() == 1 && "Should always have entry node!");
411  return this->Roots[0];
412  }
413 
414  /// findNearestCommonDominator - Find nearest common dominator basic block
415  /// for basic block A and B. If there is no such block then return NULL.
416  NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const {
417  assert(A->getParent() == B->getParent() &&
418  "Two blocks are not in same function");
419 
420  // If either A or B is a entry block then it is nearest common dominator
421  // (for forward-dominators).
422  if (!this->isPostDominator()) {
423  NodeT &Entry = A->getParent()->front();
424  if (A == &Entry || B == &Entry)
425  return &Entry;
426  }
427 
428  DomTreeNodeBase<NodeT> *NodeA = getNode(A);
429  DomTreeNodeBase<NodeT> *NodeB = getNode(B);
430 
431  if (!NodeA || !NodeB) return nullptr;
432 
433  // Use level information to go up the tree until the levels match. Then
434  // continue going up til we arrive at the same node.
435  while (NodeA && NodeA != NodeB) {
436  if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB);
437 
438  NodeA = NodeA->IDom;
439  }
440 
441  return NodeA ? NodeA->getBlock() : nullptr;
442  }
443 
444  const NodeT *findNearestCommonDominator(const NodeT *A,
445  const NodeT *B) const {
446  // Cast away the const qualifiers here. This is ok since
447  // const is re-introduced on the return type.
448  return findNearestCommonDominator(const_cast<NodeT *>(A),
449  const_cast<NodeT *>(B));
450  }
451 
453  return isPostDominator() && !A->getBlock();
454  }
455 
456  //===--------------------------------------------------------------------===//
457  // API to update (Post)DominatorTree information based on modifications to
458  // the CFG...
459 
460  /// Inform the dominator tree about a CFG edge insertion and update the tree.
461  ///
462  /// This function has to be called just before or just after making the update
463  /// on the actual CFG. There cannot be any other updates that the dominator
464  /// tree doesn't know about.
465  ///
466  /// Note that for postdominators it automatically takes care of inserting
467  /// a reverse edge internally (so there's no need to swap the parameters).
468  ///
469  void insertEdge(NodeT *From, NodeT *To) {
470  assert(From);
471  assert(To);
472  assert(From->getParent() == Parent);
473  assert(To->getParent() == Parent);
474  DomTreeBuilder::InsertEdge(*this, From, To);
475  }
476 
477  /// Inform the dominator tree about a CFG edge deletion and update the tree.
478  ///
479  /// This function has to be called just after making the update
480  /// on the actual CFG. There cannot be any other updates that the dominator
481  /// tree doesn't know about. The only exception is when the deletion that the
482  /// tree is informed about makes some (domominator) subtree unreachable -- in
483  /// this case, it is fine to perform deletions within this subtree.
484  ///
485  /// Note that for postdominators it automatically takes care of deleting
486  /// a reverse edge internally (so there's no need to swap the parameters).
487  ///
488  void deleteEdge(NodeT *From, NodeT *To) {
489  assert(From);
490  assert(To);
491  assert(From->getParent() == Parent);
492  assert(To->getParent() == Parent);
493  DomTreeBuilder::DeleteEdge(*this, From, To);
494  }
495 
496  /// Add a new node to the dominator tree information.
497  ///
498  /// This creates a new node as a child of DomBB dominator node, linking it
499  /// into the children list of the immediate dominator.
500  ///
501  /// \param BB New node in CFG.
502  /// \param DomBB CFG node that is dominator for BB.
503  /// \returns New dominator tree node that represents new CFG node.
504  ///
505  DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
506  assert(getNode(BB) == nullptr && "Block already in dominator tree!");
507  DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
508  assert(IDomNode && "Not immediate dominator specified for block!");
509  DFSInfoValid = false;
510  return (DomTreeNodes[BB] = IDomNode->addChild(
511  llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, IDomNode))).get();
512  }
513 
514  /// Add a new node to the forward dominator tree and make it a new root.
515  ///
516  /// \param BB New node in CFG.
517  /// \returns New dominator tree node that represents new CFG node.
518  ///
520  assert(getNode(BB) == nullptr && "Block already in dominator tree!");
521  assert(!this->isPostDominator() &&
522  "Cannot change root of post-dominator tree");
523  DFSInfoValid = false;
524  DomTreeNodeBase<NodeT> *NewNode = (DomTreeNodes[BB] =
525  llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, nullptr)).get();
526  if (Roots.empty()) {
527  addRoot(BB);
528  } else {
529  assert(Roots.size() == 1);
530  NodeT *OldRoot = Roots.front();
531  auto &OldNode = DomTreeNodes[OldRoot];
532  OldNode = NewNode->addChild(std::move(DomTreeNodes[OldRoot]));
533  OldNode->IDom = NewNode;
534  OldNode->UpdateLevel();
535  Roots[0] = BB;
536  }
537  return RootNode = NewNode;
538  }
539 
540  /// changeImmediateDominator - This method is used to update the dominator
541  /// tree information when a node's immediate dominator changes.
542  ///
544  DomTreeNodeBase<NodeT> *NewIDom) {
545  assert(N && NewIDom && "Cannot change null node pointers!");
546  DFSInfoValid = false;
547  N->setIDom(NewIDom);
548  }
549 
550  void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
552  }
553 
554  /// eraseNode - Removes a node from the dominator tree. Block must not
555  /// dominate any other blocks. Removes node from its immediate dominator's
556  /// children list. Deletes dominator node associated with basic block BB.
557  void eraseNode(NodeT *BB) {
558  DomTreeNodeBase<NodeT> *Node = getNode(BB);
559  assert(Node && "Removing node that isn't in dominator tree.");
560  assert(Node->getChildren().empty() && "Node is not a leaf node.");
561 
562  // Remove node from immediate dominator's children list.
563  DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
564  if (IDom) {
565  typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
566  find(IDom->Children, Node);
567  assert(I != IDom->Children.end() &&
568  "Not in immediate dominator children set!");
569  // I am no longer your child...
570  IDom->Children.erase(I);
571  }
572 
573  DomTreeNodes.erase(BB);
574  }
575 
576  /// splitBlock - BB is split and now it has one successor. Update dominator
577  /// tree to reflect this change.
578  void splitBlock(NodeT *NewBB) {
579  if (IsPostDominator)
580  Split<Inverse<NodeT *>>(NewBB);
581  else
582  Split<NodeT *>(NewBB);
583  }
584 
585  /// print - Convert to human readable form
586  ///
587  void print(raw_ostream &O) const {
588  O << "=============================--------------------------------\n";
589  if (this->isPostDominator())
590  O << "Inorder PostDominator Tree: ";
591  else
592  O << "Inorder Dominator Tree: ";
593  if (!DFSInfoValid)
594  O << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
595  O << "\n";
596 
597  // The postdom tree can have a null root if there are no returns.
598  if (getRootNode()) PrintDomTree<NodeT>(getRootNode(), O, 1);
599  }
600 
601 public:
602  /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
603  /// dominator tree in dfs order.
604  void updateDFSNumbers() const {
605  if (DFSInfoValid) {
606  SlowQueries = 0;
607  return;
608  }
609 
610  unsigned DFSNum = 0;
611 
614  32> WorkStack;
615 
616  const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
617 
618  if (!ThisRoot)
619  return;
620 
621  // Even in the case of multiple exits that form the post dominator root
622  // nodes, do not iterate over all exits, but start from the virtual root
623  // node. Otherwise bbs, that are not post dominated by any exit but by the
624  // virtual root node, will never be assigned a DFS number.
625  WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
626  ThisRoot->DFSNumIn = DFSNum++;
627 
628  while (!WorkStack.empty()) {
629  const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
630  typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
631  WorkStack.back().second;
632 
633  // If we visited all of the children of this node, "recurse" back up the
634  // stack setting the DFOutNum.
635  if (ChildIt == Node->end()) {
636  Node->DFSNumOut = DFSNum++;
637  WorkStack.pop_back();
638  } else {
639  // Otherwise, recursively visit this child.
640  const DomTreeNodeBase<NodeT> *Child = *ChildIt;
641  ++WorkStack.back().second;
642 
643  WorkStack.push_back(std::make_pair(Child, Child->begin()));
644  Child->DFSNumIn = DFSNum++;
645  }
646  }
647 
648  SlowQueries = 0;
649  DFSInfoValid = true;
650  }
651 
652  /// recalculate - compute a dominator tree for the given function
653  template <class FT> void recalculate(FT &F) {
654  using TraitsTy = GraphTraits<FT *>;
655  reset();
656  Parent = &F;
657 
658  if (!IsPostDominator) {
659  // Initialize root
660  NodeT *entry = TraitsTy::getEntryNode(&F);
661  addRoot(entry);
662  } else {
663  // Initialize the roots list
664  for (auto *Node : nodes(&F))
665  if (TraitsTy::child_begin(Node) == TraitsTy::child_end(Node))
666  addRoot(Node);
667  }
668 
669  DomTreeBuilder::Calculate(*this, F);
670  }
671 
672  /// verify - check parent and sibling property
673  bool verify() const { return DomTreeBuilder::Verify(*this); }
674 
675  protected:
676  void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
677 
678  void reset() {
679  DomTreeNodes.clear();
680  Roots.clear();
681  RootNode = nullptr;
682  Parent = nullptr;
683  DFSInfoValid = false;
684  SlowQueries = 0;
685  }
686 
687  // NewBB is split and now it has one successor. Update dominator tree to
688  // reflect this change.
689  template <class N>
690  void Split(typename GraphTraits<N>::NodeRef NewBB) {
691  using GraphT = GraphTraits<N>;
692  using NodeRef = typename GraphT::NodeRef;
693  assert(std::distance(GraphT::child_begin(NewBB),
694  GraphT::child_end(NewBB)) == 1 &&
695  "NewBB should have a single successor!");
696  NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
697 
698  std::vector<NodeRef> PredBlocks;
699  for (const auto &Pred : children<Inverse<N>>(NewBB))
700  PredBlocks.push_back(Pred);
701 
702  assert(!PredBlocks.empty() && "No predblocks?");
703 
704  bool NewBBDominatesNewBBSucc = true;
705  for (const auto &Pred : children<Inverse<N>>(NewBBSucc)) {
706  if (Pred != NewBB && !dominates(NewBBSucc, Pred) &&
707  isReachableFromEntry(Pred)) {
708  NewBBDominatesNewBBSucc = false;
709  break;
710  }
711  }
712 
713  // Find NewBB's immediate dominator and create new dominator tree node for
714  // NewBB.
715  NodeT *NewBBIDom = nullptr;
716  unsigned i = 0;
717  for (i = 0; i < PredBlocks.size(); ++i)
718  if (isReachableFromEntry(PredBlocks[i])) {
719  NewBBIDom = PredBlocks[i];
720  break;
721  }
722 
723  // It's possible that none of the predecessors of NewBB are reachable;
724  // in that case, NewBB itself is unreachable, so nothing needs to be
725  // changed.
726  if (!NewBBIDom) return;
727 
728  for (i = i + 1; i < PredBlocks.size(); ++i) {
729  if (isReachableFromEntry(PredBlocks[i]))
730  NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
731  }
732 
733  // Create the new dominator tree node... and set the idom of NewBB.
734  DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom);
735 
736  // If NewBB strictly dominates other blocks, then it is now the immediate
737  // dominator of NewBBSucc. Update the dominator tree as appropriate.
738  if (NewBBDominatesNewBBSucc) {
739  DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc);
740  changeImmediateDominator(NewBBSuccNode, NewBBNode);
741  }
742  }
743 
744  private:
745  bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
746  const DomTreeNodeBase<NodeT> *B) const {
747  assert(A != B);
750 
751  const DomTreeNodeBase<NodeT> *IDom;
752  while ((IDom = B->getIDom()) != nullptr && IDom != A && IDom != B)
753  B = IDom; // Walk up the tree
754  return IDom != nullptr;
755  }
756 
757  /// \brief Wipe this tree's state without releasing any resources.
758  ///
759  /// This is essentially a post-move helper only. It leaves the object in an
760  /// assignable and destroyable state, but otherwise invalid.
761  void wipe() {
762  DomTreeNodes.clear();
763  RootNode = nullptr;
764  Parent = nullptr;
765  }
766 };
767 
768 template <typename T>
770 
771 template <typename T>
773 
774 // These two functions are declared out of line as a workaround for building
775 // with old (< r147295) versions of clang because of pr11642.
776 template <typename NodeT, bool IsPostDom>
778  const NodeT *B) const {
779  if (A == B)
780  return true;
781 
782  // Cast away the const qualifiers here. This is ok since
783  // this function doesn't actually return the values returned
784  // from getNode.
785  return dominates(getNode(const_cast<NodeT *>(A)),
786  getNode(const_cast<NodeT *>(B)));
787 }
788 template <typename NodeT, bool IsPostDom>
790  const NodeT *A, const NodeT *B) const {
791  if (A == B)
792  return false;
793 
794  // Cast away the const qualifiers here. This is ok since
795  // this function doesn't actually return the values returned
796  // from getNode.
797  return dominates(getNode(const_cast<NodeT *>(A)),
798  getNode(const_cast<NodeT *>(B)));
799 }
800 
801 } // end namespace llvm
802 
803 #endif // LLVM_SUPPORT_GENERICDOMTREE_H
typename std::vector< DomTreeNodeBase * >::const_iterator const_iterator
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
Definition: GraphTraits.h:102
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
void Calculate(DomTreeT &DT, FuncT &F)
const_iterator end() const
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
unsigned getLevel() const
DomTreeNodeBase< NodeT > * RootNode
DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom)
void addRoot(NodeT *BB)
bool isVirtualRoot(const DomTreeNodeBase< NodeT > *A) const
DominatorTreeBase(DominatorTreeBase &&Arg)
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
const_iterator begin() const
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
const std::vector< DomTreeNodeBase * > & getChildren() const
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:663
bool isReachableFromEntry(const DomTreeNodeBase< NodeT > *A) const
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
bool verify() const
verify - check parent and sibling property
DomTreeNodeBase< NodeT > * operator[](NodeT *BB) const
See getNode.
#define F(x, y, z)
Definition: MD5.cpp:55
void PrintDomTree(const DomTreeNodeBase< NodeT > *N, raw_ostream &O, unsigned Lev)
void getDescendants(NodeT *R, SmallVectorImpl< NodeT * > &Result) const
Get all nodes dominated by R, including R itself.
DomTreeNodeBase * getIDom() const
Base class for the actual dominator tree node.
bool compare(const DominatorTreeBase &Other) const
compare - Return false if the other dominator tree base matches this dominator tree base...
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
NodeT * getBlock() const
Core dominator tree base class.
Definition: LoopInfo.h:60
Function Alias Analysis false
bool Verify(const DomTreeT &DT)
typename GraphType::UnknownGraphTypeError NodeRef
Definition: GraphTraits.h:59
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:943
void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
#define A
Definition: LargeTest.cpp:12
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree...
static constexpr bool IsPostDominator
void Split(typename GraphTraits< N >::NodeRef NewBB)
void insertEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge insertion and update the tree.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:839
#define B
Definition: LargeTest.cpp:24
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
const DomTreeNodeBase< NodeT > * getRootNode() const
const size_t N
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
DominatorTreeBase & operator=(DominatorTreeBase &&RHS)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
std::vector< NodeT * > Roots
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
bool compare(const DomTreeNodeBase *Other) const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:395
std::unique_ptr< DomTreeNodeBase > addChild(std::unique_ptr< DomTreeNodeBase > C)
unsigned getDFSNumOut() const
Basic Alias true
const NodeT * findNearestCommonDominator(const NodeT *A, const NodeT *B) const
iterator_range< typename GraphTraits< GraphType >::nodes_iterator > nodes(const GraphType &G)
Definition: GraphTraits.h:89
void print(raw_ostream &O) const
print - Convert to human readable form
#define C
Definition: LargeTest.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
decltype(std::declval< NodeT * >() ->getParent()) ParentPtr
DomTreeNodeMapType DomTreeNodes
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void changeImmediateDominator(NodeT *BB, NodeT *NewBB)
typename std::vector< DomTreeNodeBase * >::iterator iterator
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
static const Function * getParent(const Value *V)
void recalculate(FT &F)
recalculate - compute a dominator tree for the given function
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order...
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
bool isPostDominator() const
isPostDominator - Returns true if analysis based of postdoms
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
size_t getNumChildren() const
DenseMap< NodeT *, std::unique_ptr< DomTreeNodeBase< NodeT >>> DomTreeNodeMapType
const std::vector< NodeT * > & getRoots() const
getRoots - Return the root blocks of the current CFG.
NodeT * getRoot() const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
void setIDom(DomTreeNodeBase *NewIDom)