GenericDomTree.h revision ebe69fe11e48d322045d5949c83283927a0d790b
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//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_SUPPORT_GENERICDOMTREE_H
19#define LLVM_SUPPORT_GENERICDOMTREE_H
20
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/DepthFirstIterator.h"
23#include "llvm/ADT/GraphTraits.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30
31namespace llvm {
32
33/// \brief Base class that other, more interesting dominator analyses
34/// inherit from.
35template <class NodeT> class DominatorBase {
36protected:
37  std::vector<NodeT *> Roots;
38  bool IsPostDominators;
39  explicit DominatorBase(bool isPostDom)
40      : Roots(), IsPostDominators(isPostDom) {}
41  DominatorBase(DominatorBase &&Arg)
42      : Roots(std::move(Arg.Roots)),
43        IsPostDominators(std::move(Arg.IsPostDominators)) {
44    Arg.Roots.clear();
45  }
46  DominatorBase &operator=(DominatorBase &&RHS) {
47    Roots = std::move(RHS.Roots);
48    IsPostDominators = std::move(RHS.IsPostDominators);
49    RHS.Roots.clear();
50    return *this;
51  }
52
53public:
54  /// getRoots - Return the root blocks of the current CFG.  This may include
55  /// multiple blocks if we are computing post dominators.  For forward
56  /// dominators, this will always be a single block (the entry node).
57  ///
58  const std::vector<NodeT *> &getRoots() const { return Roots; }
59
60  /// isPostDominator - Returns true if analysis based of postdoms
61  ///
62  bool isPostDominator() const { return IsPostDominators; }
63};
64
65template <class NodeT> class DominatorTreeBase;
66struct PostDominatorTree;
67
68/// \brief Base class for the actual dominator tree node.
69template <class NodeT> class DomTreeNodeBase {
70  NodeT *TheBB;
71  DomTreeNodeBase<NodeT> *IDom;
72  std::vector<DomTreeNodeBase<NodeT> *> Children;
73  mutable int DFSNumIn, DFSNumOut;
74
75  template <class N> friend class DominatorTreeBase;
76  friend struct PostDominatorTree;
77
78public:
79  typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
80  typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
81      const_iterator;
82
83  iterator begin() { return Children.begin(); }
84  iterator end() { return Children.end(); }
85  const_iterator begin() const { return Children.begin(); }
86  const_iterator end() const { return Children.end(); }
87
88  NodeT *getBlock() const { return TheBB; }
89  DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
90  const std::vector<DomTreeNodeBase<NodeT> *> &getChildren() const {
91    return Children;
92  }
93
94  DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
95      : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) {}
96
97  std::unique_ptr<DomTreeNodeBase<NodeT>>
98  addChild(std::unique_ptr<DomTreeNodeBase<NodeT>> C) {
99    Children.push_back(C.get());
100    return C;
101  }
102
103  size_t getNumChildren() const { return Children.size(); }
104
105  void clearAllChildren() { Children.clear(); }
106
107  bool compare(const DomTreeNodeBase<NodeT> *Other) const {
108    if (getNumChildren() != Other->getNumChildren())
109      return true;
110
111    SmallPtrSet<const NodeT *, 4> OtherChildren;
112    for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
113      const NodeT *Nd = (*I)->getBlock();
114      OtherChildren.insert(Nd);
115    }
116
117    for (const_iterator I = begin(), E = end(); I != E; ++I) {
118      const NodeT *N = (*I)->getBlock();
119      if (OtherChildren.count(N) == 0)
120        return true;
121    }
122    return false;
123  }
124
125  void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
126    assert(IDom && "No immediate dominator?");
127    if (IDom != NewIDom) {
128      typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
129          std::find(IDom->Children.begin(), IDom->Children.end(), this);
130      assert(I != IDom->Children.end() &&
131             "Not in immediate dominator children set!");
132      // I am no longer your child...
133      IDom->Children.erase(I);
134
135      // Switch to new dominator
136      IDom = NewIDom;
137      IDom->Children.push_back(this);
138    }
139  }
140
141  /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
142  /// not call them.
143  unsigned getDFSNumIn() const { return DFSNumIn; }
144  unsigned getDFSNumOut() const { return DFSNumOut; }
145
146private:
147  // Return true if this node is dominated by other. Use this only if DFS info
148  // is valid.
149  bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
150    return this->DFSNumIn >= other->DFSNumIn &&
151           this->DFSNumOut <= other->DFSNumOut;
152  }
153};
154
155template <class NodeT>
156raw_ostream &operator<<(raw_ostream &o, const DomTreeNodeBase<NodeT> *Node) {
157  if (Node->getBlock())
158    Node->getBlock()->printAsOperand(o, false);
159  else
160    o << " <<exit node>>";
161
162  o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
163
164  return o << "\n";
165}
166
167template <class NodeT>
168void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
169                  unsigned Lev) {
170  o.indent(2 * Lev) << "[" << Lev << "] " << N;
171  for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
172                                                       E = N->end();
173       I != E; ++I)
174    PrintDomTree<NodeT>(*I, o, Lev + 1);
175}
176
177// The calculate routine is provided in a separate header but referenced here.
178template <class FuncT, class N>
179void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT,
180               FuncT &F);
181
182/// \brief Core dominator tree base class.
183///
184/// This class is a generic template over graph nodes. It is instantiated for
185/// various graphs in the LLVM IR or in the code generator.
186template <class NodeT> class DominatorTreeBase : public DominatorBase<NodeT> {
187  DominatorTreeBase(const DominatorTreeBase &) = delete;
188  DominatorTreeBase &operator=(const DominatorTreeBase &) = delete;
189
190  bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
191                               const DomTreeNodeBase<NodeT> *B) const {
192    assert(A != B);
193    assert(isReachableFromEntry(B));
194    assert(isReachableFromEntry(A));
195
196    const DomTreeNodeBase<NodeT> *IDom;
197    while ((IDom = B->getIDom()) != nullptr && IDom != A && IDom != B)
198      B = IDom; // Walk up the tree
199    return IDom != nullptr;
200  }
201
202  /// \brief Wipe this tree's state without releasing any resources.
203  ///
204  /// This is essentially a post-move helper only. It leaves the object in an
205  /// assignable and destroyable state, but otherwise invalid.
206  void wipe() {
207    DomTreeNodes.clear();
208    IDoms.clear();
209    Vertex.clear();
210    Info.clear();
211    RootNode = nullptr;
212  }
213
214protected:
215  typedef DenseMap<NodeT *, std::unique_ptr<DomTreeNodeBase<NodeT>>>
216      DomTreeNodeMapType;
217  DomTreeNodeMapType DomTreeNodes;
218  DomTreeNodeBase<NodeT> *RootNode;
219
220  mutable bool DFSInfoValid;
221  mutable unsigned int SlowQueries;
222  // Information record used during immediate dominators computation.
223  struct InfoRec {
224    unsigned DFSNum;
225    unsigned Parent;
226    unsigned Semi;
227    NodeT *Label;
228
229    InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(nullptr) {}
230  };
231
232  DenseMap<NodeT *, NodeT *> IDoms;
233
234  // Vertex - Map the DFS number to the NodeT*
235  std::vector<NodeT *> Vertex;
236
237  // Info - Collection of information used during the computation of idoms.
238  DenseMap<NodeT *, InfoRec> Info;
239
240  void reset() {
241    DomTreeNodes.clear();
242    IDoms.clear();
243    this->Roots.clear();
244    Vertex.clear();
245    RootNode = nullptr;
246  }
247
248  // NewBB is split and now it has one successor. Update dominator tree to
249  // reflect this change.
250  template <class N, class GraphT>
251  void Split(DominatorTreeBase<typename GraphT::NodeType> &DT,
252             typename GraphT::NodeType *NewBB) {
253    assert(std::distance(GraphT::child_begin(NewBB),
254                         GraphT::child_end(NewBB)) == 1 &&
255           "NewBB should have a single successor!");
256    typename GraphT::NodeType *NewBBSucc = *GraphT::child_begin(NewBB);
257
258    std::vector<typename GraphT::NodeType *> PredBlocks;
259    typedef GraphTraits<Inverse<N>> InvTraits;
260    for (typename InvTraits::ChildIteratorType
261             PI = InvTraits::child_begin(NewBB),
262             PE = InvTraits::child_end(NewBB);
263         PI != PE; ++PI)
264      PredBlocks.push_back(*PI);
265
266    assert(!PredBlocks.empty() && "No predblocks?");
267
268    bool NewBBDominatesNewBBSucc = true;
269    for (typename InvTraits::ChildIteratorType
270             PI = InvTraits::child_begin(NewBBSucc),
271             E = InvTraits::child_end(NewBBSucc);
272         PI != E; ++PI) {
273      typename InvTraits::NodeType *ND = *PI;
274      if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
275          DT.isReachableFromEntry(ND)) {
276        NewBBDominatesNewBBSucc = false;
277        break;
278      }
279    }
280
281    // Find NewBB's immediate dominator and create new dominator tree node for
282    // NewBB.
283    NodeT *NewBBIDom = nullptr;
284    unsigned i = 0;
285    for (i = 0; i < PredBlocks.size(); ++i)
286      if (DT.isReachableFromEntry(PredBlocks[i])) {
287        NewBBIDom = PredBlocks[i];
288        break;
289      }
290
291    // It's possible that none of the predecessors of NewBB are reachable;
292    // in that case, NewBB itself is unreachable, so nothing needs to be
293    // changed.
294    if (!NewBBIDom)
295      return;
296
297    for (i = i + 1; i < PredBlocks.size(); ++i) {
298      if (DT.isReachableFromEntry(PredBlocks[i]))
299        NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
300    }
301
302    // Create the new dominator tree node... and set the idom of NewBB.
303    DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
304
305    // If NewBB strictly dominates other blocks, then it is now the immediate
306    // dominator of NewBBSucc.  Update the dominator tree as appropriate.
307    if (NewBBDominatesNewBBSucc) {
308      DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
309      DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
310    }
311  }
312
313public:
314  explicit DominatorTreeBase(bool isPostDom)
315      : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
316
317  DominatorTreeBase(DominatorTreeBase &&Arg)
318      : DominatorBase<NodeT>(
319            std::move(static_cast<DominatorBase<NodeT> &>(Arg))),
320        DomTreeNodes(std::move(Arg.DomTreeNodes)),
321        RootNode(std::move(Arg.RootNode)),
322        DFSInfoValid(std::move(Arg.DFSInfoValid)),
323        SlowQueries(std::move(Arg.SlowQueries)), IDoms(std::move(Arg.IDoms)),
324        Vertex(std::move(Arg.Vertex)), Info(std::move(Arg.Info)) {
325    Arg.wipe();
326  }
327  DominatorTreeBase &operator=(DominatorTreeBase &&RHS) {
328    DominatorBase<NodeT>::operator=(
329        std::move(static_cast<DominatorBase<NodeT> &>(RHS)));
330    DomTreeNodes = std::move(RHS.DomTreeNodes);
331    RootNode = std::move(RHS.RootNode);
332    DFSInfoValid = std::move(RHS.DFSInfoValid);
333    SlowQueries = std::move(RHS.SlowQueries);
334    IDoms = std::move(RHS.IDoms);
335    Vertex = std::move(RHS.Vertex);
336    Info = std::move(RHS.Info);
337    RHS.wipe();
338    return *this;
339  }
340
341  /// compare - Return false if the other dominator tree base matches this
342  /// dominator tree base. Otherwise return true.
343  bool compare(const DominatorTreeBase &Other) const {
344
345    const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
346    if (DomTreeNodes.size() != OtherDomTreeNodes.size())
347      return true;
348
349    for (typename DomTreeNodeMapType::const_iterator
350             I = this->DomTreeNodes.begin(),
351             E = this->DomTreeNodes.end();
352         I != E; ++I) {
353      NodeT *BB = I->first;
354      typename DomTreeNodeMapType::const_iterator OI =
355          OtherDomTreeNodes.find(BB);
356      if (OI == OtherDomTreeNodes.end())
357        return true;
358
359      DomTreeNodeBase<NodeT> &MyNd = *I->second;
360      DomTreeNodeBase<NodeT> &OtherNd = *OI->second;
361
362      if (MyNd.compare(&OtherNd))
363        return true;
364    }
365
366    return false;
367  }
368
369  void releaseMemory() { reset(); }
370
371  /// getNode - return the (Post)DominatorTree node for the specified basic
372  /// block.  This is the same as using operator[] on this class.
373  ///
374  DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
375    auto I = DomTreeNodes.find(BB);
376    if (I != DomTreeNodes.end())
377      return I->second.get();
378    return nullptr;
379  }
380
381  DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const { return getNode(BB); }
382
383  /// getRootNode - This returns the entry node for the CFG of the function.  If
384  /// this tree represents the post-dominance relations for a function, however,
385  /// this root may be a node with the block == NULL.  This is the case when
386  /// there are multiple exit nodes from a particular function.  Consumers of
387  /// post-dominance information must be capable of dealing with this
388  /// possibility.
389  ///
390  DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
391  const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
392
393  /// Get all nodes dominated by R, including R itself.
394  void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
395    Result.clear();
396    const DomTreeNodeBase<NodeT> *RN = getNode(R);
397    if (!RN)
398      return; // If R is unreachable, it will not be present in the DOM tree.
399    SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
400    WL.push_back(RN);
401
402    while (!WL.empty()) {
403      const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
404      Result.push_back(N->getBlock());
405      WL.append(N->begin(), N->end());
406    }
407  }
408
409  /// properlyDominates - Returns true iff A dominates B and A != B.
410  /// Note that this is not a constant time operation!
411  ///
412  bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
413                         const DomTreeNodeBase<NodeT> *B) const {
414    if (!A || !B)
415      return false;
416    if (A == B)
417      return false;
418    return dominates(A, B);
419  }
420
421  bool properlyDominates(const NodeT *A, const NodeT *B) const;
422
423  /// isReachableFromEntry - Return true if A is dominated by the entry
424  /// block of the function containing it.
425  bool isReachableFromEntry(const NodeT *A) const {
426    assert(!this->isPostDominator() &&
427           "This is not implemented for post dominators");
428    return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
429  }
430
431  bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
432
433  /// dominates - Returns true iff A dominates B.  Note that this is not a
434  /// constant time operation!
435  ///
436  bool dominates(const DomTreeNodeBase<NodeT> *A,
437                 const DomTreeNodeBase<NodeT> *B) const {
438    // A node trivially dominates itself.
439    if (B == A)
440      return true;
441
442    // An unreachable node is dominated by anything.
443    if (!isReachableFromEntry(B))
444      return true;
445
446    // And dominates nothing.
447    if (!isReachableFromEntry(A))
448      return false;
449
450    // Compare the result of the tree walk and the dfs numbers, if expensive
451    // checks are enabled.
452#ifdef XDEBUG
453    assert((!DFSInfoValid ||
454            (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
455           "Tree walk disagrees with dfs numbers!");
456#endif
457
458    if (DFSInfoValid)
459      return B->DominatedBy(A);
460
461    // If we end up with too many slow queries, just update the
462    // DFS numbers on the theory that we are going to keep querying.
463    SlowQueries++;
464    if (SlowQueries > 32) {
465      updateDFSNumbers();
466      return B->DominatedBy(A);
467    }
468
469    return dominatedBySlowTreeWalk(A, B);
470  }
471
472  bool dominates(const NodeT *A, const NodeT *B) const;
473
474  NodeT *getRoot() const {
475    assert(this->Roots.size() == 1 && "Should always have entry node!");
476    return this->Roots[0];
477  }
478
479  /// findNearestCommonDominator - Find nearest common dominator basic block
480  /// for basic block A and B. If there is no such block then return NULL.
481  NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
482    assert(A->getParent() == B->getParent() &&
483           "Two blocks are not in same function");
484
485    // If either A or B is a entry block then it is nearest common dominator
486    // (for forward-dominators).
487    if (!this->isPostDominator()) {
488      NodeT &Entry = A->getParent()->front();
489      if (A == &Entry || B == &Entry)
490        return &Entry;
491    }
492
493    // If B dominates A then B is nearest common dominator.
494    if (dominates(B, A))
495      return B;
496
497    // If A dominates B then A is nearest common dominator.
498    if (dominates(A, B))
499      return A;
500
501    DomTreeNodeBase<NodeT> *NodeA = getNode(A);
502    DomTreeNodeBase<NodeT> *NodeB = getNode(B);
503
504    // If we have DFS info, then we can avoid all allocations by just querying
505    // it from each IDom. Note that because we call 'dominates' twice above, we
506    // expect to call through this code at most 16 times in a row without
507    // building valid DFS information. This is important as below is a *very*
508    // slow tree walk.
509    if (DFSInfoValid) {
510      DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
511      while (IDomA) {
512        if (NodeB->DominatedBy(IDomA))
513          return IDomA->getBlock();
514        IDomA = IDomA->getIDom();
515      }
516      return nullptr;
517    }
518
519    // Collect NodeA dominators set.
520    SmallPtrSet<DomTreeNodeBase<NodeT> *, 16> NodeADoms;
521    NodeADoms.insert(NodeA);
522    DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
523    while (IDomA) {
524      NodeADoms.insert(IDomA);
525      IDomA = IDomA->getIDom();
526    }
527
528    // Walk NodeB immediate dominators chain and find common dominator node.
529    DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
530    while (IDomB) {
531      if (NodeADoms.count(IDomB) != 0)
532        return IDomB->getBlock();
533
534      IDomB = IDomB->getIDom();
535    }
536
537    return nullptr;
538  }
539
540  const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
541    // Cast away the const qualifiers here. This is ok since
542    // const is re-introduced on the return type.
543    return findNearestCommonDominator(const_cast<NodeT *>(A),
544                                      const_cast<NodeT *>(B));
545  }
546
547  //===--------------------------------------------------------------------===//
548  // API to update (Post)DominatorTree information based on modifications to
549  // the CFG...
550
551  /// addNewBlock - Add a new node to the dominator tree information.  This
552  /// creates a new node as a child of DomBB dominator node,linking it into
553  /// the children list of the immediate dominator.
554  DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
555    assert(getNode(BB) == nullptr && "Block already in dominator tree!");
556    DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
557    assert(IDomNode && "Not immediate dominator specified for block!");
558    DFSInfoValid = false;
559    return (DomTreeNodes[BB] = IDomNode->addChild(
560                llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, IDomNode))).get();
561  }
562
563  /// changeImmediateDominator - This method is used to update the dominator
564  /// tree information when a node's immediate dominator changes.
565  ///
566  void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
567                                DomTreeNodeBase<NodeT> *NewIDom) {
568    assert(N && NewIDom && "Cannot change null node pointers!");
569    DFSInfoValid = false;
570    N->setIDom(NewIDom);
571  }
572
573  void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
574    changeImmediateDominator(getNode(BB), getNode(NewBB));
575  }
576
577  /// eraseNode - Removes a node from the dominator tree. Block must not
578  /// dominate any other blocks. Removes node from its immediate dominator's
579  /// children list. Deletes dominator node associated with basic block BB.
580  void eraseNode(NodeT *BB) {
581    DomTreeNodeBase<NodeT> *Node = getNode(BB);
582    assert(Node && "Removing node that isn't in dominator tree.");
583    assert(Node->getChildren().empty() && "Node is not a leaf node.");
584
585    // Remove node from immediate dominator's children list.
586    DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
587    if (IDom) {
588      typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
589          std::find(IDom->Children.begin(), IDom->Children.end(), Node);
590      assert(I != IDom->Children.end() &&
591             "Not in immediate dominator children set!");
592      // I am no longer your child...
593      IDom->Children.erase(I);
594    }
595
596    DomTreeNodes.erase(BB);
597  }
598
599  /// splitBlock - BB is split and now it has one successor. Update dominator
600  /// tree to reflect this change.
601  void splitBlock(NodeT *NewBB) {
602    if (this->IsPostDominators)
603      this->Split<Inverse<NodeT *>, GraphTraits<Inverse<NodeT *>>>(*this,
604                                                                   NewBB);
605    else
606      this->Split<NodeT *, GraphTraits<NodeT *>>(*this, NewBB);
607  }
608
609  /// print - Convert to human readable form
610  ///
611  void print(raw_ostream &o) const {
612    o << "=============================--------------------------------\n";
613    if (this->isPostDominator())
614      o << "Inorder PostDominator Tree: ";
615    else
616      o << "Inorder Dominator Tree: ";
617    if (!this->DFSInfoValid)
618      o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
619    o << "\n";
620
621    // The postdom tree can have a null root if there are no returns.
622    if (getRootNode())
623      PrintDomTree<NodeT>(getRootNode(), o, 1);
624  }
625
626protected:
627  template <class GraphT>
628  friend typename GraphT::NodeType *
629  Eval(DominatorTreeBase<typename GraphT::NodeType> &DT,
630       typename GraphT::NodeType *V, unsigned LastLinked);
631
632  template <class GraphT>
633  friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType> &DT,
634                          typename GraphT::NodeType *V, unsigned N);
635
636  template <class FuncT, class N>
637  friend void
638  Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT, FuncT &F);
639
640  /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
641  /// dominator tree in dfs order.
642  void updateDFSNumbers() const {
643    unsigned DFSNum = 0;
644
645    SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
646                          typename DomTreeNodeBase<NodeT>::const_iterator>,
647                32> WorkStack;
648
649    const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
650
651    if (!ThisRoot)
652      return;
653
654    // Even in the case of multiple exits that form the post dominator root
655    // nodes, do not iterate over all exits, but start from the virtual root
656    // node. Otherwise bbs, that are not post dominated by any exit but by the
657    // virtual root node, will never be assigned a DFS number.
658    WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
659    ThisRoot->DFSNumIn = DFSNum++;
660
661    while (!WorkStack.empty()) {
662      const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
663      typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
664          WorkStack.back().second;
665
666      // If we visited all of the children of this node, "recurse" back up the
667      // stack setting the DFOutNum.
668      if (ChildIt == Node->end()) {
669        Node->DFSNumOut = DFSNum++;
670        WorkStack.pop_back();
671      } else {
672        // Otherwise, recursively visit this child.
673        const DomTreeNodeBase<NodeT> *Child = *ChildIt;
674        ++WorkStack.back().second;
675
676        WorkStack.push_back(std::make_pair(Child, Child->begin()));
677        Child->DFSNumIn = DFSNum++;
678      }
679    }
680
681    SlowQueries = 0;
682    DFSInfoValid = true;
683  }
684
685  DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
686    if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
687      return Node;
688
689    // Haven't calculated this node yet?  Get or calculate the node for the
690    // immediate dominator.
691    NodeT *IDom = getIDom(BB);
692
693    assert(IDom || this->DomTreeNodes[nullptr]);
694    DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
695
696    // Add a new tree node for this NodeT, and link it as a child of
697    // IDomNode
698    return (this->DomTreeNodes[BB] = IDomNode->addChild(
699                llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, IDomNode))).get();
700  }
701
702  NodeT *getIDom(NodeT *BB) const { return IDoms.lookup(BB); }
703
704  void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
705
706public:
707  /// recalculate - compute a dominator tree for the given function
708  template <class FT> void recalculate(FT &F) {
709    typedef GraphTraits<FT *> TraitsTy;
710    reset();
711    this->Vertex.push_back(nullptr);
712
713    if (!this->IsPostDominators) {
714      // Initialize root
715      NodeT *entry = TraitsTy::getEntryNode(&F);
716      this->Roots.push_back(entry);
717      this->IDoms[entry] = nullptr;
718      this->DomTreeNodes[entry] = nullptr;
719
720      Calculate<FT, NodeT *>(*this, F);
721    } else {
722      // Initialize the roots list
723      for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
724                                             E = TraitsTy::nodes_end(&F);
725           I != E; ++I) {
726        if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
727          addRoot(I);
728
729        // Prepopulate maps so that we don't get iterator invalidation issues
730        // later.
731        this->IDoms[I] = nullptr;
732        this->DomTreeNodes[I] = nullptr;
733      }
734
735      Calculate<FT, Inverse<NodeT *>>(*this, F);
736    }
737  }
738};
739
740// These two functions are declared out of line as a workaround for building
741// with old (< r147295) versions of clang because of pr11642.
742template <class NodeT>
743bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) const {
744  if (A == B)
745    return true;
746
747  // Cast away the const qualifiers here. This is ok since
748  // this function doesn't actually return the values returned
749  // from getNode.
750  return dominates(getNode(const_cast<NodeT *>(A)),
751                   getNode(const_cast<NodeT *>(B)));
752}
753template <class NodeT>
754bool DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A,
755                                                 const NodeT *B) const {
756  if (A == B)
757    return false;
758
759  // Cast away the const qualifiers here. This is ok since
760  // this function doesn't actually return the values returned
761  // from getNode.
762  return dominates(getNode(const_cast<NodeT *>(A)),
763                   getNode(const_cast<NodeT *>(B)));
764}
765
766}
767
768#endif
769