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