LLVM 24.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"
36#include <algorithm>
37#include <cassert>
38#include <cstddef>
39#include <memory>
40#include <new>
41#include <type_traits>
42#include <utility>
43
44namespace llvm {
45
46template <typename NodeT, bool IsPostDom>
48
49template <class BlockT, class LoopT> class LoopInfoBase;
50
51namespace DomTreeBuilder {
52template <typename DomTreeT>
53struct SemiNCAInfo;
54} // namespace DomTreeBuilder
55
56/// Base class for the actual dominator tree node.
57template <class NodeT> class DomTreeNodeBase {
58 friend class PostDominatorTree;
59 friend class DominatorTreeBase<NodeT, false>;
60 friend class DominatorTreeBase<NodeT, true>;
63
64 NodeT *TheBB;
65 DomTreeNodeBase *IDom;
66 unsigned Level;
67 DomTreeNodeBase *FirstChild = nullptr;
68 DomTreeNodeBase *Sibling = nullptr;
69 mutable unsigned DFSNumIn = ~0;
70 mutable unsigned DFSNumOut = ~0;
71
72 public:
74 : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {}
75
78
80 : public iterator_facade_base<const_iterator, std::forward_iterator_tag,
81 DomTreeNodeBase *> {
82 DomTreeNodeBase *Node;
83
84 public:
85 const_iterator(DomTreeNodeBase *Node = nullptr) : Node(Node) {}
86 bool operator==(const const_iterator &Other) const {
87 return Other.Node == Node;
88 }
89 DomTreeNodeBase *operator*() const { return Node; }
91 Node = Node->Sibling;
92 return *this;
93 }
95 const_iterator cp = *this;
96 ++*this;
97 return cp;
98 }
99 };
100 // We don't permit modifications through the iterator.
101 using iterator = const_iterator;
102
103 iterator begin() const { return iterator{FirstChild}; }
104 iterator end() const { return iterator{}; }
105
108 return make_range(begin(), end());
109 }
110
111 NodeT *getBlock() const { return TheBB; }
112 DomTreeNodeBase *getIDom() const { return IDom; }
113 unsigned getLevel() const { return Level; }
114
115 bool isLeaf() const { return FirstChild == nullptr; }
116
117 bool compare(const DomTreeNodeBase *Other) const {
118 if (Level != Other->Level) return true;
119
120 SmallPtrSet<const NodeT *, 4> OtherChildren;
121 for (const DomTreeNodeBase *I : *Other) {
122 const NodeT *Nd = I->getBlock();
123 OtherChildren.insert(Nd);
124 }
125
126 size_t OwnCount = 0;
127 for (const DomTreeNodeBase *I : *this) {
128 const NodeT *N = I->getBlock();
129 if (OtherChildren.count(N) == 0)
130 return true;
131 ++OwnCount;
132 }
133 return OwnCount != OtherChildren.size();
134 }
135
136 void setIDom(DomTreeNodeBase *NewIDom) {
137 assert(IDom && "No immediate dominator?");
138 if (IDom == NewIDom) return;
139 IDom->removeChild(this);
140
141 // Switch to new dominator
142 IDom = NewIDom;
143 IDom->addChild(this);
144
145 UpdateLevel();
146 }
147
148 /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
149 /// in the dominator tree. They are only guaranteed valid if
150 /// updateDFSNumbers() has been called.
151 unsigned getDFSNumIn() const { return DFSNumIn; }
152 unsigned getDFSNumOut() const { return DFSNumOut; }
153
154private:
155 void addChild(DomTreeNodeBase *C) {
156 assert(!C->Sibling && "cannot add child that already has siblings");
157 C->Sibling = FirstChild;
158 FirstChild = C;
159 }
160
161 void removeChild(DomTreeNodeBase *C) {
162 DomTreeNodeBase **It = &FirstChild;
163 while (*It != C) {
164 assert(*It != nullptr && "Not in immediate dominator children list!");
165 It = &(*It)->Sibling;
166 }
167 *It = C->Sibling;
168 C->Sibling = nullptr;
169 }
170
171 // Return true if this node is dominated by other. Use this only if DFS info
172 // is valid.
173 bool DominatedBy(const DomTreeNodeBase *other) const {
174 return this->DFSNumIn >= other->DFSNumIn &&
175 this->DFSNumOut <= other->DFSNumOut;
176 }
177
178 void UpdateLevel() {
179 assert(IDom);
180 if (Level == IDom->Level + 1) return;
181
182 SmallVector<DomTreeNodeBase *, 64> WorkStack = {this};
183
184 while (!WorkStack.empty()) {
185 DomTreeNodeBase *Current = WorkStack.pop_back_val();
186 Current->Level = Current->IDom->Level + 1;
187
188 for (DomTreeNodeBase *C : *Current) {
189 assert(C->IDom);
190 if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C);
191 }
192 }
193 }
194};
195
196template <class NodeT>
198 if (Node->getBlock())
199 Node->getBlock()->printAsOperand(O, false);
200 else
201 O << " <<exit node>>";
202
203 O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} ["
204 << Node->getLevel() << "]\n";
205
206 return O;
207}
208
209template <class NodeT>
211 unsigned Lev) {
212 O.indent(2 * Lev) << "[" << Lev << "] " << N;
213 for (const auto &I : *N)
214 PrintDomTree<NodeT>(I, O, Lev + 1);
215}
216
217namespace DomTreeBuilder {
218// The routines below are provided in a separate header but referenced here.
219template <typename DomTreeT>
220void Calculate(DomTreeT &DT);
221
222template <typename DomTreeT>
223void CalculateWithUpdates(DomTreeT &DT,
225
226template <typename DomTreeT>
227void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
228 typename DomTreeT::NodePtr To);
229
230template <typename DomTreeT>
231void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
232 typename DomTreeT::NodePtr To);
233
234template <typename DomTreeT>
235void ApplyUpdates(DomTreeT &DT,
236 GraphDiff<typename DomTreeT::NodePtr,
237 DomTreeT::IsPostDominator> &PreViewCFG,
238 GraphDiff<typename DomTreeT::NodePtr,
239 DomTreeT::IsPostDominator> *PostViewCFG);
240
241template <typename DomTreeT>
242bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL);
243} // namespace DomTreeBuilder
244
245/// Default DomTreeNode traits for NodeT. The default implementation assume a
246/// Function-like NodeT. Can be specialized to support different node types.
247template <typename NodeT> struct DomTreeNodeTraits {
248 using NodeType = NodeT;
249 using NodePtr = NodeT *;
250 using ParentPtr = decltype(std::declval<NodePtr>()->getParent());
251 static_assert(std::is_pointer_v<ParentPtr>,
252 "Currently NodeT's parent must be a pointer type");
253 using ParentType = std::remove_pointer_t<ParentPtr>;
254
255 static NodeT *getEntryNode(ParentPtr Parent) { return &Parent->front(); }
256 static ParentPtr getParent(NodePtr BB) { return BB->getParent(); }
257};
258
259/// Core dominator tree base class.
260///
261/// This class is a generic template over graph nodes. It is instantiated for
262/// various graphs in the LLVM IR or in the code generator.
263template <typename NodeT, bool IsPostDom> class DominatorTreeBase {
264public:
265 static_assert(GraphHasNodeNumbers<NodeT *>,
266 "DominatorTreeBase requires graphs with numbered nodes");
267 static_assert(std::is_pointer_v<typename GraphTraits<NodeT *>::NodeRef>,
268 "Currently DominatorTreeBase supports only pointer nodes");
271 using NodePtr = typename NodeTrait::NodePtr;
273 static_assert(std::is_pointer_v<ParentPtr>,
274 "Currently NodeT's parent must be a pointer type");
275 using ParentType = std::remove_pointer_t<ParentPtr>;
276 static constexpr bool IsPostDominator = IsPostDom;
277
280 static constexpr UpdateKind Insert = UpdateKind::Insert;
281 static constexpr UpdateKind Delete = UpdateKind::Delete;
282
284
285protected:
286 // Dominators always have a single root, postdominators can have more.
288
292 ParentPtr Parent = nullptr;
293
294 // Use small slab size to reduce memory waste for modules with many small
295 // functions. Compensate with a short GrowthDelay. This is relevant for
296 // ThinLTO on modules with many functions (not uncommon in C++), where all
297 // dominator trees are live at the same time.
298 static constexpr size_t SlabSize = 8 * sizeof(DomTreeNodeBase<NodeT>);
300 /*GrowthDelay=*/2>
302
303 mutable bool DFSInfoValid = false;
304 mutable unsigned int SlowQueries = 0;
305 unsigned BlockNumberEpoch = 0;
306
308 template <class BlockT, class LoopT> friend class LoopInfoBase;
309
310public:
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 // For LoopInfoBase's use in deriving a reverse-preorder traversal.
376 auto nodes() const {
378 return N != nullptr;
379 });
380 }
381
382 unsigned getNodeIndex(const NodeT *BB) const {
383 assert(BlockNumberEpoch == GraphTraits<ParentPtr>::getNumberEpoch(Parent) &&
384 "dominator tree used with outdated block numbers");
385 if constexpr (IsPostDom) {
386 if (!BB)
387 return 0; // BB may be nullptr for post-dominator tree, map to 0.
388 } else
389 assert(BB && "dominator tree block must be non-null");
390 return GraphTraits<const NodeT *>::getNumber(BB) + IsPostDom;
391 }
392
393public:
394 /// getNode - return the (Post)DominatorTree node for the specified basic
395 /// block. This is the same as using operator[] on this class. The result
396 /// may (but is not required to) be null for a forward (backwards)
397 /// statically unreachable block.
398 DomTreeNodeBase<NodeT> *getNode(const NodeT *BB) const {
399 assert((!BB || Parent == NodeTrait::getParent(const_cast<NodeT *>(BB))) &&
400 "cannot get DomTreeNode of block with different parent");
401 if (unsigned Idx = getNodeIndex(BB); Idx < DomTreeNodes.size())
402 return DomTreeNodes[Idx];
403 return nullptr;
404 }
405
406 /// See getNode.
407 DomTreeNodeBase<NodeT> *operator[](const NodeT *BB) const {
408 return getNode(BB);
409 }
410
411 /// getRootNode - This returns the entry node for the CFG of the function. If
412 /// this tree represents the post-dominance relations for a function, however,
413 /// this root may be a node with the block == NULL. This is the case when
414 /// there are multiple exit nodes from a particular function. Consumers of
415 /// post-dominance information must be capable of dealing with this
416 /// possibility.
417 ///
419 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
420
421 /// Get all nodes dominated by R, including R itself.
422 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
423 Result.clear();
424 const DomTreeNodeBase<NodeT> *RN = getNode(R);
425 if (!RN)
426 return; // If R is unreachable, it will not be present in the DOM tree.
428 WL.push_back(RN);
429
430 while (!WL.empty()) {
432 Result.push_back(N->getBlock());
433 WL.append(N->begin(), N->end());
434 }
435 }
436
437 /// properlyDominates - Returns true iff A dominates B and A != B.
438 /// Note that this is not a constant time operation!
439 ///
441 const DomTreeNodeBase<NodeT> *B) const {
442 if (!A || !B)
443 return false;
444 if (A == B)
445 return false;
446 return dominates(A, B);
447 }
448
449 bool properlyDominates(const NodeT *A, const NodeT *B) const;
450
451 /// isReachableFromEntry - Return true if A is dominated by the entry
452 /// block of the function containing it.
453 bool isReachableFromEntry(const NodeT *A) const {
454 assert(!this->isPostDominator() &&
455 "This is not implemented for post dominators");
456 return getNode(A) != nullptr;
457 }
458
459 /// dominates - Returns true iff A dominates B. Note that this is not a
460 /// constant time operation!
461 ///
463 const DomTreeNodeBase<NodeT> *B) const {
464 // A node trivially dominates itself.
465 if (B == A)
466 return true;
467
468 // An unreachable node is dominated by anything.
469 if (!B)
470 return true;
471
472 // And dominates nothing.
473 if (!A)
474 return false;
475
476 if (B->getIDom() == A) return true;
477
478 if (A->getIDom() == B) return false;
479
480 // A can only dominate B if it is higher in the tree.
481 if (A->getLevel() >= B->getLevel()) return false;
482
483 // Compare the result of the tree walk and the dfs numbers, if expensive
484 // checks are enabled.
485#ifdef EXPENSIVE_CHECKS
487 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
488 "Tree walk disagrees with dfs numbers!");
489#endif
490
491 if (DFSInfoValid)
492 return B->DominatedBy(A);
493
494 // If we end up with too many slow queries, just update the
495 // DFS numbers on the theory that we are going to keep querying.
496 SlowQueries++;
497 if (SlowQueries > 32) {
499 return B->DominatedBy(A);
500 }
501
502 return dominatedBySlowTreeWalk(A, B);
503 }
504
505 bool dominates(const NodeT *A, const NodeT *B) const;
506
507 NodeT *getRoot() const {
508 assert(this->Roots.size() == 1 && "Should always have entry node!");
509 return this->Roots[0];
510 }
511
512 /// Find nearest common dominator basic block for basic block A and B. A and B
513 /// must have tree nodes.
514 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const {
515 assert(A && B && "Pointers are not valid");
517 "Two blocks are not in same function");
518
519 // If either A or B is a entry block then it is nearest common dominator
520 // (for forward-dominators).
521 if (!isPostDominator()) {
522 NodeT &Entry =
524 if (A == &Entry || B == &Entry)
525 return &Entry;
526 }
527
530 assert(NodeA && "A must be in the tree");
531 assert(NodeB && "B must be in the tree");
532
533 // Use level information to go up the tree until the levels match. Then
534 // continue going up til we arrive at the same node.
535 while (NodeA != NodeB) {
536 if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB);
537
538 NodeA = NodeA->IDom;
539 }
540
541 return NodeA->getBlock();
542 }
543
544 const NodeT *findNearestCommonDominator(const NodeT *A,
545 const NodeT *B) const {
546 // Cast away the const qualifiers here. This is ok since
547 // const is re-introduced on the return type.
548 return findNearestCommonDominator(const_cast<NodeT *>(A),
549 const_cast<NodeT *>(B));
550 }
551
553 return isPostDominator() && !A->getBlock();
554 }
555
556 template <typename IteratorTy>
558 assert(!Nodes.empty() && "Nodes list is empty!");
559
560 NodeT *NCD = *Nodes.begin();
561 for (NodeT *Node : llvm::drop_begin(Nodes)) {
563
564 // Stop when the root is reached.
565 if (isVirtualRoot(getNode(NCD)))
566 return nullptr;
567 }
568
569 return NCD;
570 }
571
572 //===--------------------------------------------------------------------===//
573 // API to update (Post)DominatorTree information based on modifications to
574 // the CFG...
575
576 /// Inform the dominator tree about a sequence of CFG edge insertions and
577 /// deletions and perform a batch update on the tree.
578 ///
579 /// This function should be used when there were multiple CFG updates after
580 /// the last dominator tree update. It takes care of performing the updates
581 /// in sync with the CFG and optimizes away the redundant operations that
582 /// cancel each other.
583 /// The functions expects the sequence of updates to be balanced. Eg.:
584 /// - {{Insert, A, B}, {Delete, A, B}, {Insert, A, B}} is fine, because
585 /// logically it results in a single insertions.
586 /// - {{Insert, A, B}, {Insert, A, B}} is invalid, because it doesn't make
587 /// sense to insert the same edge twice.
588 ///
589 /// What's more, the functions assumes that it's safe to ask every node in the
590 /// CFG about its children and inverse children. This implies that deletions
591 /// of CFG edges must not delete the CFG nodes before calling this function.
592 ///
593 /// The applyUpdates function can reorder the updates and remove redundant
594 /// ones internally (as long as it is done in a deterministic fashion). The
595 /// batch updater is also able to detect sequences of zero and exactly one
596 /// update -- it's optimized to do less work in these cases.
597 ///
598 /// Note that for postdominators it automatically takes care of applying
599 /// updates on reverse edges internally (so there's no need to swap the
600 /// From and To pointers when constructing DominatorTree::UpdateType).
601 /// The type of updates is the same for DomTreeBase<T> and PostDomTreeBase<T>
602 /// with the same template parameter T.
603 ///
604 /// \param Updates An ordered sequence of updates to perform. The current CFG
605 /// and the reverse of these updates provides the pre-view of the CFG.
606 ///
608
609 /// \param Updates An ordered sequence of updates to perform. The current CFG
610 /// and the reverse of these updates provides the pre-view of the CFG.
611 /// \param PostViewUpdates An ordered sequence of update to perform in order
612 /// to obtain a post-view of the CFG. The DT will be updated assuming the
613 /// obtained PostViewCFG is the desired end state.
615 ArrayRef<UpdateType> PostViewUpdates);
616
617 /// Inform the dominator tree about a CFG edge insertion and update the tree.
618 ///
619 /// This function has to be called just before or just after making the update
620 /// on the actual CFG. There cannot be any other updates that the dominator
621 /// tree doesn't know about.
622 ///
623 /// Note that for postdominators it automatically takes care of inserting
624 /// a reverse edge internally (so there's no need to swap the parameters).
625 ///
626 void insertEdge(NodeT *From, NodeT *To);
627
628 /// Inform the dominator tree about a CFG edge deletion and update the tree.
629 ///
630 /// This function has to be called just after making the update on the actual
631 /// CFG. An internal functions checks if the edge doesn't exist in the CFG in
632 /// DEBUG mode. There cannot be any other updates that the
633 /// dominator tree doesn't know about.
634 ///
635 /// Note that for postdominators it automatically takes care of deleting
636 /// a reverse edge internally (so there's no need to swap the parameters).
637 ///
638 void deleteEdge(NodeT *From, NodeT *To);
639
640 /// Add a new node to the dominator tree information.
641 ///
642 /// This creates a new node as a child of DomBB dominator node, linking it
643 /// into the children list of the immediate dominator.
644 ///
645 /// \param BB New node in CFG.
646 /// \param DomBB CFG node that is dominator for BB.
647 /// \returns New dominator tree node that represents new CFG node.
648 ///
649 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
650 assert(getNode(BB) == nullptr && "Block already in dominator tree!");
651 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
652 assert(IDomNode && "Not immediate dominator specified for block!");
653 DFSInfoValid = false;
654 return createNode(BB, IDomNode);
655 }
656
657 /// Add a new node to the forward dominator tree and make it a new root.
658 ///
659 /// \param BB New node in CFG.
660 /// \returns New dominator tree node that represents new CFG node.
661 ///
663 assert(getNode(BB) == nullptr && "Block already in dominator tree!");
664 assert(!this->isPostDominator() &&
665 "Cannot change root of post-dominator tree");
666 DFSInfoValid = false;
667 DomTreeNodeBase<NodeT> *NewNode = createNode(BB);
668 if (Roots.empty()) {
669 addRoot(BB);
670 } else {
671 assert(Roots.size() == 1);
672 NodeT *OldRoot = Roots.front();
673 DomTreeNodeBase<NodeT> *OldNode = getNode(OldRoot);
674 NewNode->addChild(OldNode);
675 OldNode->IDom = NewNode;
676 OldNode->UpdateLevel();
677 Roots[0] = BB;
678 }
679 return RootNode = NewNode;
680 }
681
682 /// changeImmediateDominator - This method is used to update the dominator
683 /// tree information when a node's immediate dominator changes.
684 ///
686 DomTreeNodeBase<NodeT> *NewIDom) {
687 assert(N && NewIDom && "Cannot change null node pointers!");
688 DFSInfoValid = false;
689 N->setIDom(NewIDom);
690 }
691
692 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
694 }
695
696 /// eraseNode - Removes a node from the dominator tree. Block must not
697 /// dominate any other blocks. Removes node from its immediate dominator's
698 /// children list. Deletes dominator node associated with basic block BB.
699 void eraseNode(NodeT *BB) {
700 unsigned Idx = getNodeIndex(BB);
702 assert(Node && "Removing node that isn't in dominator tree.");
703 assert(Node->isLeaf() && "Node is not a leaf node.");
704
705 DFSInfoValid = false;
706
707 // Remove node from immediate dominator's children list.
708 if (DomTreeNodeBase<NodeT> *IDom = Node->getIDom())
709 IDom->removeChild(Node);
710
711 DomTreeNodes[Idx] = nullptr;
712
713 if (!IsPostDom) return;
714
715 // Remember to update PostDominatorTree roots.
716 auto RIt = llvm::find(Roots, BB);
717 if (RIt != Roots.end()) {
718 std::swap(*RIt, Roots.back());
719 Roots.pop_back();
720 }
721 }
722
723 /// splitBlock - BB is split and now it has one successor. Update dominator
724 /// tree to reflect this change.
725 void splitBlock(NodeT *NewBB) {
726 if (IsPostDominator)
728 else
729 Split<NodeT *>(NewBB);
730 }
731
732 /// print - Convert to human readable form
733 ///
734 void print(raw_ostream &O) const {
735 O << "=============================--------------------------------\n";
736 if (IsPostDominator)
737 O << "Inorder PostDominator Tree: ";
738 else
739 O << "Inorder Dominator Tree: ";
740 if (!DFSInfoValid)
741 O << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
742 O << "\n";
743
744 // The postdom tree can have a null root if there are no returns.
746 O << "Roots: ";
747 for (const NodePtr Block : Roots) {
748 Block->printAsOperand(O, false);
749 O << " ";
750 }
751 O << "\n";
752 }
753
754public:
755 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
756 /// dominator tree in dfs order.
757 void updateDFSNumbers() const {
758 if (DFSInfoValid) {
759 SlowQueries = 0;
760 return;
761 }
762
765 32> WorkStack;
766
767 const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
768 assert((!Parent || ThisRoot) && "Empty constructed DomTree");
769 if (!ThisRoot)
770 return;
771
772 // Both dominators and postdominators have a single root node. In the case
773 // case of PostDominatorTree, this node is a virtual root.
774 WorkStack.push_back({ThisRoot, ThisRoot->begin()});
775
776 unsigned DFSNum = 0;
777 ThisRoot->DFSNumIn = DFSNum++;
778
779 while (!WorkStack.empty()) {
780 const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
781 const auto ChildIt = WorkStack.back().second;
782
783 // If we visited all of the children of this node, "recurse" back up the
784 // stack setting the DFOutNum.
785 if (ChildIt == Node->end()) {
786 Node->DFSNumOut = DFSNum;
787 WorkStack.pop_back();
788 } else {
789 // Otherwise, recursively visit this child.
790 const DomTreeNodeBase<NodeT> *Child = *ChildIt;
791 ++WorkStack.back().second;
792
793 WorkStack.push_back({Child, Child->begin()});
794 Child->DFSNumIn = DFSNum++;
795 }
796 }
797
798 SlowQueries = 0;
799 DFSInfoValid = true;
800 }
801
802private:
803 void updateBlockNumberEpoch() {
805 }
806
807public:
808 /// recalculate - compute a dominator tree for the given function
810
812
813 /// Update dominator tree after renumbering blocks.
815 updateBlockNumberEpoch();
816
817 unsigned MaxNumber = GraphTraits<ParentPtr>::getMaxNumber(Parent);
818 DomTreeNodeStorageTy NewVector;
819 NewVector.resize(MaxNumber + IsPostDom); // index 0 is for nullptr
821 if (Node)
822 NewVector[getNodeIndex(Node->getBlock())] = Node;
823 }
824 DomTreeNodes = std::move(NewVector);
825 }
826
827 /// verify - checks if the tree is correct. There are 3 level of verification:
828 /// - Full -- verifies if the tree is correct by making sure all the
829 /// properties (including the parent and the sibling property)
830 /// hold.
831 /// Takes O(N^3) time.
832 ///
833 /// - Basic -- checks if the tree is correct, but compares it to a freshly
834 /// constructed tree instead of checking the sibling property.
835 /// Takes O(N^2) time.
836 ///
837 /// - Fast -- checks basic tree structure and compares it with a freshly
838 /// constructed tree.
839 /// Takes O(N^2) time worst case, but is faster in practise (same
840 /// as tree construction).
842
843 void reset() {
844 DomTreeNodes.clear();
845 Roots.clear();
846 RootNode = nullptr;
847 Parent = nullptr;
848 DFSInfoValid = false;
849 NodeAllocator.Reset();
850 SlowQueries = 0;
851 }
852
853protected:
854 inline void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
855
856 /// Create a node for \p BB; the caller must link it with addChild.
859 static_assert(std::is_trivially_destructible_v<DomTreeNodeBase<NodeT>>);
860 auto *Node = new (NodeAllocator) DomTreeNodeBase<NodeT>(BB, IDom);
861 unsigned Idx = getNodeIndex(BB);
862 if (Idx >= DomTreeNodes.size()) {
863 // Add 1 for post-dominator trees, 0 is nullptr block.
864 unsigned Max = GraphTraits<ParentPtr>::getMaxNumber(Parent) + IsPostDom;
865 assert(Idx < Max && "getMaxNumber returned too small value");
866 DomTreeNodes.resize(Max);
867 }
868 DomTreeNodes[Idx] = Node;
869 return Node;
870 }
871
873 DomTreeNodeBase<NodeT> *IDom = nullptr) {
874 auto *Node = createNodeUnlinked(BB, IDom);
875 if (IDom)
876 IDom->addChild(Node);
877 return Node;
878 }
879
880 // NewBB is split and now it has one successor. Update dominator tree to
881 // reflect this change.
882 template <class N>
883 void Split(typename GraphTraits<N>::NodeRef NewBB) {
884 using GraphT = GraphTraits<N>;
885 using NodeRef = typename GraphT::NodeRef;
887 "NewBB should have a single successor!");
888 NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
889
891
892 assert(!PredBlocks.empty() && "No predblocks?");
893
894 bool NewBBDominatesNewBBSucc = true;
895 for (auto *Pred : inverse_children<N>(NewBBSucc)) {
896 if (Pred != NewBB && !dominates(NewBBSucc, Pred) &&
897 isReachableFromEntry(Pred)) {
898 NewBBDominatesNewBBSucc = false;
899 break;
900 }
901 }
902
903 // Find NewBB's immediate dominator and create new dominator tree node for
904 // NewBB.
905 NodeT *NewBBIDom = nullptr;
906 unsigned i = 0;
907 for (i = 0; i < PredBlocks.size(); ++i)
908 if (isReachableFromEntry(PredBlocks[i])) {
909 NewBBIDom = PredBlocks[i];
910 break;
911 }
912
913 // It's possible that none of the predecessors of NewBB are reachable;
914 // in that case, NewBB itself is unreachable, so nothing needs to be
915 // changed.
916 if (!NewBBIDom) return;
917
918 for (i = i + 1; i < PredBlocks.size(); ++i) {
919 if (isReachableFromEntry(PredBlocks[i]))
920 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
921 }
922
923 // Create the new dominator tree node... and set the idom of NewBB.
924 DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom);
925
926 // If NewBB strictly dominates other blocks, then it is now the immediate
927 // dominator of NewBBSucc. Update the dominator tree as appropriate.
928 if (NewBBDominatesNewBBSucc) {
929 DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc);
930 changeImmediateDominator(NewBBSuccNode, NewBBNode);
931 }
932 }
933
934 private:
935 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
936 const DomTreeNodeBase<NodeT> *B) const {
937 assert(A != B);
938 assert(A && B);
939
940 const unsigned ALevel = A->getLevel();
941 const DomTreeNodeBase<NodeT> *IDom;
942
943 // Don't walk nodes above A's subtree. When we reach A's level, we must
944 // either find A or be in some other subtree not dominated by A.
945 while ((IDom = B->getIDom()) != nullptr && IDom->getLevel() >= ALevel)
946 B = IDom; // Walk up the tree
947
948 return B == A;
949 }
950};
951
952template <typename T>
954
955template <typename T>
957
958// These two functions are declared out of line as a workaround for building
959// with old (< r147295) versions of clang because of pr11642.
960template <typename NodeT, bool IsPostDom>
962 const NodeT *B) const {
963 if (A == B)
964 return true;
965
966 return dominates(getNode(A), getNode(B));
967}
968template <typename NodeT, bool IsPostDom>
970 const NodeT *A, const NodeT *B) const {
971 if (A == B)
972 return false;
973
974 return dominates(getNode(A), getNode(B));
975}
976
977} // end namespace llvm
978
979#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)
Unify divergent function exit nodes
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition Allocator.h:71
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)
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
Core dominator tree base class.
DominatorTreeBase(DominatorTreeBase &&Arg)=default
DomTreeNodeTraits< BlockT > NodeTrait
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
BumpPtrAllocatorImpl< MallocAllocator, SlabSize, SlabSize, 2 > NodeAllocator
bool isPostDominator() const
isPostDominator - Returns true if analysis based of postdoms
DomTreeNodeBase< NodeT > * createNodeUnlinked(NodeT *BB, DomTreeNodeBase< NodeT > *IDom)
Create a node for BB; the caller must link it with addChild.
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.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void updateBlockNumbers()
Update dominator tree after renumbering blocks.
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.
SmallVector< DomTreeNodeBase< BlockT > * > DomTreeNodeStorageTy
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
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
This class builds and contains all of the top-level loop structures in the specified function.
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
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.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
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:1765
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.
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:299
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:551
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:880
#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