LLVM 23.0.0git
GenericDomTree.h
Go to the documentation of this file.
1//===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// This file defines a set of templates that efficiently compute a dominator
11/// tree over a generic graph. This is used typically in LLVM for fast
12/// dominance queries on the CFG, but is fully generic w.r.t. the underlying
13/// graph types.
14///
15/// Unlike ADT/* graph algorithms, generic dominator tree has more requirements
16/// on the graph's NodeRef. The NodeRef should be a pointer and,
17/// either NodeRef->getParent() must return the parent node that is also a
18/// pointer or DomTreeNodeTraits needs to be specialized.
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"
29#include "llvm/ADT/STLExtras.h"
35#include <algorithm>
36#include <cassert>
37#include <cstddef>
38#include <memory>
39#include <type_traits>
40#include <utility>
41
42namespace llvm {
43
44template <typename NodeT, bool IsPostDom>
46
47namespace DomTreeBuilder {
48template <typename DomTreeT>
49struct SemiNCAInfo;
50} // namespace DomTreeBuilder
51
52/// Base class for the actual dominator tree node.
53template <class NodeT> class DomTreeNodeBase {
54 friend class PostDominatorTree;
55 friend class DominatorTreeBase<NodeT, false>;
56 friend class DominatorTreeBase<NodeT, true>;
59
60 NodeT *TheBB;
61 DomTreeNodeBase *IDom;
62 unsigned Level;
63 DomTreeNodeBase *FirstChild = nullptr;
64 DomTreeNodeBase *Sibling = nullptr;
65 DomTreeNodeBase **AppendPtr = &FirstChild;
66 mutable unsigned DFSNumIn = ~0;
67 mutable unsigned DFSNumOut = ~0;
68
69 public:
71 : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {}
72
75
77 : public iterator_facade_base<const_iterator, std::forward_iterator_tag,
78 DomTreeNodeBase *> {
79 DomTreeNodeBase *Node;
80
81 public:
82 const_iterator(DomTreeNodeBase *Node = nullptr) : Node(Node) {}
83 bool operator==(const const_iterator &Other) const {
84 return Other.Node == Node;
85 }
86 DomTreeNodeBase *operator*() const { return Node; }
88 Node = Node->Sibling;
89 return *this;
90 }
92 const_iterator cp = *this;
93 ++*this;
94 return cp;
95 }
96 };
97 // We don't permit modifications through the iterator.
98 using iterator = const_iterator;
99
100 iterator begin() const { return iterator{FirstChild}; }
101 iterator end() const { return iterator{}; }
102
105 return make_range(begin(), end());
106 }
107
108 NodeT *getBlock() const { return TheBB; }
109 DomTreeNodeBase *getIDom() const { return IDom; }
110 unsigned getLevel() const { return Level; }
111
112 // TODO: make these private once NewGVN doesn't require these anymore.
114 assert(!C->Sibling && "cannot add child that already has siblings");
115 assert(!*AppendPtr && "sibling of last child must be nullptr");
116 *AppendPtr = C;
117 AppendPtr = &C->Sibling;
118 }
119
120 // TODO: make these private once NewGVN doesn't require these anymore.
122 DomTreeNodeBase **It = &FirstChild;
123 while (*It != C) {
124 assert(*It != nullptr && "Not in immediate dominator children list!");
125 It = &(*It)->Sibling;
126 }
127 assert(!*AppendPtr && "sibling of last child must be nullptr");
128 assert(C->Sibling || AppendPtr == &C->Sibling);
129 *It = C->Sibling;
130 if (C->Sibling)
131 C->Sibling = nullptr;
132 else
133 AppendPtr = It;
134 }
135
136 bool isLeaf() const { return FirstChild == nullptr; }
137
138 bool compare(const DomTreeNodeBase *Other) const {
139 if (Level != Other->Level) return true;
140
141 SmallPtrSet<const NodeT *, 4> OtherChildren;
142 for (const DomTreeNodeBase *I : *Other) {
143 const NodeT *Nd = I->getBlock();
144 OtherChildren.insert(Nd);
145 }
146
147 size_t OwnCount = 0;
148 for (const DomTreeNodeBase *I : *this) {
149 const NodeT *N = I->getBlock();
150 if (OtherChildren.count(N) == 0)
151 return true;
152 ++OwnCount;
153 }
154 return OwnCount != OtherChildren.size();
155 }
156
157 void setIDom(DomTreeNodeBase *NewIDom) {
158 assert(IDom && "No immediate dominator?");
159 if (IDom == NewIDom) return;
160 IDom->removeChild(this);
161
162 // Switch to new dominator
163 IDom = NewIDom;
164 IDom->addChild(this);
165
166 UpdateLevel();
167 }
168
169 /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
170 /// in the dominator tree. They are only guaranteed valid if
171 /// updateDFSNumbers() has been called.
172 unsigned getDFSNumIn() const { return DFSNumIn; }
173 unsigned getDFSNumOut() const { return DFSNumOut; }
174
175private:
176 // Return true if this node is dominated by other. Use this only if DFS info
177 // is valid.
178 bool DominatedBy(const DomTreeNodeBase *other) const {
179 return this->DFSNumIn >= other->DFSNumIn &&
180 this->DFSNumOut <= other->DFSNumOut;
181 }
182
183 void UpdateLevel() {
184 assert(IDom);
185 if (Level == IDom->Level + 1) return;
186
187 SmallVector<DomTreeNodeBase *, 64> WorkStack = {this};
188
189 while (!WorkStack.empty()) {
190 DomTreeNodeBase *Current = WorkStack.pop_back_val();
191 Current->Level = Current->IDom->Level + 1;
192
193 for (DomTreeNodeBase *C : *Current) {
194 assert(C->IDom);
195 if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C);
196 }
197 }
198 }
199};
200
201template <class NodeT>
203 if (Node->getBlock())
204 Node->getBlock()->printAsOperand(O, false);
205 else
206 O << " <<exit node>>";
207
208 O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} ["
209 << Node->getLevel() << "]\n";
210
211 return O;
212}
213
214template <class NodeT>
216 unsigned Lev) {
217 O.indent(2 * Lev) << "[" << Lev << "] " << N;
218 for (const auto &I : *N)
219 PrintDomTree<NodeT>(I, O, Lev + 1);
220}
221
222namespace DomTreeBuilder {
223// The routines below are provided in a separate header but referenced here.
224template <typename DomTreeT>
225void Calculate(DomTreeT &DT);
226
227template <typename DomTreeT>
228void CalculateWithUpdates(DomTreeT &DT,
230
231template <typename DomTreeT>
232void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
233 typename DomTreeT::NodePtr To);
234
235template <typename DomTreeT>
236void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
237 typename DomTreeT::NodePtr To);
238
239template <typename DomTreeT>
240void ApplyUpdates(DomTreeT &DT,
241 GraphDiff<typename DomTreeT::NodePtr,
242 DomTreeT::IsPostDominator> &PreViewCFG,
243 GraphDiff<typename DomTreeT::NodePtr,
244 DomTreeT::IsPostDominator> *PostViewCFG);
245
246template <typename DomTreeT>
247bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL);
248} // namespace DomTreeBuilder
249
250/// Default DomTreeNode traits for NodeT. The default implementation assume a
251/// Function-like NodeT. Can be specialized to support different node types.
252template <typename NodeT> struct DomTreeNodeTraits {
253 using NodeType = NodeT;
254 using NodePtr = NodeT *;
255 using ParentPtr = decltype(std::declval<NodePtr>()->getParent());
256 static_assert(std::is_pointer_v<ParentPtr>,
257 "Currently NodeT's parent must be a pointer type");
258 using ParentType = std::remove_pointer_t<ParentPtr>;
259
260 static NodeT *getEntryNode(ParentPtr Parent) { return &Parent->front(); }
261 static ParentPtr getParent(NodePtr BB) { return BB->getParent(); }
262};
263
264/// Core dominator tree base class.
265///
266/// This class is a generic template over graph nodes. It is instantiated for
267/// various graphs in the LLVM IR or in the code generator.
268template <typename NodeT, bool IsPostDom>
270 public:
271 static_assert(std::is_pointer_v<typename GraphTraits<NodeT *>::NodeRef>,
272 "Currently DominatorTreeBase supports only pointer nodes");
275 using NodePtr = typename NodeTrait::NodePtr;
277 static_assert(std::is_pointer_v<ParentPtr>,
278 "Currently NodeT's parent must be a pointer type");
279 using ParentType = std::remove_pointer_t<ParentPtr>;
280 static constexpr bool IsPostDominator = IsPostDom;
281
284 static constexpr UpdateKind Insert = UpdateKind::Insert;
285 static constexpr UpdateKind Delete = UpdateKind::Delete;
286
288
289protected:
290 // Dominators always have a single root, postdominators can have more.
292
296 // For graphs where blocks don't have numbers, create a numbering here.
297 // TODO: use an empty struct with [[no_unique_address]] in C++20.
298 std::conditional_t<!GraphHasNodeNumbers<NodeT *>,
302 ParentPtr Parent = nullptr;
303
304 mutable bool DFSInfoValid = false;
305 mutable unsigned int SlowQueries = 0;
306 unsigned BlockNumberEpoch = 0;
307
309
310 public:
311 DominatorTreeBase() = default;
312
315
318
319 /// Iteration over roots.
320 ///
321 /// This may include multiple blocks if we are computing post dominators.
322 /// For forward dominators, this will always be a single block (the entry
323 /// block).
326
327 root_iterator root_begin() { return Roots.begin(); }
328 const_root_iterator root_begin() const { return Roots.begin(); }
329 root_iterator root_end() { return Roots.end(); }
330 const_root_iterator root_end() const { return Roots.end(); }
331
332 size_t root_size() const { return Roots.size(); }
333
340
341 /// isPostDominator - Returns true if analysis based of postdoms
342 ///
343 bool isPostDominator() const { return IsPostDominator; }
344
345 /// compare - Return false if the other dominator tree base matches this
346 /// dominator tree base. Otherwise return true.
347 bool compare(const DominatorTreeBase &Other) const {
348 if (Parent != Other.Parent) return true;
349
350 if (Roots.size() != Other.Roots.size())
351 return true;
352
353 if (!std::is_permutation(Roots.begin(), Roots.end(), Other.Roots.begin()))
354 return true;
355
356 size_t NumNodes = 0;
357 // All nodes we have must exist and be equal in the other tree.
358 for (const auto &Node : DomTreeNodes) {
359 if (!Node)
360 continue;
361 if (Node->compare(Other.getNode(Node->getBlock())))
362 return true;
363 NumNodes++;
364 }
365
366 // If the other tree has more nodes than we have, they're not equal.
367 size_t NumOtherNodes = 0;
368 for (const auto &OtherNode : Other.DomTreeNodes)
369 if (OtherNode)
370 NumOtherNodes++;
371 return NumNodes != NumOtherNodes;
372 }
373
374private:
375 std::optional<unsigned> getNodeIndex(const NodeT *BB) const {
376 if constexpr (GraphHasNodeNumbers<NodeT *>) {
377 // BB can be nullptr, map nullptr to index 0.
380 "dominator tree used with outdated block numbers");
381 return BB ? GraphTraits<const NodeT *>::getNumber(BB) + 1 : 0;
382 } else {
383 if (auto It = NodeNumberMap.find(BB); It != NodeNumberMap.end())
384 return It->second;
385 return std::nullopt;
386 }
387 }
388
389 unsigned getNodeIndexForInsert(const NodeT *BB) {
390 if constexpr (GraphHasNodeNumbers<NodeT *>) {
391 // getNodeIndex will never fail if nodes have getNumber().
392 unsigned Idx = *getNodeIndex(BB);
393 if (Idx >= DomTreeNodes.size()) {
394 unsigned Max = GraphTraits<ParentPtr>::getMaxNumber(Parent);
395 DomTreeNodes.resize(Max > Idx + 1 ? Max : Idx + 1);
396 }
397 return Idx;
398 } else {
399 // We might already have a number stored for BB.
400 unsigned Idx =
401 NodeNumberMap.try_emplace(BB, DomTreeNodes.size()).first->second;
402 if (Idx >= DomTreeNodes.size())
403 DomTreeNodes.resize(Idx + 1);
404 return Idx;
405 }
406 }
407
408public:
409 /// getNode - return the (Post)DominatorTree node for the specified basic
410 /// block. This is the same as using operator[] on this class. The result
411 /// may (but is not required to) be null for a forward (backwards)
412 /// statically unreachable block.
413 DomTreeNodeBase<NodeT> *getNode(const NodeT *BB) const {
414 assert((!BB || Parent == NodeTrait::getParent(const_cast<NodeT *>(BB))) &&
415 "cannot get DomTreeNode of block with different parent");
416 if (auto Idx = getNodeIndex(BB); Idx && *Idx < DomTreeNodes.size())
417 return DomTreeNodes[*Idx].get();
418 return nullptr;
419 }
420
421 /// See getNode.
422 DomTreeNodeBase<NodeT> *operator[](const NodeT *BB) const {
423 return getNode(BB);
424 }
425
426 /// getRootNode - This returns the entry node for the CFG of the function. If
427 /// this tree represents the post-dominance relations for a function, however,
428 /// this root may be a node with the block == NULL. This is the case when
429 /// there are multiple exit nodes from a particular function. Consumers of
430 /// post-dominance information must be capable of dealing with this
431 /// possibility.
432 ///
434 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
435
436 /// Get all nodes dominated by R, including R itself.
437 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
438 Result.clear();
439 const DomTreeNodeBase<NodeT> *RN = getNode(R);
440 if (!RN)
441 return; // If R is unreachable, it will not be present in the DOM tree.
443 WL.push_back(RN);
444
445 while (!WL.empty()) {
447 Result.push_back(N->getBlock());
448 WL.append(N->begin(), N->end());
449 }
450 }
451
452 /// properlyDominates - Returns true iff A dominates B and A != B.
453 /// Note that this is not a constant time operation!
454 ///
456 const DomTreeNodeBase<NodeT> *B) const {
457 if (!A || !B)
458 return false;
459 if (A == B)
460 return false;
461 return dominates(A, B);
462 }
463
464 bool properlyDominates(const NodeT *A, const NodeT *B) const;
465
466 /// isReachableFromEntry - Return true if A is dominated by the entry
467 /// block of the function containing it.
468 bool isReachableFromEntry(const NodeT *A) const {
469 assert(!this->isPostDominator() &&
470 "This is not implemented for post dominators");
471 return isReachableFromEntry(getNode(A));
472 }
473
474 bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
475
476 /// dominates - Returns true iff A dominates B. Note that this is not a
477 /// constant time operation!
478 ///
480 const DomTreeNodeBase<NodeT> *B) const {
481 // A node trivially dominates itself.
482 if (B == A)
483 return true;
484
485 // An unreachable node is dominated by anything.
487 return true;
488
489 // And dominates nothing.
491 return false;
492
493 if (B->getIDom() == A) return true;
494
495 if (A->getIDom() == B) return false;
496
497 // A can only dominate B if it is higher in the tree.
498 if (A->getLevel() >= B->getLevel()) return false;
499
500 // Compare the result of the tree walk and the dfs numbers, if expensive
501 // checks are enabled.
502#ifdef EXPENSIVE_CHECKS
504 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
505 "Tree walk disagrees with dfs numbers!");
506#endif
507
508 if (DFSInfoValid)
509 return B->DominatedBy(A);
510
511 // If we end up with too many slow queries, just update the
512 // DFS numbers on the theory that we are going to keep querying.
513 SlowQueries++;
514 if (SlowQueries > 32) {
516 return B->DominatedBy(A);
517 }
518
519 return dominatedBySlowTreeWalk(A, B);
520 }
521
522 bool dominates(const NodeT *A, const NodeT *B) const;
523
524 NodeT *getRoot() const {
525 assert(this->Roots.size() == 1 && "Should always have entry node!");
526 return this->Roots[0];
527 }
528
529 /// Find nearest common dominator basic block for basic block A and B. A and B
530 /// must have tree nodes.
531 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const {
532 assert(A && B && "Pointers are not valid");
534 "Two blocks are not in same function");
535
536 // If either A or B is a entry block then it is nearest common dominator
537 // (for forward-dominators).
538 if (!isPostDominator()) {
539 NodeT &Entry =
541 if (A == &Entry || B == &Entry)
542 return &Entry;
543 }
544
547 assert(NodeA && "A must be in the tree");
548 assert(NodeB && "B must be in the tree");
549
550 // Use level information to go up the tree until the levels match. Then
551 // continue going up til we arrive at the same node.
552 while (NodeA != NodeB) {
553 if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB);
554
555 NodeA = NodeA->IDom;
556 }
557
558 return NodeA->getBlock();
559 }
560
561 const NodeT *findNearestCommonDominator(const NodeT *A,
562 const NodeT *B) const {
563 // Cast away the const qualifiers here. This is ok since
564 // const is re-introduced on the return type.
565 return findNearestCommonDominator(const_cast<NodeT *>(A),
566 const_cast<NodeT *>(B));
567 }
568
570 return isPostDominator() && !A->getBlock();
571 }
572
573 template <typename IteratorTy>
575 assert(!Nodes.empty() && "Nodes list is empty!");
576
577 NodeT *NCD = *Nodes.begin();
578 for (NodeT *Node : llvm::drop_begin(Nodes)) {
580
581 // Stop when the root is reached.
582 if (isVirtualRoot(getNode(NCD)))
583 return nullptr;
584 }
585
586 return NCD;
587 }
588
589 //===--------------------------------------------------------------------===//
590 // API to update (Post)DominatorTree information based on modifications to
591 // the CFG...
592
593 /// Inform the dominator tree about a sequence of CFG edge insertions and
594 /// deletions and perform a batch update on the tree.
595 ///
596 /// This function should be used when there were multiple CFG updates after
597 /// the last dominator tree update. It takes care of performing the updates
598 /// in sync with the CFG and optimizes away the redundant operations that
599 /// cancel each other.
600 /// The functions expects the sequence of updates to be balanced. Eg.:
601 /// - {{Insert, A, B}, {Delete, A, B}, {Insert, A, B}} is fine, because
602 /// logically it results in a single insertions.
603 /// - {{Insert, A, B}, {Insert, A, B}} is invalid, because it doesn't make
604 /// sense to insert the same edge twice.
605 ///
606 /// What's more, the functions assumes that it's safe to ask every node in the
607 /// CFG about its children and inverse children. This implies that deletions
608 /// of CFG edges must not delete the CFG nodes before calling this function.
609 ///
610 /// The applyUpdates function can reorder the updates and remove redundant
611 /// ones internally (as long as it is done in a deterministic fashion). The
612 /// batch updater is also able to detect sequences of zero and exactly one
613 /// update -- it's optimized to do less work in these cases.
614 ///
615 /// Note that for postdominators it automatically takes care of applying
616 /// updates on reverse edges internally (so there's no need to swap the
617 /// From and To pointers when constructing DominatorTree::UpdateType).
618 /// The type of updates is the same for DomTreeBase<T> and PostDomTreeBase<T>
619 /// with the same template parameter T.
620 ///
621 /// \param Updates An ordered sequence of updates to perform. The current CFG
622 /// and the reverse of these updates provides the pre-view of the CFG.
623 ///
626 Updates, /*ReverseApplyUpdates=*/true);
627 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, nullptr);
628 }
629
630 /// \param Updates An ordered sequence of updates to perform. The current CFG
631 /// and the reverse of these updates provides the pre-view of the CFG.
632 /// \param PostViewUpdates An ordered sequence of update to perform in order
633 /// to obtain a post-view of the CFG. The DT will be updated assuming the
634 /// obtained PostViewCFG is the desired end state.
636 ArrayRef<UpdateType> PostViewUpdates) {
637 if (Updates.empty()) {
638 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
639 DomTreeBuilder::ApplyUpdates(*this, PostViewCFG, &PostViewCFG);
640 } else {
641 // PreViewCFG needs to merge Updates and PostViewCFG. The updates in
642 // Updates need to be reversed, and match the direction in PostViewCFG.
643 // The PostViewCFG is created with updates reversed (equivalent to changes
644 // made to the CFG), so the PreViewCFG needs all the updates reverse
645 // applied.
646 SmallVector<UpdateType> AllUpdates(Updates);
647 append_range(AllUpdates, PostViewUpdates);
648 GraphDiff<NodePtr, IsPostDom> PreViewCFG(AllUpdates,
649 /*ReverseApplyUpdates=*/true);
650 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
651 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, &PostViewCFG);
652 }
653 }
654
655 /// Inform the dominator tree about a CFG edge insertion and update the tree.
656 ///
657 /// This function has to be called just before or just after making the update
658 /// on the actual CFG. There cannot be any other updates that the dominator
659 /// tree doesn't know about.
660 ///
661 /// Note that for postdominators it automatically takes care of inserting
662 /// a reverse edge internally (so there's no need to swap the parameters).
663 ///
664 void insertEdge(NodeT *From, NodeT *To) {
665 assert(From);
666 assert(To);
669 DomTreeBuilder::InsertEdge(*this, From, To);
670 }
671
672 /// Inform the dominator tree about a CFG edge deletion and update the tree.
673 ///
674 /// This function has to be called just after making the update on the actual
675 /// CFG. An internal functions checks if the edge doesn't exist in the CFG in
676 /// DEBUG mode. There cannot be any other updates that the
677 /// dominator tree doesn't know about.
678 ///
679 /// Note that for postdominators it automatically takes care of deleting
680 /// a reverse edge internally (so there's no need to swap the parameters).
681 ///
682 void deleteEdge(NodeT *From, NodeT *To) {
683 assert(From);
684 assert(To);
687 DomTreeBuilder::DeleteEdge(*this, From, To);
688 }
689
690 /// Add a new node to the dominator tree information.
691 ///
692 /// This creates a new node as a child of DomBB dominator node, linking it
693 /// into the children list of the immediate dominator.
694 ///
695 /// \param BB New node in CFG.
696 /// \param DomBB CFG node that is dominator for BB.
697 /// \returns New dominator tree node that represents new CFG node.
698 ///
699 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
700 assert(getNode(BB) == nullptr && "Block already in dominator tree!");
701 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
702 assert(IDomNode && "Not immediate dominator specified for block!");
703 DFSInfoValid = false;
704 return createNode(BB, IDomNode);
705 }
706
707 /// Add a new node to the forward dominator tree and make it a new root.
708 ///
709 /// \param BB New node in CFG.
710 /// \returns New dominator tree node that represents new CFG node.
711 ///
713 assert(getNode(BB) == nullptr && "Block already in dominator tree!");
714 assert(!this->isPostDominator() &&
715 "Cannot change root of post-dominator tree");
716 DFSInfoValid = false;
717 DomTreeNodeBase<NodeT> *NewNode = createNode(BB);
718 if (Roots.empty()) {
719 addRoot(BB);
720 } else {
721 assert(Roots.size() == 1);
722 NodeT *OldRoot = Roots.front();
723 DomTreeNodeBase<NodeT> *OldNode = getNode(OldRoot);
724 NewNode->addChild(OldNode);
725 OldNode->IDom = NewNode;
726 OldNode->UpdateLevel();
727 Roots[0] = BB;
728 }
729 return RootNode = NewNode;
730 }
731
732 /// changeImmediateDominator - This method is used to update the dominator
733 /// tree information when a node's immediate dominator changes.
734 ///
736 DomTreeNodeBase<NodeT> *NewIDom) {
737 assert(N && NewIDom && "Cannot change null node pointers!");
738 DFSInfoValid = false;
739 N->setIDom(NewIDom);
740 }
741
742 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
744 }
745
746 /// eraseNode - Removes a node from the dominator tree. Block must not
747 /// dominate any other blocks. Removes node from its immediate dominator's
748 /// children list. Deletes dominator node associated with basic block BB.
749 void eraseNode(NodeT *BB) {
750 std::optional<unsigned> IdxOpt = getNodeIndex(BB);
751 assert(IdxOpt && DomTreeNodes[*IdxOpt] &&
752 "Removing node that isn't in dominator tree.");
753 DomTreeNodeBase<NodeT> *Node = DomTreeNodes[*IdxOpt].get();
754 assert(Node->isLeaf() && "Node is not a leaf node.");
755
756 DFSInfoValid = false;
757
758 // Remove node from immediate dominator's children list.
759 if (DomTreeNodeBase<NodeT> *IDom = Node->getIDom())
760 IDom->removeChild(Node);
761
762 DomTreeNodes[*IdxOpt] = nullptr;
763 if constexpr (!GraphHasNodeNumbers<NodeT *>)
764 NodeNumberMap.erase(BB);
765
766 if (!IsPostDom) return;
767
768 // Remember to update PostDominatorTree roots.
769 auto RIt = llvm::find(Roots, BB);
770 if (RIt != Roots.end()) {
771 std::swap(*RIt, Roots.back());
772 Roots.pop_back();
773 }
774 }
775
776 /// splitBlock - BB is split and now it has one successor. Update dominator
777 /// tree to reflect this change.
778 void splitBlock(NodeT *NewBB) {
779 if (IsPostDominator)
781 else
782 Split<NodeT *>(NewBB);
783 }
784
785 /// print - Convert to human readable form
786 ///
787 void print(raw_ostream &O) const {
788 O << "=============================--------------------------------\n";
789 if (IsPostDominator)
790 O << "Inorder PostDominator Tree: ";
791 else
792 O << "Inorder Dominator Tree: ";
793 if (!DFSInfoValid)
794 O << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
795 O << "\n";
796
797 // The postdom tree can have a null root if there are no returns.
799 O << "Roots: ";
800 for (const NodePtr Block : Roots) {
801 Block->printAsOperand(O, false);
802 O << " ";
803 }
804 O << "\n";
805 }
806
807public:
808 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
809 /// dominator tree in dfs order.
810 void updateDFSNumbers() const {
811 if (DFSInfoValid) {
812 SlowQueries = 0;
813 return;
814 }
815
818 32> WorkStack;
819
820 const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
821 assert((!Parent || ThisRoot) && "Empty constructed DomTree");
822 if (!ThisRoot)
823 return;
824
825 // Both dominators and postdominators have a single root node. In the case
826 // case of PostDominatorTree, this node is a virtual root.
827 WorkStack.push_back({ThisRoot, ThisRoot->begin()});
828
829 unsigned DFSNum = 0;
830 ThisRoot->DFSNumIn = DFSNum++;
831
832 while (!WorkStack.empty()) {
833 const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
834 const auto ChildIt = WorkStack.back().second;
835
836 // If we visited all of the children of this node, "recurse" back up the
837 // stack setting the DFOutNum.
838 if (ChildIt == Node->end()) {
839 Node->DFSNumOut = DFSNum++;
840 WorkStack.pop_back();
841 } else {
842 // Otherwise, recursively visit this child.
843 const DomTreeNodeBase<NodeT> *Child = *ChildIt;
844 ++WorkStack.back().second;
845
846 WorkStack.push_back({Child, Child->begin()});
847 Child->DFSNumIn = DFSNum++;
848 }
849 }
850
851 SlowQueries = 0;
852 DFSInfoValid = true;
853 }
854
855private:
856 void updateBlockNumberEpoch() {
857 // Nothing to do for graphs that don't number their blocks.
858 if constexpr (GraphHasNodeNumbers<NodeT *>)
860 }
861
862public:
863 /// recalculate - compute a dominator tree for the given function
865 Parent = &Func;
866 updateBlockNumberEpoch();
868 }
869
871 Parent = &Func;
872 updateBlockNumberEpoch();
874 }
875
876 /// Update dominator tree after renumbering blocks.
877 template <typename T = NodeT>
878 std::enable_if_t<GraphHasNodeNumbers<T *>, void> updateBlockNumbers() {
879 updateBlockNumberEpoch();
880
881 unsigned MaxNumber = GraphTraits<ParentPtr>::getMaxNumber(Parent);
882 DomTreeNodeStorageTy NewVector;
883 NewVector.resize(MaxNumber + 1); // +1, because index 0 is for nullptr
884 for (auto &Node : DomTreeNodes) {
885 if (!Node)
886 continue;
887 unsigned Idx = *getNodeIndex(Node->getBlock());
888 // getMaxNumber is not necessarily supported
889 if (Idx >= NewVector.size())
890 NewVector.resize(Idx + 1);
891 NewVector[Idx] = std::move(Node);
892 }
893 DomTreeNodes = std::move(NewVector);
894 }
895
896 /// verify - checks if the tree is correct. There are 3 level of verification:
897 /// - Full -- verifies if the tree is correct by making sure all the
898 /// properties (including the parent and the sibling property)
899 /// hold.
900 /// Takes O(N^3) time.
901 ///
902 /// - Basic -- checks if the tree is correct, but compares it to a freshly
903 /// constructed tree instead of checking the sibling property.
904 /// Takes O(N^2) time.
905 ///
906 /// - Fast -- checks basic tree structure and compares it with a freshly
907 /// constructed tree.
908 /// Takes O(N^2) time worst case, but is faster in practise (same
909 /// as tree construction).
911 return DomTreeBuilder::Verify(*this, VL);
912 }
913
914 void reset() {
915 DomTreeNodes.clear();
916 if constexpr (!GraphHasNodeNumbers<NodeT *>)
917 NodeNumberMap.clear();
918 Roots.clear();
919 RootNode = nullptr;
920 Parent = nullptr;
921 DFSInfoValid = false;
922 SlowQueries = 0;
923 }
924
925protected:
926 inline void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
927
929 DomTreeNodeBase<NodeT> *IDom = nullptr) {
930 auto Node = std::make_unique<DomTreeNodeBase<NodeT>>(BB, IDom);
931 auto *NodePtr = Node.get();
932 unsigned NodeIdx = getNodeIndexForInsert(BB);
933 DomTreeNodes[NodeIdx] = std::move(Node);
934 if (IDom)
935 IDom->addChild(NodePtr);
936 return NodePtr;
937 }
938
939 // NewBB is split and now it has one successor. Update dominator tree to
940 // reflect this change.
941 template <class N>
942 void Split(typename GraphTraits<N>::NodeRef NewBB) {
943 using GraphT = GraphTraits<N>;
944 using NodeRef = typename GraphT::NodeRef;
946 "NewBB should have a single successor!");
947 NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
948
950
951 assert(!PredBlocks.empty() && "No predblocks?");
952
953 bool NewBBDominatesNewBBSucc = true;
954 for (auto *Pred : inverse_children<N>(NewBBSucc)) {
955 if (Pred != NewBB && !dominates(NewBBSucc, Pred) &&
956 isReachableFromEntry(Pred)) {
957 NewBBDominatesNewBBSucc = false;
958 break;
959 }
960 }
961
962 // Find NewBB's immediate dominator and create new dominator tree node for
963 // NewBB.
964 NodeT *NewBBIDom = nullptr;
965 unsigned i = 0;
966 for (i = 0; i < PredBlocks.size(); ++i)
967 if (isReachableFromEntry(PredBlocks[i])) {
968 NewBBIDom = PredBlocks[i];
969 break;
970 }
971
972 // It's possible that none of the predecessors of NewBB are reachable;
973 // in that case, NewBB itself is unreachable, so nothing needs to be
974 // changed.
975 if (!NewBBIDom) return;
976
977 for (i = i + 1; i < PredBlocks.size(); ++i) {
978 if (isReachableFromEntry(PredBlocks[i]))
979 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
980 }
981
982 // Create the new dominator tree node... and set the idom of NewBB.
983 DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom);
984
985 // If NewBB strictly dominates other blocks, then it is now the immediate
986 // dominator of NewBBSucc. Update the dominator tree as appropriate.
987 if (NewBBDominatesNewBBSucc) {
988 DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc);
989 changeImmediateDominator(NewBBSuccNode, NewBBNode);
990 }
991 }
992
993 private:
994 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
995 const DomTreeNodeBase<NodeT> *B) const {
996 assert(A != B);
999
1000 const unsigned ALevel = A->getLevel();
1001 const DomTreeNodeBase<NodeT> *IDom;
1002
1003 // Don't walk nodes above A's subtree. When we reach A's level, we must
1004 // either find A or be in some other subtree not dominated by A.
1005 while ((IDom = B->getIDom()) != nullptr && IDom->getLevel() >= ALevel)
1006 B = IDom; // Walk up the tree
1007
1008 return B == A;
1009 }
1010};
1011
1012template <typename T>
1014
1015template <typename T>
1017
1018// These two functions are declared out of line as a workaround for building
1019// with old (< r147295) versions of clang because of pr11642.
1020template <typename NodeT, bool IsPostDom>
1022 const NodeT *B) const {
1023 if (A == B)
1024 return true;
1025
1026 return dominates(getNode(A), getNode(B));
1027}
1028template <typename NodeT, bool IsPostDom>
1030 const NodeT *A, const NodeT *B) const {
1031 if (A == B)
1032 return false;
1033
1034 return dominates(getNode(A), getNode(B));
1035}
1036
1037} // end namespace llvm
1038
1039#endif // LLVM_SUPPORT_GENERICDOMTREE_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
#define I(x, y, z)
Definition MD5.cpp:57
ppc ctr loops PowerPC CTR Loops Verify
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Value * RHS
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
bool operator==(const const_iterator &Other) const
DomTreeNodeBase * operator*() const
const_iterator(DomTreeNodeBase *Node=nullptr)
Base class for the actual dominator tree node.
iterator_range< iterator > children()
DomTreeNodeBase(const DomTreeNodeBase &)=delete
void setIDom(DomTreeNodeBase *NewIDom)
void removeChild(DomTreeNodeBase *C)
DomTreeNodeBase * getIDom() const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
iterator begin() const
DomTreeNodeBase & operator=(const DomTreeNodeBase &)=delete
DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom)
bool compare(const DomTreeNodeBase *Other) const
NodeT * getBlock() const
unsigned getLevel() const
iterator end() const
iterator_range< const_iterator > children() const
unsigned getDFSNumOut() const
void addChild(DomTreeNodeBase *C)
Core dominator tree base class.
DominatorTreeBase(DominatorTreeBase &&Arg)=default
DomTreeNodeTraits< BlockT > NodeTrait
bool isReachableFromEntry(const DomTreeNodeBase< NodeT > *A) const
void print(raw_ostream &O) const
print - Convert to human readable form
typename NodeTrait::NodeType NodeType
DomTreeNodeBase< NodeT > * operator[](const NodeT *BB) const
See getNode.
typename SmallVectorImpl< BlockT * >::iterator root_iterator
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(NodeT *BB, NodeT *NewBB)
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
void Split(typename GraphTraits< N >::NodeRef NewBB)
iterator_range< root_iterator > roots()
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
std::remove_pointer_t< ParentPtr > ParentType
NodeT * findNearestCommonDominator(iterator_range< IteratorTy > Nodes) const
bool isPostDominator() const
isPostDominator - Returns true if analysis based of postdoms
bool dominates(const NodeT *A, const NodeT *B) const
const NodeT * findNearestCommonDominator(const NodeT *A, const NodeT *B) const
void getDescendants(NodeT *R, SmallVectorImpl< NodeT * > &Result) const
Get all nodes dominated by R, including R itself.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * createNode(NodeT *BB, DomTreeNodeBase< NodeT > *IDom=nullptr)
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
void insertEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge insertion and update the tree.
std::enable_if_t< GraphHasNodeNumbers< T * >, void > updateBlockNumbers()
Update dominator tree after renumbering blocks.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
iterator_range< const_root_iterator > roots() const
const_root_iterator root_end() const
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
void recalculate(ParentType &Func, ArrayRef< UpdateType > Updates)
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
typename SmallVectorImpl< BlockT * >::const_iterator const_root_iterator
bool compare(const DominatorTreeBase &Other) const
compare - Return false if the other dominator tree base matches this dominator tree base.
DominatorTreeBase & operator=(DominatorTreeBase &&RHS)=default
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
root_iterator root_begin()
DominatorTreeBase(const DominatorTreeBase &)=delete
const_root_iterator root_begin() const
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
SmallVector< BlockT *, IsPostDom ? 4 :1 > Roots
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
const DomTreeNodeBase< NodeT > * getRootNode() const
std::conditional_t<!GraphHasNodeNumbers< BlockT * >, DenseMap< const BlockT *, unsigned >, std::tuple<> > NodeNumberMap
DomTreeNodeBase< BlockT > * RootNode
typename NodeTrait::NodePtr NodePtr
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
void applyUpdates(ArrayRef< UpdateType > Updates, ArrayRef< UpdateType > PostViewUpdates)
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const NodeT *A, const NodeT *B) const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
bool isVirtualRoot(const DomTreeNodeBase< NodeT > *A) const
typename NodeTrait::ParentPtr ParentPtr
DominatorTreeBase & operator=(const DominatorTreeBase &)=delete
SmallVector< std::unique_ptr< DomTreeNodeBase< BlockT > > > DomTreeNodeStorageTy
size_type size() const
Definition SmallPtrSet.h:99
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::const_iterator const_iterator
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
typename SuperClass::iterator iterator
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
IteratorT begin() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL)
void CalculateWithUpdates(DomTreeT &DT, ArrayRef< typename DomTreeT::UpdateType > Updates)
void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
void ApplyUpdates(DomTreeT &DT, GraphDiff< typename DomTreeT::NodePtr, DomTreeT::IsPostDominator > &PreViewCFG, GraphDiff< typename DomTreeT::NodePtr, DomTreeT::IsPostDominator > *PostViewCFG)
void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1763
void PrintDomTree(const DomTreeNodeBase< NodeT > *N, raw_ostream &O, unsigned Lev)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr bool GraphHasNodeNumbers
Indicate whether a GraphTraits<NodeT>::getNumber() is supported.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2198
DominatorTreeBase< T, true > PostDomTreeBase
DominatorTreeBase< T, false > DomTreeBase
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:300
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
Default DomTreeNode traits for NodeT.
static NodeT * getEntryNode(ParentPtr Parent)
std::remove_pointer_t< ParentPtr > ParentType
static ParentPtr getParent(NodePtr BB)
decltype(std::declval< NodePtr >() ->getParent()) ParentPtr
typename GraphType::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:95