1 //===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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"
32 /// \brief Base class that other, more interesting dominator analyses
34 template <class NodeT> class DominatorBase {
36 std::vector<NodeT *> Roots;
37 const bool IsPostDominators;
38 inline explicit DominatorBase(bool isPostDom)
39 : Roots(), IsPostDominators(isPostDom) {}
42 /// getRoots - Return the root blocks of the current CFG. This may include
43 /// multiple blocks if we are computing post dominators. For forward
44 /// dominators, this will always be a single block (the entry node).
46 inline const std::vector<NodeT *> &getRoots() const { return Roots; }
48 /// isPostDominator - Returns true if analysis based of postdoms
50 bool isPostDominator() const { return IsPostDominators; }
53 template <class NodeT> class DominatorTreeBase;
54 struct PostDominatorTree;
56 /// \brief Base class for the actual dominator tree node.
57 template <class NodeT> class DomTreeNodeBase {
59 DomTreeNodeBase<NodeT> *IDom;
60 std::vector<DomTreeNodeBase<NodeT> *> Children;
61 mutable int DFSNumIn, DFSNumOut;
63 template <class N> friend class DominatorTreeBase;
64 friend struct PostDominatorTree;
67 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
68 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
71 iterator begin() { return Children.begin(); }
72 iterator end() { return Children.end(); }
73 const_iterator begin() const { return Children.begin(); }
74 const_iterator end() const { return Children.end(); }
76 NodeT *getBlock() const { return TheBB; }
77 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
78 const std::vector<DomTreeNodeBase<NodeT> *> &getChildren() const {
82 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
83 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) {}
85 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
86 Children.push_back(C);
90 size_t getNumChildren() const { return Children.size(); }
92 void clearAllChildren() { Children.clear(); }
94 bool compare(const DomTreeNodeBase<NodeT> *Other) const {
95 if (getNumChildren() != Other->getNumChildren())
98 SmallPtrSet<const NodeT *, 4> OtherChildren;
99 for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
100 const NodeT *Nd = (*I)->getBlock();
101 OtherChildren.insert(Nd);
104 for (const_iterator I = begin(), E = end(); I != E; ++I) {
105 const NodeT *N = (*I)->getBlock();
106 if (OtherChildren.count(N) == 0)
112 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
113 assert(IDom && "No immediate dominator?");
114 if (IDom != NewIDom) {
115 typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
116 std::find(IDom->Children.begin(), IDom->Children.end(), this);
117 assert(I != IDom->Children.end() &&
118 "Not in immediate dominator children set!");
119 // I am no longer your child...
120 IDom->Children.erase(I);
122 // Switch to new dominator
124 IDom->Children.push_back(this);
128 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
130 unsigned getDFSNumIn() const { return DFSNumIn; }
131 unsigned getDFSNumOut() const { return DFSNumOut; }
134 // Return true if this node is dominated by other. Use this only if DFS info
136 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
137 return this->DFSNumIn >= other->DFSNumIn &&
138 this->DFSNumOut <= other->DFSNumOut;
142 template <class NodeT>
143 inline raw_ostream &operator<<(raw_ostream &o,
144 const DomTreeNodeBase<NodeT> *Node) {
145 if (Node->getBlock())
146 Node->getBlock()->printAsOperand(o, false);
148 o << " <<exit node>>";
150 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
155 template <class NodeT>
156 inline void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
158 o.indent(2 * Lev) << "[" << Lev << "] " << N;
159 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
162 PrintDomTree<NodeT>(*I, o, Lev + 1);
165 // The calculate routine is provided in a separate header but referenced here.
166 template <class FuncT, class N>
167 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT,
170 /// \brief Core dominator tree base class.
172 /// This class is a generic template over graph nodes. It is instantiated for
173 /// various graphs in the LLVM IR or in the code generator.
174 template <class NodeT> class DominatorTreeBase : public DominatorBase<NodeT> {
175 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
176 const DomTreeNodeBase<NodeT> *B) const {
178 assert(isReachableFromEntry(B));
179 assert(isReachableFromEntry(A));
181 const DomTreeNodeBase<NodeT> *IDom;
182 while ((IDom = B->getIDom()) != nullptr && IDom != A && IDom != B)
183 B = IDom; // Walk up the tree
184 return IDom != nullptr;
188 typedef DenseMap<NodeT *, DomTreeNodeBase<NodeT> *> DomTreeNodeMapType;
189 DomTreeNodeMapType DomTreeNodes;
190 DomTreeNodeBase<NodeT> *RootNode;
192 mutable bool DFSInfoValid;
193 mutable unsigned int SlowQueries;
194 // Information record used during immediate dominators computation.
201 InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(nullptr) {}
204 DenseMap<NodeT *, NodeT *> IDoms;
206 // Vertex - Map the DFS number to the NodeT*
207 std::vector<NodeT *> Vertex;
209 // Info - Collection of information used during the computation of idoms.
210 DenseMap<NodeT *, InfoRec> Info;
213 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
214 E = DomTreeNodes.end();
217 DomTreeNodes.clear();
224 // NewBB is split and now it has one successor. Update dominator tree to
225 // reflect this change.
226 template <class N, class GraphT>
227 void Split(DominatorTreeBase<typename GraphT::NodeType> &DT,
228 typename GraphT::NodeType *NewBB) {
229 assert(std::distance(GraphT::child_begin(NewBB),
230 GraphT::child_end(NewBB)) == 1 &&
231 "NewBB should have a single successor!");
232 typename GraphT::NodeType *NewBBSucc = *GraphT::child_begin(NewBB);
234 std::vector<typename GraphT::NodeType *> PredBlocks;
235 typedef GraphTraits<Inverse<N>> InvTraits;
236 for (typename InvTraits::ChildIteratorType
237 PI = InvTraits::child_begin(NewBB),
238 PE = InvTraits::child_end(NewBB);
240 PredBlocks.push_back(*PI);
242 assert(!PredBlocks.empty() && "No predblocks?");
244 bool NewBBDominatesNewBBSucc = true;
245 for (typename InvTraits::ChildIteratorType
246 PI = InvTraits::child_begin(NewBBSucc),
247 E = InvTraits::child_end(NewBBSucc);
249 typename InvTraits::NodeType *ND = *PI;
250 if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
251 DT.isReachableFromEntry(ND)) {
252 NewBBDominatesNewBBSucc = false;
257 // Find NewBB's immediate dominator and create new dominator tree node for
259 NodeT *NewBBIDom = nullptr;
261 for (i = 0; i < PredBlocks.size(); ++i)
262 if (DT.isReachableFromEntry(PredBlocks[i])) {
263 NewBBIDom = PredBlocks[i];
267 // It's possible that none of the predecessors of NewBB are reachable;
268 // in that case, NewBB itself is unreachable, so nothing needs to be
273 for (i = i + 1; i < PredBlocks.size(); ++i) {
274 if (DT.isReachableFromEntry(PredBlocks[i]))
275 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
278 // Create the new dominator tree node... and set the idom of NewBB.
279 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
281 // If NewBB strictly dominates other blocks, then it is now the immediate
282 // dominator of NewBBSucc. Update the dominator tree as appropriate.
283 if (NewBBDominatesNewBBSucc) {
284 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
285 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
290 explicit DominatorTreeBase(bool isPostDom)
291 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
292 virtual ~DominatorTreeBase() { reset(); }
294 /// compare - Return false if the other dominator tree base matches this
295 /// dominator tree base. Otherwise return true.
296 bool compare(const DominatorTreeBase &Other) const {
298 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
299 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
302 for (typename DomTreeNodeMapType::const_iterator
303 I = this->DomTreeNodes.begin(),
304 E = this->DomTreeNodes.end();
306 NodeT *BB = I->first;
307 typename DomTreeNodeMapType::const_iterator OI =
308 OtherDomTreeNodes.find(BB);
309 if (OI == OtherDomTreeNodes.end())
312 DomTreeNodeBase<NodeT> *MyNd = I->second;
313 DomTreeNodeBase<NodeT> *OtherNd = OI->second;
315 if (MyNd->compare(OtherNd))
322 virtual void releaseMemory() { reset(); }
324 /// getNode - return the (Post)DominatorTree node for the specified basic
325 /// block. This is the same as using operator[] on this class.
327 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
328 return DomTreeNodes.lookup(BB);
331 inline DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const {
335 /// getRootNode - This returns the entry node for the CFG of the function. If
336 /// this tree represents the post-dominance relations for a function, however,
337 /// this root may be a node with the block == NULL. This is the case when
338 /// there are multiple exit nodes from a particular function. Consumers of
339 /// post-dominance information must be capable of dealing with this
342 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
343 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
345 /// Get all nodes dominated by R, including R itself.
346 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
348 const DomTreeNodeBase<NodeT> *RN = getNode(R);
350 return; // If R is unreachable, it will not be present in the DOM tree.
351 SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
354 while (!WL.empty()) {
355 const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
356 Result.push_back(N->getBlock());
357 WL.append(N->begin(), N->end());
361 /// properlyDominates - Returns true iff A dominates B and A != B.
362 /// Note that this is not a constant time operation!
364 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
365 const DomTreeNodeBase<NodeT> *B) const {
370 return dominates(A, B);
373 bool properlyDominates(const NodeT *A, const NodeT *B) const;
375 /// isReachableFromEntry - Return true if A is dominated by the entry
376 /// block of the function containing it.
377 bool isReachableFromEntry(const NodeT *A) const {
378 assert(!this->isPostDominator() &&
379 "This is not implemented for post dominators");
380 return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
383 inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
387 /// dominates - Returns true iff A dominates B. Note that this is not a
388 /// constant time operation!
390 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
391 const DomTreeNodeBase<NodeT> *B) const {
392 // A node trivially dominates itself.
396 // An unreachable node is dominated by anything.
397 if (!isReachableFromEntry(B))
400 // And dominates nothing.
401 if (!isReachableFromEntry(A))
404 // Compare the result of the tree walk and the dfs numbers, if expensive
405 // checks are enabled.
407 assert((!DFSInfoValid ||
408 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
409 "Tree walk disagrees with dfs numbers!");
413 return B->DominatedBy(A);
415 // If we end up with too many slow queries, just update the
416 // DFS numbers on the theory that we are going to keep querying.
418 if (SlowQueries > 32) {
420 return B->DominatedBy(A);
423 return dominatedBySlowTreeWalk(A, B);
426 bool dominates(const NodeT *A, const NodeT *B) const;
428 NodeT *getRoot() const {
429 assert(this->Roots.size() == 1 && "Should always have entry node!");
430 return this->Roots[0];
433 /// findNearestCommonDominator - Find nearest common dominator basic block
434 /// for basic block A and B. If there is no such block then return NULL.
435 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
436 assert(A->getParent() == B->getParent() &&
437 "Two blocks are not in same function");
439 // If either A or B is a entry block then it is nearest common dominator
440 // (for forward-dominators).
441 if (!this->isPostDominator()) {
442 NodeT &Entry = A->getParent()->front();
443 if (A == &Entry || B == &Entry)
447 // If B dominates A then B is nearest common dominator.
451 // If A dominates B then A is nearest common dominator.
455 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
456 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
458 // If we have DFS info, then we can avoid all allocations by just querying
459 // it from each IDom. Note that because we call 'dominates' twice above, we
460 // expect to call through this code at most 16 times in a row without
461 // building valid DFS information. This is important as below is a *very*
464 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
466 if (NodeB->DominatedBy(IDomA))
467 return IDomA->getBlock();
468 IDomA = IDomA->getIDom();
473 // Collect NodeA dominators set.
474 SmallPtrSet<DomTreeNodeBase<NodeT> *, 16> NodeADoms;
475 NodeADoms.insert(NodeA);
476 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
478 NodeADoms.insert(IDomA);
479 IDomA = IDomA->getIDom();
482 // Walk NodeB immediate dominators chain and find common dominator node.
483 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
485 if (NodeADoms.count(IDomB) != 0)
486 return IDomB->getBlock();
488 IDomB = IDomB->getIDom();
494 const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
495 // Cast away the const qualifiers here. This is ok since
496 // const is re-introduced on the return type.
497 return findNearestCommonDominator(const_cast<NodeT *>(A),
498 const_cast<NodeT *>(B));
501 //===--------------------------------------------------------------------===//
502 // API to update (Post)DominatorTree information based on modifications to
505 /// addNewBlock - Add a new node to the dominator tree information. This
506 /// creates a new node as a child of DomBB dominator node,linking it into
507 /// the children list of the immediate dominator.
508 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
509 assert(getNode(BB) == nullptr && "Block already in dominator tree!");
510 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
511 assert(IDomNode && "Not immediate dominator specified for block!");
512 DFSInfoValid = false;
513 return DomTreeNodes[BB] =
514 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
517 /// changeImmediateDominator - This method is used to update the dominator
518 /// tree information when a node's immediate dominator changes.
520 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
521 DomTreeNodeBase<NodeT> *NewIDom) {
522 assert(N && NewIDom && "Cannot change null node pointers!");
523 DFSInfoValid = false;
527 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
528 changeImmediateDominator(getNode(BB), getNode(NewBB));
531 /// eraseNode - Removes a node from the dominator tree. Block must not
532 /// dominate any other blocks. Removes node from its immediate dominator's
533 /// children list. Deletes dominator node associated with basic block BB.
534 void eraseNode(NodeT *BB) {
535 DomTreeNodeBase<NodeT> *Node = getNode(BB);
536 assert(Node && "Removing node that isn't in dominator tree.");
537 assert(Node->getChildren().empty() && "Node is not a leaf node.");
539 // Remove node from immediate dominator's children list.
540 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
542 typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
543 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
544 assert(I != IDom->Children.end() &&
545 "Not in immediate dominator children set!");
546 // I am no longer your child...
547 IDom->Children.erase(I);
550 DomTreeNodes.erase(BB);
554 /// removeNode - Removes a node from the dominator tree. Block must not
555 /// dominate any other blocks. Invalidates any node pointing to removed
557 void removeNode(NodeT *BB) {
558 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
559 DomTreeNodes.erase(BB);
562 /// splitBlock - BB is split and now it has one successor. Update dominator
563 /// tree to reflect this change.
564 void splitBlock(NodeT *NewBB) {
565 if (this->IsPostDominators)
566 this->Split<Inverse<NodeT *>, GraphTraits<Inverse<NodeT *>>>(*this,
569 this->Split<NodeT *, GraphTraits<NodeT *>>(*this, NewBB);
572 /// print - Convert to human readable form
574 void print(raw_ostream &o) const {
575 o << "=============================--------------------------------\n";
576 if (this->isPostDominator())
577 o << "Inorder PostDominator Tree: ";
579 o << "Inorder Dominator Tree: ";
580 if (!this->DFSInfoValid)
581 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
584 // The postdom tree can have a null root if there are no returns.
586 PrintDomTree<NodeT>(getRootNode(), o, 1);
590 template <class GraphT>
591 friend typename GraphT::NodeType *
592 Eval(DominatorTreeBase<typename GraphT::NodeType> &DT,
593 typename GraphT::NodeType *V, unsigned LastLinked);
595 template <class GraphT>
596 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType> &DT,
597 typename GraphT::NodeType *V, unsigned N);
599 template <class FuncT, class N>
601 Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT, FuncT &F);
603 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
604 /// dominator tree in dfs order.
605 void updateDFSNumbers() const {
608 SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
609 typename DomTreeNodeBase<NodeT>::const_iterator>,
612 const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
617 // Even in the case of multiple exits that form the post dominator root
618 // nodes, do not iterate over all exits, but start from the virtual root
619 // node. Otherwise bbs, that are not post dominated by any exit but by the
620 // virtual root node, will never be assigned a DFS number.
621 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
622 ThisRoot->DFSNumIn = DFSNum++;
624 while (!WorkStack.empty()) {
625 const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
626 typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
627 WorkStack.back().second;
629 // If we visited all of the children of this node, "recurse" back up the
630 // stack setting the DFOutNum.
631 if (ChildIt == Node->end()) {
632 Node->DFSNumOut = DFSNum++;
633 WorkStack.pop_back();
635 // Otherwise, recursively visit this child.
636 const DomTreeNodeBase<NodeT> *Child = *ChildIt;
637 ++WorkStack.back().second;
639 WorkStack.push_back(std::make_pair(Child, Child->begin()));
640 Child->DFSNumIn = DFSNum++;
648 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
649 if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
652 // Haven't calculated this node yet? Get or calculate the node for the
653 // immediate dominator.
654 NodeT *IDom = getIDom(BB);
656 assert(IDom || this->DomTreeNodes[nullptr]);
657 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
659 // Add a new tree node for this NodeT, and link it as a child of
661 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
662 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
665 inline NodeT *getIDom(NodeT *BB) const { return IDoms.lookup(BB); }
667 inline void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
670 /// recalculate - compute a dominator tree for the given function
671 template <class FT> void recalculate(FT &F) {
672 typedef GraphTraits<FT *> TraitsTy;
674 this->Vertex.push_back(nullptr);
676 if (!this->IsPostDominators) {
678 NodeT *entry = TraitsTy::getEntryNode(&F);
679 this->Roots.push_back(entry);
680 this->IDoms[entry] = nullptr;
681 this->DomTreeNodes[entry] = nullptr;
683 Calculate<FT, NodeT *>(*this, F);
685 // Initialize the roots list
686 for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
687 E = TraitsTy::nodes_end(&F);
689 if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
692 // Prepopulate maps so that we don't get iterator invalidation issues
694 this->IDoms[I] = nullptr;
695 this->DomTreeNodes[I] = nullptr;
698 Calculate<FT, Inverse<NodeT *>>(*this, F);
703 // These two functions are declared out of line as a workaround for building
704 // with old (< r147295) versions of clang because of pr11642.
705 template <class NodeT>
706 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) const {
710 // Cast away the const qualifiers here. This is ok since
711 // this function doesn't actually return the values returned
713 return dominates(getNode(const_cast<NodeT *>(A)),
714 getNode(const_cast<NodeT *>(B)));
716 template <class NodeT>
717 bool DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A,
718 const NodeT *B) const {
722 // Cast away the const qualifiers here. This is ok since
723 // this function doesn't actually return the values returned
725 return dominates(getNode(const_cast<NodeT *>(A)),
726 getNode(const_cast<NodeT *>(B)));