LLVM 19.0.0git
GenericDomTreeConstruction.h
Go to the documentation of this file.
1//===- GenericDomTreeConstruction.h - Dominator Calculation ------*- 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/// Generic dominator tree construction - this file provides routines to
11/// construct immediate dominator information for a flow-graph based on the
12/// Semi-NCA algorithm described in this dissertation:
13///
14/// [1] Linear-Time Algorithms for Dominators and Related Problems
15/// Loukas Georgiadis, Princeton University, November 2005, pp. 21-23:
16/// ftp://ftp.cs.princeton.edu/reports/2005/737.pdf
17///
18/// Semi-NCA algorithm runs in O(n^2) worst-case time but usually slightly
19/// faster than Simple Lengauer-Tarjan in practice.
20///
21/// O(n^2) worst cases happen when the computation of nearest common ancestors
22/// requires O(n) average time, which is very unlikely in real world. If this
23/// ever turns out to be an issue, consider implementing a hybrid algorithm
24/// that uses SLT to perform full constructions and SemiNCA for incremental
25/// updates.
26///
27/// The file uses the Depth Based Search algorithm to perform incremental
28/// updates (insertion and deletions). The implemented algorithm is based on
29/// this publication:
30///
31/// [2] An Experimental Study of Dynamic Dominators
32/// Loukas Georgiadis, et al., April 12 2016, pp. 5-7, 9-10:
33/// https://arxiv.org/pdf/1604.02711.pdf
34///
35//===----------------------------------------------------------------------===//
36
37#ifndef LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
38#define LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
39
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseSet.h"
44#include "llvm/Support/Debug.h"
46#include <optional>
47#include <queue>
48
49#define DEBUG_TYPE "dom-tree-builder"
50
51namespace llvm {
52namespace DomTreeBuilder {
53
54template <typename DomTreeT>
56 using NodePtr = typename DomTreeT::NodePtr;
57 using NodeT = typename DomTreeT::NodeType;
59 using RootsT = decltype(DomTreeT::Roots);
60 static constexpr bool IsPostDom = DomTreeT::IsPostDominator;
62
63 // Information record used by Semi-NCA during tree construction.
64 struct InfoRec {
65 unsigned DFSNum = 0;
66 unsigned Parent = 0;
67 unsigned Semi = 0;
68 unsigned Label = 0;
69 NodePtr IDom = nullptr;
71 };
72
73 // Number to node mapping is 1-based. Initialize the mapping to start with
74 // a dummy element.
77
78 using UpdateT = typename DomTreeT::UpdateType;
79 using UpdateKind = typename DomTreeT::UpdateKind;
81 // Note: Updates inside PreViewCFG are already legalized.
84 NumLegalized(PreViewCFG.getNumLegalizedUpdates()) {}
85
86 // Remembers if the whole tree was recalculated at some point during the
87 // current batch update.
88 bool IsRecalculated = false;
91 const size_t NumLegalized;
92 };
93
96
97 // If BUI is a nullptr, then there's no batch update in progress.
99
100 void clear() {
101 NumToNode = {nullptr}; // Restore to initial state with a dummy start node.
102 NodeToInfo.clear();
103 // Don't reset the pointer to BatchUpdateInfo here -- if there's an update
104 // in progress, we need this information to continue it.
105 }
106
107 template <bool Inversed>
109 if (BUI)
110 return BUI->PreViewCFG.template getChildren<Inversed>(N);
111 return getChildren<Inversed>(N);
112 }
113
114 template <bool Inversed>
116 using DirectedNodeT =
117 std::conditional_t<Inversed, Inverse<NodePtr>, NodePtr>;
118 auto R = children<DirectedNodeT>(N);
119 SmallVector<NodePtr, 8> Res(detail::reverse_if<!Inversed>(R));
120
121 // Remove nullptr children for clang.
122 llvm::erase(Res, nullptr);
123 return Res;
124 }
125
127 auto InfoIt = NodeToInfo.find(BB);
128 if (InfoIt == NodeToInfo.end()) return nullptr;
129
130 return InfoIt->second.IDom;
131 }
132
134 if (TreeNodePtr Node = DT.getNode(BB)) return Node;
135
136 // Haven't calculated this node yet? Get or calculate the node for the
137 // immediate dominator.
138 NodePtr IDom = getIDom(BB);
139
140 assert(IDom || DT.DomTreeNodes[nullptr]);
141 TreeNodePtr IDomNode = getNodeForBlock(IDom, DT);
142
143 // Add a new tree node for this NodeT, and link it as a child of
144 // IDomNode
145 return DT.createChild(BB, IDomNode);
146 }
147
148 static bool AlwaysDescend(NodePtr, NodePtr) { return true; }
149
152
154 BlockNamePrinter(TreeNodePtr TN) : N(TN ? TN->getBlock() : nullptr) {}
155
157 if (!BP.N)
158 O << "nullptr";
159 else
160 BP.N->printAsOperand(O, false);
161
162 return O;
163 }
164 };
165
167
168 // Custom DFS implementation which can skip nodes based on a provided
169 // predicate. It also collects ReverseChildren so that we don't have to spend
170 // time getting predecessors in SemiNCA.
171 //
172 // If IsReverse is set to true, the DFS walk will be performed backwards
173 // relative to IsPostDom -- using reverse edges for dominators and forward
174 // edges for postdominators.
175 //
176 // If SuccOrder is specified then in this order the DFS traverses the children
177 // otherwise the order is implied by the results of getChildren().
178 template <bool IsReverse = false, typename DescendCondition>
179 unsigned runDFS(NodePtr V, unsigned LastNum, DescendCondition Condition,
180 unsigned AttachToNum,
181 const NodeOrderMap *SuccOrder = nullptr) {
182 assert(V);
183 SmallVector<NodePtr, 64> WorkList = {V};
184 NodeToInfo[V].Parent = AttachToNum;
185
186 while (!WorkList.empty()) {
187 const NodePtr BB = WorkList.pop_back_val();
188 auto &BBInfo = NodeToInfo[BB];
189
190 // Visited nodes always have positive DFS numbers.
191 if (BBInfo.DFSNum != 0) continue;
192 BBInfo.DFSNum = BBInfo.Semi = BBInfo.Label = ++LastNum;
194
195 constexpr bool Direction = IsReverse != IsPostDom; // XOR.
196 auto Successors = getChildren<Direction>(BB, BatchUpdates);
197 if (SuccOrder && Successors.size() > 1)
199 Successors.begin(), Successors.end(), [=](NodePtr A, NodePtr B) {
200 return SuccOrder->find(A)->second < SuccOrder->find(B)->second;
201 });
202
203 for (const NodePtr Succ : Successors) {
204 const auto SIT = NodeToInfo.find(Succ);
205 // Don't visit nodes more than once but remember to collect
206 // ReverseChildren.
207 if (SIT != NodeToInfo.end() && SIT->second.DFSNum != 0) {
208 if (Succ != BB) SIT->second.ReverseChildren.push_back(LastNum);
209 continue;
210 }
211
212 if (!Condition(BB, Succ)) continue;
213
214 // It's fine to add Succ to the map, because we know that it will be
215 // visited later.
216 auto &SuccInfo = NodeToInfo[Succ];
217 WorkList.push_back(Succ);
218 SuccInfo.Parent = LastNum;
219 SuccInfo.ReverseChildren.push_back(LastNum);
220 }
221 }
222
223 return LastNum;
224 }
225
226 // V is a predecessor of W. eval() returns V if V < W, otherwise the minimum
227 // of sdom(U), where U > W and there is a virtual forest path from U to V. The
228 // virtual forest consists of linked edges of processed vertices.
229 //
230 // We can follow Parent pointers (virtual forest edges) to determine the
231 // ancestor U with minimum sdom(U). But it is slow and thus we employ the path
232 // compression technique to speed up to O(m*log(n)). Theoretically the virtual
233 // forest can be organized as balanced trees to achieve almost linear
234 // O(m*alpha(m,n)) running time. But it requires two auxiliary arrays (Size
235 // and Child) and is unlikely to be faster than the simple implementation.
236 //
237 // For each vertex V, its Label points to the vertex with the minimal sdom(U)
238 // (Semi) in its path from V (included) to NodeToInfo[V].Parent (excluded).
239 unsigned eval(unsigned V, unsigned LastLinked,
241 ArrayRef<InfoRec *> NumToInfo) {
242 InfoRec *VInfo = NumToInfo[V];
243 if (VInfo->Parent < LastLinked)
244 return VInfo->Label;
245
246 // Store ancestors except the last (root of a virtual tree) into a stack.
247 assert(Stack.empty());
248 do {
249 Stack.push_back(VInfo);
250 VInfo = NumToInfo[VInfo->Parent];
251 } while (VInfo->Parent >= LastLinked);
252
253 // Path compression. Point each vertex's Parent to the root and update its
254 // Label if any of its ancestors (PInfo->Label) has a smaller Semi.
255 const InfoRec *PInfo = VInfo;
256 const InfoRec *PLabelInfo = NumToInfo[PInfo->Label];
257 do {
258 VInfo = Stack.pop_back_val();
259 VInfo->Parent = PInfo->Parent;
260 const InfoRec *VLabelInfo = NumToInfo[VInfo->Label];
261 if (PLabelInfo->Semi < VLabelInfo->Semi)
262 VInfo->Label = PInfo->Label;
263 else
264 PLabelInfo = VLabelInfo;
265 PInfo = VInfo;
266 } while (!Stack.empty());
267 return VInfo->Label;
268 }
269
270 // This function requires DFS to be run before calling it.
271 void runSemiNCA() {
272 const unsigned NextDFSNum(NumToNode.size());
273 SmallVector<InfoRec *, 8> NumToInfo = {nullptr};
274 NumToInfo.reserve(NextDFSNum);
275 // Initialize IDoms to spanning tree parents.
276 for (unsigned i = 1; i < NextDFSNum; ++i) {
277 const NodePtr V = NumToNode[i];
278 auto &VInfo = NodeToInfo[V];
279 VInfo.IDom = NumToNode[VInfo.Parent];
280 NumToInfo.push_back(&VInfo);
281 }
282
283 // Step #1: Calculate the semidominators of all vertices.
285 for (unsigned i = NextDFSNum - 1; i >= 2; --i) {
286 auto &WInfo = *NumToInfo[i];
287
288 // Initialize the semi dominator to point to the parent node.
289 WInfo.Semi = WInfo.Parent;
290 for (unsigned N : WInfo.ReverseChildren) {
291 unsigned SemiU = NumToInfo[eval(N, i + 1, EvalStack, NumToInfo)]->Semi;
292 if (SemiU < WInfo.Semi) WInfo.Semi = SemiU;
293 }
294 }
295
296 // Step #2: Explicitly define the immediate dominator of each vertex.
297 // IDom[i] = NCA(SDom[i], SpanningTreeParent(i)).
298 // Note that the parents were stored in IDoms and later got invalidated
299 // during path compression in Eval.
300 for (unsigned i = 2; i < NextDFSNum; ++i) {
301 auto &WInfo = *NumToInfo[i];
302 assert(WInfo.Semi != 0);
303 const unsigned SDomNum = NumToInfo[WInfo.Semi]->DFSNum;
304 NodePtr WIDomCandidate = WInfo.IDom;
305 while (true) {
306 auto &WIDomCandidateInfo = NodeToInfo.find(WIDomCandidate)->second;
307 if (WIDomCandidateInfo.DFSNum <= SDomNum)
308 break;
309 WIDomCandidate = WIDomCandidateInfo.IDom;
310 }
311
312 WInfo.IDom = WIDomCandidate;
313 }
314 }
315
316 // PostDominatorTree always has a virtual root that represents a virtual CFG
317 // node that serves as a single exit from the function. All the other exits
318 // (CFG nodes with terminators and nodes in infinite loops are logically
319 // connected to this virtual CFG exit node).
320 // This functions maps a nullptr CFG node to the virtual root tree node.
322 assert(IsPostDom && "Only postdominators have a virtual root");
323 assert(NumToNode.size() == 1 && "SNCAInfo must be freshly constructed");
324
325 auto &BBInfo = NodeToInfo[nullptr];
326 BBInfo.DFSNum = BBInfo.Semi = BBInfo.Label = 1;
327
328 NumToNode.push_back(nullptr); // NumToNode[1] = nullptr;
329 }
330
331 // For postdominators, nodes with no forward successors are trivial roots that
332 // are always selected as tree roots. Roots with forward successors correspond
333 // to CFG nodes within infinite loops.
335 assert(N && "N must be a valid node");
336 return !getChildren<false>(N, BUI).empty();
337 }
338
339 static NodePtr GetEntryNode(const DomTreeT &DT) {
340 assert(DT.Parent && "Parent not set");
342 }
343
344 // Finds all roots without relaying on the set of roots already stored in the
345 // tree.
346 // We define roots to be some non-redundant set of the CFG nodes
347 static RootsT FindRoots(const DomTreeT &DT, BatchUpdatePtr BUI) {
348 assert(DT.Parent && "Parent pointer is not set");
349 RootsT Roots;
350
351 // For dominators, function entry CFG node is always a tree root node.
352 if (!IsPostDom) {
353 Roots.push_back(GetEntryNode(DT));
354 return Roots;
355 }
356
357 SemiNCAInfo SNCA(BUI);
358
359 // PostDominatorTree always has a virtual root.
360 SNCA.addVirtualRoot();
361 unsigned Num = 1;
362
363 LLVM_DEBUG(dbgs() << "\t\tLooking for trivial roots\n");
364
365 // Step #1: Find all the trivial roots that are going to will definitely
366 // remain tree roots.
367 unsigned Total = 0;
368 // It may happen that there are some new nodes in the CFG that are result of
369 // the ongoing batch update, but we cannot really pretend that they don't
370 // exist -- we won't see any outgoing or incoming edges to them, so it's
371 // fine to discover them here, as they would end up appearing in the CFG at
372 // some point anyway.
373 for (const NodePtr N : nodes(DT.Parent)) {
374 ++Total;
375 // If it has no *successors*, it is definitely a root.
376 if (!HasForwardSuccessors(N, BUI)) {
377 Roots.push_back(N);
378 // Run DFS not to walk this part of CFG later.
379 Num = SNCA.runDFS(N, Num, AlwaysDescend, 1);
380 LLVM_DEBUG(dbgs() << "Found a new trivial root: " << BlockNamePrinter(N)
381 << "\n");
382 LLVM_DEBUG(dbgs() << "Last visited node: "
383 << BlockNamePrinter(SNCA.NumToNode[Num]) << "\n");
384 }
385 }
386
387 LLVM_DEBUG(dbgs() << "\t\tLooking for non-trivial roots\n");
388
389 // Step #2: Find all non-trivial root candidates. Those are CFG nodes that
390 // are reverse-unreachable were not visited by previous DFS walks (i.e. CFG
391 // nodes in infinite loops).
392 bool HasNonTrivialRoots = false;
393 // Accounting for the virtual exit, see if we had any reverse-unreachable
394 // nodes.
395 if (Total + 1 != Num) {
396 HasNonTrivialRoots = true;
397
398 // SuccOrder is the order of blocks in the function. It is needed to make
399 // the calculation of the FurthestAway node and the whole PostDomTree
400 // immune to swap successors transformation (e.g. canonicalizing branch
401 // predicates). SuccOrder is initialized lazily only for successors of
402 // reverse unreachable nodes.
403 std::optional<NodeOrderMap> SuccOrder;
404 auto InitSuccOrderOnce = [&]() {
405 SuccOrder = NodeOrderMap();
406 for (const auto Node : nodes(DT.Parent))
407 if (SNCA.NodeToInfo.count(Node) == 0)
408 for (const auto Succ : getChildren<false>(Node, SNCA.BatchUpdates))
409 SuccOrder->try_emplace(Succ, 0);
410
411 // Add mapping for all entries of SuccOrder.
412 unsigned NodeNum = 0;
413 for (const auto Node : nodes(DT.Parent)) {
414 ++NodeNum;
415 auto Order = SuccOrder->find(Node);
416 if (Order != SuccOrder->end()) {
417 assert(Order->second == 0);
418 Order->second = NodeNum;
419 }
420 }
421 };
422
423 // Make another DFS pass over all other nodes to find the
424 // reverse-unreachable blocks, and find the furthest paths we'll be able
425 // to make.
426 // Note that this looks N^2, but it's really 2N worst case, if every node
427 // is unreachable. This is because we are still going to only visit each
428 // unreachable node once, we may just visit it in two directions,
429 // depending on how lucky we get.
430 for (const NodePtr I : nodes(DT.Parent)) {
431 if (SNCA.NodeToInfo.count(I) == 0) {
433 << "\t\t\tVisiting node " << BlockNamePrinter(I) << "\n");
434 // Find the furthest away we can get by following successors, then
435 // follow them in reverse. This gives us some reasonable answer about
436 // the post-dom tree inside any infinite loop. In particular, it
437 // guarantees we get to the farthest away point along *some*
438 // path. This also matches the GCC's behavior.
439 // If we really wanted a totally complete picture of dominance inside
440 // this infinite loop, we could do it with SCC-like algorithms to find
441 // the lowest and highest points in the infinite loop. In theory, it
442 // would be nice to give the canonical backedge for the loop, but it's
443 // expensive and does not always lead to a minimal set of roots.
444 LLVM_DEBUG(dbgs() << "\t\t\tRunning forward DFS\n");
445
446 if (!SuccOrder)
447 InitSuccOrderOnce();
448 assert(SuccOrder);
449
450 const unsigned NewNum =
451 SNCA.runDFS<true>(I, Num, AlwaysDescend, Num, &*SuccOrder);
452 const NodePtr FurthestAway = SNCA.NumToNode[NewNum];
453 LLVM_DEBUG(dbgs() << "\t\t\tFound a new furthest away node "
454 << "(non-trivial root): "
455 << BlockNamePrinter(FurthestAway) << "\n");
456 Roots.push_back(FurthestAway);
457 LLVM_DEBUG(dbgs() << "\t\t\tPrev DFSNum: " << Num << ", new DFSNum: "
458 << NewNum << "\n\t\t\tRemoving DFS info\n");
459 for (unsigned i = NewNum; i > Num; --i) {
460 const NodePtr N = SNCA.NumToNode[i];
461 LLVM_DEBUG(dbgs() << "\t\t\t\tRemoving DFS info for "
462 << BlockNamePrinter(N) << "\n");
463 SNCA.NodeToInfo.erase(N);
464 SNCA.NumToNode.pop_back();
465 }
466 const unsigned PrevNum = Num;
467 LLVM_DEBUG(dbgs() << "\t\t\tRunning reverse DFS\n");
468 Num = SNCA.runDFS(FurthestAway, Num, AlwaysDescend, 1);
469 for (unsigned i = PrevNum + 1; i <= Num; ++i)
470 LLVM_DEBUG(dbgs() << "\t\t\t\tfound node "
471 << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
472 }
473 }
474 }
475
476 LLVM_DEBUG(dbgs() << "Total: " << Total << ", Num: " << Num << "\n");
477 LLVM_DEBUG(dbgs() << "Discovered CFG nodes:\n");
478 LLVM_DEBUG(for (size_t i = 0; i <= Num; ++i) dbgs()
479 << i << ": " << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
480
481 assert((Total + 1 == Num) && "Everything should have been visited");
482
483 // Step #3: If we found some non-trivial roots, make them non-redundant.
484 if (HasNonTrivialRoots) RemoveRedundantRoots(DT, BUI, Roots);
485
486 LLVM_DEBUG(dbgs() << "Found roots: ");
487 LLVM_DEBUG(for (auto *Root
488 : Roots) dbgs()
489 << BlockNamePrinter(Root) << " ");
490 LLVM_DEBUG(dbgs() << "\n");
491
492 return Roots;
493 }
494
495 // This function only makes sense for postdominators.
496 // We define roots to be some set of CFG nodes where (reverse) DFS walks have
497 // to start in order to visit all the CFG nodes (including the
498 // reverse-unreachable ones).
499 // When the search for non-trivial roots is done it may happen that some of
500 // the non-trivial roots are reverse-reachable from other non-trivial roots,
501 // which makes them redundant. This function removes them from the set of
502 // input roots.
503 static void RemoveRedundantRoots(const DomTreeT &DT, BatchUpdatePtr BUI,
504 RootsT &Roots) {
505 assert(IsPostDom && "This function is for postdominators only");
506 LLVM_DEBUG(dbgs() << "Removing redundant roots\n");
507
508 SemiNCAInfo SNCA(BUI);
509
510 for (unsigned i = 0; i < Roots.size(); ++i) {
511 auto &Root = Roots[i];
512 // Trivial roots are always non-redundant.
513 if (!HasForwardSuccessors(Root, BUI)) continue;
514 LLVM_DEBUG(dbgs() << "\tChecking if " << BlockNamePrinter(Root)
515 << " remains a root\n");
516 SNCA.clear();
517 // Do a forward walk looking for the other roots.
518 const unsigned Num = SNCA.runDFS<true>(Root, 0, AlwaysDescend, 0);
519 // Skip the start node and begin from the second one (note that DFS uses
520 // 1-based indexing).
521 for (unsigned x = 2; x <= Num; ++x) {
522 const NodePtr N = SNCA.NumToNode[x];
523 // If we wound another root in a (forward) DFS walk, remove the current
524 // root from the set of roots, as it is reverse-reachable from the other
525 // one.
526 if (llvm::is_contained(Roots, N)) {
527 LLVM_DEBUG(dbgs() << "\tForward DFS walk found another root "
528 << BlockNamePrinter(N) << "\n\tRemoving root "
529 << BlockNamePrinter(Root) << "\n");
530 std::swap(Root, Roots.back());
531 Roots.pop_back();
532
533 // Root at the back takes the current root's place.
534 // Start the next loop iteration with the same index.
535 --i;
536 break;
537 }
538 }
539 }
540 }
541
542 template <typename DescendCondition>
543 void doFullDFSWalk(const DomTreeT &DT, DescendCondition DC) {
544 if (!IsPostDom) {
545 assert(DT.Roots.size() == 1 && "Dominators should have a singe root");
546 runDFS(DT.Roots[0], 0, DC, 0);
547 return;
548 }
549
551 unsigned Num = 1;
552 for (const NodePtr Root : DT.Roots) Num = runDFS(Root, Num, DC, 1);
553 }
554
555 static void CalculateFromScratch(DomTreeT &DT, BatchUpdatePtr BUI) {
556 auto *Parent = DT.Parent;
557 DT.reset();
558 DT.Parent = Parent;
559 // If the update is using the actual CFG, BUI is null. If it's using a view,
560 // BUI is non-null and the PreCFGView is used. When calculating from
561 // scratch, make the PreViewCFG equal to the PostCFGView, so Post is used.
562 BatchUpdatePtr PostViewBUI = nullptr;
563 if (BUI && BUI->PostViewCFG) {
564 BUI->PreViewCFG = *BUI->PostViewCFG;
565 PostViewBUI = BUI;
566 }
567 // This is rebuilding the whole tree, not incrementally, but PostViewBUI is
568 // used in case the caller needs a DT update with a CFGView.
569 SemiNCAInfo SNCA(PostViewBUI);
570
571 // Step #0: Number blocks in depth-first order and initialize variables used
572 // in later stages of the algorithm.
573 DT.Roots = FindRoots(DT, PostViewBUI);
575
576 SNCA.runSemiNCA();
577 if (BUI) {
578 BUI->IsRecalculated = true;
580 dbgs() << "DomTree recalculated, skipping future batch updates\n");
581 }
582
583 if (DT.Roots.empty()) return;
584
585 // Add a node for the root. If the tree is a PostDominatorTree it will be
586 // the virtual exit (denoted by (BasicBlock *) nullptr) which postdominates
587 // all real exits (including multiple exit blocks, infinite loops).
588 NodePtr Root = IsPostDom ? nullptr : DT.Roots[0];
589
590 DT.RootNode = DT.createNode(Root);
591 SNCA.attachNewSubtree(DT, DT.RootNode);
592 }
593
594 void attachNewSubtree(DomTreeT& DT, const TreeNodePtr AttachTo) {
595 // Attach the first unreachable block to AttachTo.
596 NodeToInfo[NumToNode[1]].IDom = AttachTo->getBlock();
597 // Loop over all of the discovered blocks in the function...
599 // Don't replace this with 'count', the insertion side effect is important
600 if (DT.DomTreeNodes[W]) continue; // Haven't calculated this node yet?
601
602 NodePtr ImmDom = getIDom(W);
603
604 // Get or calculate the node for the immediate dominator.
605 TreeNodePtr IDomNode = getNodeForBlock(ImmDom, DT);
606
607 // Add a new tree node for this BasicBlock, and link it as a child of
608 // IDomNode.
609 DT.createChild(W, IDomNode);
610 }
611 }
612
613 void reattachExistingSubtree(DomTreeT &DT, const TreeNodePtr AttachTo) {
614 NodeToInfo[NumToNode[1]].IDom = AttachTo->getBlock();
615 for (const NodePtr N : llvm::drop_begin(NumToNode)) {
616 const TreeNodePtr TN = DT.getNode(N);
617 assert(TN);
618 const TreeNodePtr NewIDom = DT.getNode(NodeToInfo[N].IDom);
619 TN->setIDom(NewIDom);
620 }
621 }
622
623 // Helper struct used during edge insertions.
625 struct Compare {
627 return LHS->getLevel() < RHS->getLevel();
628 }
629 };
630
631 // Bucket queue of tree nodes ordered by descending level. For simplicity,
632 // we use a priority_queue here.
633 std::priority_queue<TreeNodePtr, SmallVector<TreeNodePtr, 8>,
634 Compare>
638#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
639 SmallVector<TreeNodePtr, 8> VisitedUnaffected;
640#endif
641 };
642
643 static void InsertEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
644 const NodePtr From, const NodePtr To) {
645 assert((From || IsPostDom) &&
646 "From has to be a valid CFG node or a virtual root");
647 assert(To && "Cannot be a nullptr");
648 LLVM_DEBUG(dbgs() << "Inserting edge " << BlockNamePrinter(From) << " -> "
649 << BlockNamePrinter(To) << "\n");
650 TreeNodePtr FromTN = DT.getNode(From);
651
652 if (!FromTN) {
653 // Ignore edges from unreachable nodes for (forward) dominators.
654 if (!IsPostDom) return;
655
656 // The unreachable node becomes a new root -- a tree node for it.
657 TreeNodePtr VirtualRoot = DT.getNode(nullptr);
658 FromTN = DT.createChild(From, VirtualRoot);
659 DT.Roots.push_back(From);
660 }
661
662 DT.DFSInfoValid = false;
663
664 const TreeNodePtr ToTN = DT.getNode(To);
665 if (!ToTN)
666 InsertUnreachable(DT, BUI, FromTN, To);
667 else
668 InsertReachable(DT, BUI, FromTN, ToTN);
669 }
670
671 // Determines if some existing root becomes reverse-reachable after the
672 // insertion. Rebuilds the whole tree if that situation happens.
673 static bool UpdateRootsBeforeInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
674 const TreeNodePtr From,
675 const TreeNodePtr To) {
676 assert(IsPostDom && "This function is only for postdominators");
677 // Destination node is not attached to the virtual root, so it cannot be a
678 // root.
679 if (!DT.isVirtualRoot(To->getIDom())) return false;
680
681 if (!llvm::is_contained(DT.Roots, To->getBlock()))
682 return false; // To is not a root, nothing to update.
683
684 LLVM_DEBUG(dbgs() << "\t\tAfter the insertion, " << BlockNamePrinter(To)
685 << " is no longer a root\n\t\tRebuilding the tree!!!\n");
686
687 CalculateFromScratch(DT, BUI);
688 return true;
689 }
690
693 if (A.size() != B.size())
694 return false;
695 SmallPtrSet<NodePtr, 4> Set(A.begin(), A.end());
696 for (NodePtr N : B)
697 if (Set.count(N) == 0)
698 return false;
699 return true;
700 }
701
702 // Updates the set of roots after insertion or deletion. This ensures that
703 // roots are the same when after a series of updates and when the tree would
704 // be built from scratch.
705 static void UpdateRootsAfterUpdate(DomTreeT &DT, const BatchUpdatePtr BUI) {
706 assert(IsPostDom && "This function is only for postdominators");
707
708 // The tree has only trivial roots -- nothing to update.
709 if (llvm::none_of(DT.Roots, [BUI](const NodePtr N) {
710 return HasForwardSuccessors(N, BUI);
711 }))
712 return;
713
714 // Recalculate the set of roots.
715 RootsT Roots = FindRoots(DT, BUI);
716 if (!isPermutation(DT.Roots, Roots)) {
717 // The roots chosen in the CFG have changed. This is because the
718 // incremental algorithm does not really know or use the set of roots and
719 // can make a different (implicit) decision about which node within an
720 // infinite loop becomes a root.
721
722 LLVM_DEBUG(dbgs() << "Roots are different in updated trees\n"
723 << "The entire tree needs to be rebuilt\n");
724 // It may be possible to update the tree without recalculating it, but
725 // we do not know yet how to do it, and it happens rarely in practice.
726 CalculateFromScratch(DT, BUI);
727 }
728 }
729
730 // Handles insertion to a node already in the dominator tree.
731 static void InsertReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
732 const TreeNodePtr From, const TreeNodePtr To) {
733 LLVM_DEBUG(dbgs() << "\tReachable " << BlockNamePrinter(From->getBlock())
734 << " -> " << BlockNamePrinter(To->getBlock()) << "\n");
735 if (IsPostDom && UpdateRootsBeforeInsertion(DT, BUI, From, To)) return;
736 // DT.findNCD expects both pointers to be valid. When From is a virtual
737 // root, then its CFG block pointer is a nullptr, so we have to 'compute'
738 // the NCD manually.
739 const NodePtr NCDBlock =
740 (From->getBlock() && To->getBlock())
741 ? DT.findNearestCommonDominator(From->getBlock(), To->getBlock())
742 : nullptr;
743 assert(NCDBlock || DT.isPostDominator());
744 const TreeNodePtr NCD = DT.getNode(NCDBlock);
745 assert(NCD);
746
747 LLVM_DEBUG(dbgs() << "\t\tNCA == " << BlockNamePrinter(NCD) << "\n");
748 const unsigned NCDLevel = NCD->getLevel();
749
750 // Based on Lemma 2.5 from [2], after insertion of (From,To), v is affected
751 // iff depth(NCD)+1 < depth(v) && a path P from To to v exists where every
752 // w on P s.t. depth(v) <= depth(w)
753 //
754 // This reduces to a widest path problem (maximizing the depth of the
755 // minimum vertex in the path) which can be solved by a modified version of
756 // Dijkstra with a bucket queue (named depth-based search in [2]).
757
758 // To is in the path, so depth(NCD)+1 < depth(v) <= depth(To). Nothing
759 // affected if this does not hold.
760 if (NCDLevel + 1 >= To->getLevel())
761 return;
762
764 SmallVector<TreeNodePtr, 8> UnaffectedOnCurrentLevel;
765 II.Bucket.push(To);
766 II.Visited.insert(To);
767
768 while (!II.Bucket.empty()) {
769 TreeNodePtr TN = II.Bucket.top();
770 II.Bucket.pop();
771 II.Affected.push_back(TN);
772
773 const unsigned CurrentLevel = TN->getLevel();
774 LLVM_DEBUG(dbgs() << "Mark " << BlockNamePrinter(TN) <<
775 "as affected, CurrentLevel " << CurrentLevel << "\n");
776
777 assert(TN->getBlock() && II.Visited.count(TN) && "Preconditions!");
778
779 while (true) {
780 // Unlike regular Dijkstra, we have an inner loop to expand more
781 // vertices. The first iteration is for the (affected) vertex popped
782 // from II.Bucket and the rest are for vertices in
783 // UnaffectedOnCurrentLevel, which may eventually expand to affected
784 // vertices.
785 //
786 // Invariant: there is an optimal path from `To` to TN with the minimum
787 // depth being CurrentLevel.
788 for (const NodePtr Succ : getChildren<IsPostDom>(TN->getBlock(), BUI)) {
789 const TreeNodePtr SuccTN = DT.getNode(Succ);
790 assert(SuccTN &&
791 "Unreachable successor found at reachable insertion");
792 const unsigned SuccLevel = SuccTN->getLevel();
793
794 LLVM_DEBUG(dbgs() << "\tSuccessor " << BlockNamePrinter(Succ)
795 << ", level = " << SuccLevel << "\n");
796
797 // There is an optimal path from `To` to Succ with the minimum depth
798 // being min(CurrentLevel, SuccLevel).
799 //
800 // If depth(NCD)+1 < depth(Succ) is not satisfied, Succ is unaffected
801 // and no affected vertex may be reached by a path passing through it.
802 // Stop here. Also, Succ may be visited by other predecessors but the
803 // first visit has the optimal path. Stop if Succ has been visited.
804 if (SuccLevel <= NCDLevel + 1 || !II.Visited.insert(SuccTN).second)
805 continue;
806
807 if (SuccLevel > CurrentLevel) {
808 // Succ is unaffected but it may (transitively) expand to affected
809 // vertices. Store it in UnaffectedOnCurrentLevel.
810 LLVM_DEBUG(dbgs() << "\t\tMarking visited not affected "
811 << BlockNamePrinter(Succ) << "\n");
812 UnaffectedOnCurrentLevel.push_back(SuccTN);
813#ifndef NDEBUG
814 II.VisitedUnaffected.push_back(SuccTN);
815#endif
816 } else {
817 // The condition is satisfied (Succ is affected). Add Succ to the
818 // bucket queue.
819 LLVM_DEBUG(dbgs() << "\t\tAdd " << BlockNamePrinter(Succ)
820 << " to a Bucket\n");
821 II.Bucket.push(SuccTN);
822 }
823 }
824
825 if (UnaffectedOnCurrentLevel.empty())
826 break;
827 TN = UnaffectedOnCurrentLevel.pop_back_val();
828 LLVM_DEBUG(dbgs() << " Next: " << BlockNamePrinter(TN) << "\n");
829 }
830 }
831
832 // Finish by updating immediate dominators and levels.
833 UpdateInsertion(DT, BUI, NCD, II);
834 }
835
836 // Updates immediate dominators and levels after insertion.
837 static void UpdateInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
838 const TreeNodePtr NCD, InsertionInfo &II) {
839 LLVM_DEBUG(dbgs() << "Updating NCD = " << BlockNamePrinter(NCD) << "\n");
840
841 for (const TreeNodePtr TN : II.Affected) {
842 LLVM_DEBUG(dbgs() << "\tIDom(" << BlockNamePrinter(TN)
843 << ") = " << BlockNamePrinter(NCD) << "\n");
844 TN->setIDom(NCD);
845 }
846
847#if defined(LLVM_ENABLE_ABI_BREAKING_CHECKS) && !defined(NDEBUG)
848 for (const TreeNodePtr TN : II.VisitedUnaffected)
849 assert(TN->getLevel() == TN->getIDom()->getLevel() + 1 &&
850 "TN should have been updated by an affected ancestor");
851#endif
852
853 if (IsPostDom) UpdateRootsAfterUpdate(DT, BUI);
854 }
855
856 // Handles insertion to previously unreachable nodes.
857 static void InsertUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
858 const TreeNodePtr From, const NodePtr To) {
859 LLVM_DEBUG(dbgs() << "Inserting " << BlockNamePrinter(From)
860 << " -> (unreachable) " << BlockNamePrinter(To) << "\n");
861
862 // Collect discovered edges to already reachable nodes.
863 SmallVector<std::pair<NodePtr, TreeNodePtr>, 8> DiscoveredEdgesToReachable;
864 // Discover and connect nodes that became reachable with the insertion.
865 ComputeUnreachableDominators(DT, BUI, To, From, DiscoveredEdgesToReachable);
866
867 LLVM_DEBUG(dbgs() << "Inserted " << BlockNamePrinter(From)
868 << " -> (prev unreachable) " << BlockNamePrinter(To)
869 << "\n");
870
871 // Used the discovered edges and inset discovered connecting (incoming)
872 // edges.
873 for (const auto &Edge : DiscoveredEdgesToReachable) {
874 LLVM_DEBUG(dbgs() << "\tInserting discovered connecting edge "
875 << BlockNamePrinter(Edge.first) << " -> "
876 << BlockNamePrinter(Edge.second) << "\n");
877 InsertReachable(DT, BUI, DT.getNode(Edge.first), Edge.second);
878 }
879 }
880
881 // Connects nodes that become reachable with an insertion.
883 DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr Root,
884 const TreeNodePtr Incoming,
885 SmallVectorImpl<std::pair<NodePtr, TreeNodePtr>>
886 &DiscoveredConnectingEdges) {
887 assert(!DT.getNode(Root) && "Root must not be reachable");
888
889 // Visit only previously unreachable nodes.
890 auto UnreachableDescender = [&DT, &DiscoveredConnectingEdges](NodePtr From,
891 NodePtr To) {
892 const TreeNodePtr ToTN = DT.getNode(To);
893 if (!ToTN) return true;
894
895 DiscoveredConnectingEdges.push_back({From, ToTN});
896 return false;
897 };
898
899 SemiNCAInfo SNCA(BUI);
900 SNCA.runDFS(Root, 0, UnreachableDescender, 0);
901 SNCA.runSemiNCA();
902 SNCA.attachNewSubtree(DT, Incoming);
903
904 LLVM_DEBUG(dbgs() << "After adding unreachable nodes\n");
905 }
906
907 static void DeleteEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
908 const NodePtr From, const NodePtr To) {
909 assert(From && To && "Cannot disconnect nullptrs");
910 LLVM_DEBUG(dbgs() << "Deleting edge " << BlockNamePrinter(From) << " -> "
911 << BlockNamePrinter(To) << "\n");
912
913#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
914 // Ensure that the edge was in fact deleted from the CFG before informing
915 // the DomTree about it.
916 // The check is O(N), so run it only in debug configuration.
917 auto IsSuccessor = [BUI](const NodePtr SuccCandidate, const NodePtr Of) {
918 auto Successors = getChildren<IsPostDom>(Of, BUI);
919 return llvm::is_contained(Successors, SuccCandidate);
920 };
921 (void)IsSuccessor;
922 assert(!IsSuccessor(To, From) && "Deleted edge still exists in the CFG!");
923#endif
924
925 const TreeNodePtr FromTN = DT.getNode(From);
926 // Deletion in an unreachable subtree -- nothing to do.
927 if (!FromTN) return;
928
929 const TreeNodePtr ToTN = DT.getNode(To);
930 if (!ToTN) {
932 dbgs() << "\tTo (" << BlockNamePrinter(To)
933 << ") already unreachable -- there is no edge to delete\n");
934 return;
935 }
936
937 const NodePtr NCDBlock = DT.findNearestCommonDominator(From, To);
938 const TreeNodePtr NCD = DT.getNode(NCDBlock);
939
940 // If To dominates From -- nothing to do.
941 if (ToTN != NCD) {
942 DT.DFSInfoValid = false;
943
944 const TreeNodePtr ToIDom = ToTN->getIDom();
945 LLVM_DEBUG(dbgs() << "\tNCD " << BlockNamePrinter(NCD) << ", ToIDom "
946 << BlockNamePrinter(ToIDom) << "\n");
947
948 // To remains reachable after deletion.
949 // (Based on the caption under Figure 4. from [2].)
950 if (FromTN != ToIDom || HasProperSupport(DT, BUI, ToTN))
951 DeleteReachable(DT, BUI, FromTN, ToTN);
952 else
953 DeleteUnreachable(DT, BUI, ToTN);
954 }
955
956 if (IsPostDom) UpdateRootsAfterUpdate(DT, BUI);
957 }
958
959 // Handles deletions that leave destination nodes reachable.
960 static void DeleteReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
961 const TreeNodePtr FromTN,
962 const TreeNodePtr ToTN) {
963 LLVM_DEBUG(dbgs() << "Deleting reachable " << BlockNamePrinter(FromTN)
964 << " -> " << BlockNamePrinter(ToTN) << "\n");
965 LLVM_DEBUG(dbgs() << "\tRebuilding subtree\n");
966
967 // Find the top of the subtree that needs to be rebuilt.
968 // (Based on the lemma 2.6 from [2].)
969 const NodePtr ToIDom =
970 DT.findNearestCommonDominator(FromTN->getBlock(), ToTN->getBlock());
971 assert(ToIDom || DT.isPostDominator());
972 const TreeNodePtr ToIDomTN = DT.getNode(ToIDom);
973 assert(ToIDomTN);
974 const TreeNodePtr PrevIDomSubTree = ToIDomTN->getIDom();
975 // Top of the subtree to rebuild is the root node. Rebuild the tree from
976 // scratch.
977 if (!PrevIDomSubTree) {
978 LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
979 CalculateFromScratch(DT, BUI);
980 return;
981 }
982
983 // Only visit nodes in the subtree starting at To.
984 const unsigned Level = ToIDomTN->getLevel();
985 auto DescendBelow = [Level, &DT](NodePtr, NodePtr To) {
986 return DT.getNode(To)->getLevel() > Level;
987 };
988
989 LLVM_DEBUG(dbgs() << "\tTop of subtree: " << BlockNamePrinter(ToIDomTN)
990 << "\n");
991
992 SemiNCAInfo SNCA(BUI);
993 SNCA.runDFS(ToIDom, 0, DescendBelow, 0);
994 LLVM_DEBUG(dbgs() << "\tRunning Semi-NCA\n");
995 SNCA.runSemiNCA();
996 SNCA.reattachExistingSubtree(DT, PrevIDomSubTree);
997 }
998
999 // Checks if a node has proper support, as defined on the page 3 and later
1000 // explained on the page 7 of [2].
1001 static bool HasProperSupport(DomTreeT &DT, const BatchUpdatePtr BUI,
1002 const TreeNodePtr TN) {
1003 LLVM_DEBUG(dbgs() << "IsReachableFromIDom " << BlockNamePrinter(TN)
1004 << "\n");
1005 auto TNB = TN->getBlock();
1006 for (const NodePtr Pred : getChildren<!IsPostDom>(TNB, BUI)) {
1007 LLVM_DEBUG(dbgs() << "\tPred " << BlockNamePrinter(Pred) << "\n");
1008 if (!DT.getNode(Pred)) continue;
1009
1010 const NodePtr Support = DT.findNearestCommonDominator(TNB, Pred);
1011 LLVM_DEBUG(dbgs() << "\tSupport " << BlockNamePrinter(Support) << "\n");
1012 if (Support != TNB) {
1013 LLVM_DEBUG(dbgs() << "\t" << BlockNamePrinter(TN)
1014 << " is reachable from support "
1015 << BlockNamePrinter(Support) << "\n");
1016 return true;
1017 }
1018 }
1019
1020 return false;
1021 }
1022
1023 // Handle deletions that make destination node unreachable.
1024 // (Based on the lemma 2.7 from the [2].)
1025 static void DeleteUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
1026 const TreeNodePtr ToTN) {
1027 LLVM_DEBUG(dbgs() << "Deleting unreachable subtree "
1028 << BlockNamePrinter(ToTN) << "\n");
1029 assert(ToTN);
1030 assert(ToTN->getBlock());
1031
1032 if (IsPostDom) {
1033 // Deletion makes a region reverse-unreachable and creates a new root.
1034 // Simulate that by inserting an edge from the virtual root to ToTN and
1035 // adding it as a new root.
1036 LLVM_DEBUG(dbgs() << "\tDeletion made a region reverse-unreachable\n");
1037 LLVM_DEBUG(dbgs() << "\tAdding new root " << BlockNamePrinter(ToTN)
1038 << "\n");
1039 DT.Roots.push_back(ToTN->getBlock());
1040 InsertReachable(DT, BUI, DT.getNode(nullptr), ToTN);
1041 return;
1042 }
1043
1044 SmallVector<NodePtr, 16> AffectedQueue;
1045 const unsigned Level = ToTN->getLevel();
1046
1047 // Traverse destination node's descendants with greater level in the tree
1048 // and collect visited nodes.
1049 auto DescendAndCollect = [Level, &AffectedQueue, &DT](NodePtr, NodePtr To) {
1050 const TreeNodePtr TN = DT.getNode(To);
1051 assert(TN);
1052 if (TN->getLevel() > Level) return true;
1053 if (!llvm::is_contained(AffectedQueue, To))
1054 AffectedQueue.push_back(To);
1055
1056 return false;
1057 };
1058
1059 SemiNCAInfo SNCA(BUI);
1060 unsigned LastDFSNum =
1061 SNCA.runDFS(ToTN->getBlock(), 0, DescendAndCollect, 0);
1062
1063 TreeNodePtr MinNode = ToTN;
1064
1065 // Identify the top of the subtree to rebuild by finding the NCD of all
1066 // the affected nodes.
1067 for (const NodePtr N : AffectedQueue) {
1068 const TreeNodePtr TN = DT.getNode(N);
1069 const NodePtr NCDBlock =
1070 DT.findNearestCommonDominator(TN->getBlock(), ToTN->getBlock());
1071 assert(NCDBlock || DT.isPostDominator());
1072 const TreeNodePtr NCD = DT.getNode(NCDBlock);
1073 assert(NCD);
1074
1075 LLVM_DEBUG(dbgs() << "Processing affected node " << BlockNamePrinter(TN)
1076 << " with NCD = " << BlockNamePrinter(NCD)
1077 << ", MinNode =" << BlockNamePrinter(MinNode) << "\n");
1078 if (NCD != TN && NCD->getLevel() < MinNode->getLevel()) MinNode = NCD;
1079 }
1080
1081 // Root reached, rebuild the whole tree from scratch.
1082 if (!MinNode->getIDom()) {
1083 LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
1084 CalculateFromScratch(DT, BUI);
1085 return;
1086 }
1087
1088 // Erase the unreachable subtree in reverse preorder to process all children
1089 // before deleting their parent.
1090 for (unsigned i = LastDFSNum; i > 0; --i) {
1091 const NodePtr N = SNCA.NumToNode[i];
1092 const TreeNodePtr TN = DT.getNode(N);
1093 LLVM_DEBUG(dbgs() << "Erasing node " << BlockNamePrinter(TN) << "\n");
1094
1095 EraseNode(DT, TN);
1096 }
1097
1098 // The affected subtree start at the To node -- there's no extra work to do.
1099 if (MinNode == ToTN) return;
1100
1101 LLVM_DEBUG(dbgs() << "DeleteUnreachable: running DFS with MinNode = "
1102 << BlockNamePrinter(MinNode) << "\n");
1103 const unsigned MinLevel = MinNode->getLevel();
1104 const TreeNodePtr PrevIDom = MinNode->getIDom();
1105 assert(PrevIDom);
1106 SNCA.clear();
1107
1108 // Identify nodes that remain in the affected subtree.
1109 auto DescendBelow = [MinLevel, &DT](NodePtr, NodePtr To) {
1110 const TreeNodePtr ToTN = DT.getNode(To);
1111 return ToTN && ToTN->getLevel() > MinLevel;
1112 };
1113 SNCA.runDFS(MinNode->getBlock(), 0, DescendBelow, 0);
1114
1115 LLVM_DEBUG(dbgs() << "Previous IDom(MinNode) = "
1116 << BlockNamePrinter(PrevIDom) << "\nRunning Semi-NCA\n");
1117
1118 // Rebuild the remaining part of affected subtree.
1119 SNCA.runSemiNCA();
1120 SNCA.reattachExistingSubtree(DT, PrevIDom);
1121 }
1122
1123 // Removes leaf tree nodes from the dominator tree.
1124 static void EraseNode(DomTreeT &DT, const TreeNodePtr TN) {
1125 assert(TN);
1126 assert(TN->getNumChildren() == 0 && "Not a tree leaf");
1127
1128 const TreeNodePtr IDom = TN->getIDom();
1129 assert(IDom);
1130
1131 auto ChIt = llvm::find(IDom->Children, TN);
1132 assert(ChIt != IDom->Children.end());
1133 std::swap(*ChIt, IDom->Children.back());
1134 IDom->Children.pop_back();
1135
1136 DT.DomTreeNodes.erase(TN->getBlock());
1137 }
1138
1139 //~~
1140 //===--------------------- DomTree Batch Updater --------------------------===
1141 //~~
1142
1143 static void ApplyUpdates(DomTreeT &DT, GraphDiffT &PreViewCFG,
1144 GraphDiffT *PostViewCFG) {
1145 // Note: the PostViewCFG is only used when computing from scratch. It's data
1146 // should already included in the PreViewCFG for incremental updates.
1147 const size_t NumUpdates = PreViewCFG.getNumLegalizedUpdates();
1148 if (NumUpdates == 0)
1149 return;
1150
1151 // Take the fast path for a single update and avoid running the batch update
1152 // machinery.
1153 if (NumUpdates == 1) {
1154 UpdateT Update = PreViewCFG.popUpdateForIncrementalUpdates();
1155 if (!PostViewCFG) {
1156 if (Update.getKind() == UpdateKind::Insert)
1157 InsertEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
1158 else
1159 DeleteEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
1160 } else {
1161 BatchUpdateInfo BUI(*PostViewCFG, PostViewCFG);
1162 if (Update.getKind() == UpdateKind::Insert)
1163 InsertEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1164 else
1165 DeleteEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1166 }
1167 return;
1168 }
1169
1170 BatchUpdateInfo BUI(PreViewCFG, PostViewCFG);
1171 // Recalculate the DominatorTree when the number of updates
1172 // exceeds a threshold, which usually makes direct updating slower than
1173 // recalculation. We select this threshold proportional to the
1174 // size of the DominatorTree. The constant is selected
1175 // by choosing the one with an acceptable performance on some real-world
1176 // inputs.
1177
1178 // Make unittests of the incremental algorithm work
1179 if (DT.DomTreeNodes.size() <= 100) {
1180 if (BUI.NumLegalized > DT.DomTreeNodes.size())
1181 CalculateFromScratch(DT, &BUI);
1182 } else if (BUI.NumLegalized > DT.DomTreeNodes.size() / 40)
1183 CalculateFromScratch(DT, &BUI);
1184
1185 // If the DominatorTree was recalculated at some point, stop the batch
1186 // updates. Full recalculations ignore batch updates and look at the actual
1187 // CFG.
1188 for (size_t i = 0; i < BUI.NumLegalized && !BUI.IsRecalculated; ++i)
1189 ApplyNextUpdate(DT, BUI);
1190 }
1191
1192 static void ApplyNextUpdate(DomTreeT &DT, BatchUpdateInfo &BUI) {
1193 // Popping the next update, will move the PreViewCFG to the next snapshot.
1195#if 0
1196 // FIXME: The LLVM_DEBUG macro only plays well with a modular
1197 // build of LLVM when the header is marked as textual, but doing
1198 // so causes redefinition errors.
1199 LLVM_DEBUG(dbgs() << "Applying update: ");
1200 LLVM_DEBUG(CurrentUpdate.dump(); dbgs() << "\n");
1201#endif
1202
1203 if (CurrentUpdate.getKind() == UpdateKind::Insert)
1204 InsertEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1205 else
1206 DeleteEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1207 }
1208
1209 //~~
1210 //===--------------- DomTree correctness verification ---------------------===
1211 //~~
1212
1213 // Check if the tree has correct roots. A DominatorTree always has a single
1214 // root which is the function's entry node. A PostDominatorTree can have
1215 // multiple roots - one for each node with no successors and for infinite
1216 // loops.
1217 // Running time: O(N).
1218 bool verifyRoots(const DomTreeT &DT) {
1219 if (!DT.Parent && !DT.Roots.empty()) {
1220 errs() << "Tree has no parent but has roots!\n";
1221 errs().flush();
1222 return false;
1223 }
1224
1225 if (!IsPostDom) {
1226 if (DT.Roots.empty()) {
1227 errs() << "Tree doesn't have a root!\n";
1228 errs().flush();
1229 return false;
1230 }
1231
1232 if (DT.getRoot() != GetEntryNode(DT)) {
1233 errs() << "Tree's root is not its parent's entry node!\n";
1234 errs().flush();
1235 return false;
1236 }
1237 }
1238
1239 RootsT ComputedRoots = FindRoots(DT, nullptr);
1240 if (!isPermutation(DT.Roots, ComputedRoots)) {
1241 errs() << "Tree has different roots than freshly computed ones!\n";
1242 errs() << "\tPDT roots: ";
1243 for (const NodePtr N : DT.Roots) errs() << BlockNamePrinter(N) << ", ";
1244 errs() << "\n\tComputed roots: ";
1245 for (const NodePtr N : ComputedRoots)
1246 errs() << BlockNamePrinter(N) << ", ";
1247 errs() << "\n";
1248 errs().flush();
1249 return false;
1250 }
1251
1252 return true;
1253 }
1254
1255 // Checks if the tree contains all reachable nodes in the input graph.
1256 // Running time: O(N).
1257 bool verifyReachability(const DomTreeT &DT) {
1258 clear();
1260
1261 for (auto &NodeToTN : DT.DomTreeNodes) {
1262 const TreeNodePtr TN = NodeToTN.second.get();
1263 const NodePtr BB = TN->getBlock();
1264
1265 // Virtual root has a corresponding virtual CFG node.
1266 if (DT.isVirtualRoot(TN)) continue;
1267
1268 if (NodeToInfo.count(BB) == 0) {
1269 errs() << "DomTree node " << BlockNamePrinter(BB)
1270 << " not found by DFS walk!\n";
1271 errs().flush();
1272
1273 return false;
1274 }
1275 }
1276
1277 for (const NodePtr N : NumToNode) {
1278 if (N && !DT.getNode(N)) {
1279 errs() << "CFG node " << BlockNamePrinter(N)
1280 << " not found in the DomTree!\n";
1281 errs().flush();
1282
1283 return false;
1284 }
1285 }
1286
1287 return true;
1288 }
1289
1290 // Check if for every parent with a level L in the tree all of its children
1291 // have level L + 1.
1292 // Running time: O(N).
1293 static bool VerifyLevels(const DomTreeT &DT) {
1294 for (auto &NodeToTN : DT.DomTreeNodes) {
1295 const TreeNodePtr TN = NodeToTN.second.get();
1296 const NodePtr BB = TN->getBlock();
1297 if (!BB) continue;
1298
1299 const TreeNodePtr IDom = TN->getIDom();
1300 if (!IDom && TN->getLevel() != 0) {
1301 errs() << "Node without an IDom " << BlockNamePrinter(BB)
1302 << " has a nonzero level " << TN->getLevel() << "!\n";
1303 errs().flush();
1304
1305 return false;
1306 }
1307
1308 if (IDom && TN->getLevel() != IDom->getLevel() + 1) {
1309 errs() << "Node " << BlockNamePrinter(BB) << " has level "
1310 << TN->getLevel() << " while its IDom "
1311 << BlockNamePrinter(IDom->getBlock()) << " has level "
1312 << IDom->getLevel() << "!\n";
1313 errs().flush();
1314
1315 return false;
1316 }
1317 }
1318
1319 return true;
1320 }
1321
1322 // Check if the computed DFS numbers are correct. Note that DFS info may not
1323 // be valid, and when that is the case, we don't verify the numbers.
1324 // Running time: O(N log(N)).
1325 static bool VerifyDFSNumbers(const DomTreeT &DT) {
1326 if (!DT.DFSInfoValid || !DT.Parent)
1327 return true;
1328
1329 const NodePtr RootBB = IsPostDom ? nullptr : *DT.root_begin();
1330 const TreeNodePtr Root = DT.getNode(RootBB);
1331
1332 auto PrintNodeAndDFSNums = [](const TreeNodePtr TN) {
1333 errs() << BlockNamePrinter(TN) << " {" << TN->getDFSNumIn() << ", "
1334 << TN->getDFSNumOut() << '}';
1335 };
1336
1337 // Verify the root's DFS In number. Although DFS numbering would also work
1338 // if we started from some other value, we assume 0-based numbering.
1339 if (Root->getDFSNumIn() != 0) {
1340 errs() << "DFSIn number for the tree root is not:\n\t";
1341 PrintNodeAndDFSNums(Root);
1342 errs() << '\n';
1343 errs().flush();
1344 return false;
1345 }
1346
1347 // For each tree node verify if children's DFS numbers cover their parent's
1348 // DFS numbers with no gaps.
1349 for (const auto &NodeToTN : DT.DomTreeNodes) {
1350 const TreeNodePtr Node = NodeToTN.second.get();
1351
1352 // Handle tree leaves.
1353 if (Node->isLeaf()) {
1354 if (Node->getDFSNumIn() + 1 != Node->getDFSNumOut()) {
1355 errs() << "Tree leaf should have DFSOut = DFSIn + 1:\n\t";
1356 PrintNodeAndDFSNums(Node);
1357 errs() << '\n';
1358 errs().flush();
1359 return false;
1360 }
1361
1362 continue;
1363 }
1364
1365 // Make a copy and sort it such that it is possible to check if there are
1366 // no gaps between DFS numbers of adjacent children.
1367 SmallVector<TreeNodePtr, 8> Children(Node->begin(), Node->end());
1368 llvm::sort(Children, [](const TreeNodePtr Ch1, const TreeNodePtr Ch2) {
1369 return Ch1->getDFSNumIn() < Ch2->getDFSNumIn();
1370 });
1371
1372 auto PrintChildrenError = [Node, &Children, PrintNodeAndDFSNums](
1373 const TreeNodePtr FirstCh, const TreeNodePtr SecondCh) {
1374 assert(FirstCh);
1375
1376 errs() << "Incorrect DFS numbers for:\n\tParent ";
1377 PrintNodeAndDFSNums(Node);
1378
1379 errs() << "\n\tChild ";
1380 PrintNodeAndDFSNums(FirstCh);
1381
1382 if (SecondCh) {
1383 errs() << "\n\tSecond child ";
1384 PrintNodeAndDFSNums(SecondCh);
1385 }
1386
1387 errs() << "\nAll children: ";
1388 for (const TreeNodePtr Ch : Children) {
1389 PrintNodeAndDFSNums(Ch);
1390 errs() << ", ";
1391 }
1392
1393 errs() << '\n';
1394 errs().flush();
1395 };
1396
1397 if (Children.front()->getDFSNumIn() != Node->getDFSNumIn() + 1) {
1398 PrintChildrenError(Children.front(), nullptr);
1399 return false;
1400 }
1401
1402 if (Children.back()->getDFSNumOut() + 1 != Node->getDFSNumOut()) {
1403 PrintChildrenError(Children.back(), nullptr);
1404 return false;
1405 }
1406
1407 for (size_t i = 0, e = Children.size() - 1; i != e; ++i) {
1408 if (Children[i]->getDFSNumOut() + 1 != Children[i + 1]->getDFSNumIn()) {
1409 PrintChildrenError(Children[i], Children[i + 1]);
1410 return false;
1411 }
1412 }
1413 }
1414
1415 return true;
1416 }
1417
1418 // The below routines verify the correctness of the dominator tree relative to
1419 // the CFG it's coming from. A tree is a dominator tree iff it has two
1420 // properties, called the parent property and the sibling property. Tarjan
1421 // and Lengauer prove (but don't explicitly name) the properties as part of
1422 // the proofs in their 1972 paper, but the proofs are mostly part of proving
1423 // things about semidominators and idoms, and some of them are simply asserted
1424 // based on even earlier papers (see, e.g., lemma 2). Some papers refer to
1425 // these properties as "valid" and "co-valid". See, e.g., "Dominators,
1426 // directed bipolar orders, and independent spanning trees" by Loukas
1427 // Georgiadis and Robert E. Tarjan, as well as "Dominator Tree Verification
1428 // and Vertex-Disjoint Paths " by the same authors.
1429
1430 // A very simple and direct explanation of these properties can be found in
1431 // "An Experimental Study of Dynamic Dominators", found at
1432 // https://arxiv.org/abs/1604.02711
1433
1434 // The easiest way to think of the parent property is that it's a requirement
1435 // of being a dominator. Let's just take immediate dominators. For PARENT to
1436 // be an immediate dominator of CHILD, all paths in the CFG must go through
1437 // PARENT before they hit CHILD. This implies that if you were to cut PARENT
1438 // out of the CFG, there should be no paths to CHILD that are reachable. If
1439 // there are, then you now have a path from PARENT to CHILD that goes around
1440 // PARENT and still reaches CHILD, which by definition, means PARENT can't be
1441 // a dominator of CHILD (let alone an immediate one).
1442
1443 // The sibling property is similar. It says that for each pair of sibling
1444 // nodes in the dominator tree (LEFT and RIGHT) , they must not dominate each
1445 // other. If sibling LEFT dominated sibling RIGHT, it means there are no
1446 // paths in the CFG from sibling LEFT to sibling RIGHT that do not go through
1447 // LEFT, and thus, LEFT is really an ancestor (in the dominator tree) of
1448 // RIGHT, not a sibling.
1449
1450 // It is possible to verify the parent and sibling properties in linear time,
1451 // but the algorithms are complex. Instead, we do it in a straightforward
1452 // N^2 and N^3 way below, using direct path reachability.
1453
1454 // Checks if the tree has the parent property: if for all edges from V to W in
1455 // the input graph, such that V is reachable, the parent of W in the tree is
1456 // an ancestor of V in the tree.
1457 // Running time: O(N^2).
1458 //
1459 // This means that if a node gets disconnected from the graph, then all of
1460 // the nodes it dominated previously will now become unreachable.
1461 bool verifyParentProperty(const DomTreeT &DT) {
1462 for (auto &NodeToTN : DT.DomTreeNodes) {
1463 const TreeNodePtr TN = NodeToTN.second.get();
1464 const NodePtr BB = TN->getBlock();
1465 if (!BB || TN->isLeaf())
1466 continue;
1467
1468 LLVM_DEBUG(dbgs() << "Verifying parent property of node "
1469 << BlockNamePrinter(TN) << "\n");
1470 clear();
1471 doFullDFSWalk(DT, [BB](NodePtr From, NodePtr To) {
1472 return From != BB && To != BB;
1473 });
1474
1475 for (TreeNodePtr Child : TN->children())
1476 if (NodeToInfo.count(Child->getBlock()) != 0) {
1477 errs() << "Child " << BlockNamePrinter(Child)
1478 << " reachable after its parent " << BlockNamePrinter(BB)
1479 << " is removed!\n";
1480 errs().flush();
1481
1482 return false;
1483 }
1484 }
1485
1486 return true;
1487 }
1488
1489 // Check if the tree has sibling property: if a node V does not dominate a
1490 // node W for all siblings V and W in the tree.
1491 // Running time: O(N^3).
1492 //
1493 // This means that if a node gets disconnected from the graph, then all of its
1494 // siblings will now still be reachable.
1495 bool verifySiblingProperty(const DomTreeT &DT) {
1496 for (auto &NodeToTN : DT.DomTreeNodes) {
1497 const TreeNodePtr TN = NodeToTN.second.get();
1498 const NodePtr BB = TN->getBlock();
1499 if (!BB || TN->isLeaf())
1500 continue;
1501
1502 for (const TreeNodePtr N : TN->children()) {
1503 clear();
1504 NodePtr BBN = N->getBlock();
1505 doFullDFSWalk(DT, [BBN](NodePtr From, NodePtr To) {
1506 return From != BBN && To != BBN;
1507 });
1508
1509 for (const TreeNodePtr S : TN->children()) {
1510 if (S == N) continue;
1511
1512 if (NodeToInfo.count(S->getBlock()) == 0) {
1513 errs() << "Node " << BlockNamePrinter(S)
1514 << " not reachable when its sibling " << BlockNamePrinter(N)
1515 << " is removed!\n";
1516 errs().flush();
1517
1518 return false;
1519 }
1520 }
1521 }
1522 }
1523
1524 return true;
1525 }
1526
1527 // Check if the given tree is the same as a freshly computed one for the same
1528 // Parent.
1529 // Running time: O(N^2), but faster in practice (same as tree construction).
1530 //
1531 // Note that this does not check if that the tree construction algorithm is
1532 // correct and should be only used for fast (but possibly unsound)
1533 // verification.
1534 static bool IsSameAsFreshTree(const DomTreeT &DT) {
1535 DomTreeT FreshTree;
1536 FreshTree.recalculate(*DT.Parent);
1537 const bool Different = DT.compare(FreshTree);
1538
1539 if (Different) {
1540 errs() << (DT.isPostDominator() ? "Post" : "")
1541 << "DominatorTree is different than a freshly computed one!\n"
1542 << "\tCurrent:\n";
1543 DT.print(errs());
1544 errs() << "\n\tFreshly computed tree:\n";
1545 FreshTree.print(errs());
1546 errs().flush();
1547 }
1548
1549 return !Different;
1550 }
1551};
1552
1553template <class DomTreeT>
1554void Calculate(DomTreeT &DT) {
1556}
1557
1558template <typename DomTreeT>
1559void CalculateWithUpdates(DomTreeT &DT,
1561 // FIXME: Updated to use the PreViewCFG and behave the same as until now.
1562 // This behavior is however incorrect; this actually needs the PostViewCFG.
1564 Updates, /*ReverseApplyUpdates=*/true);
1565 typename SemiNCAInfo<DomTreeT>::BatchUpdateInfo BUI(PreViewCFG);
1567}
1568
1569template <class DomTreeT>
1570void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
1571 typename DomTreeT::NodePtr To) {
1572 if (DT.isPostDominator()) std::swap(From, To);
1573 SemiNCAInfo<DomTreeT>::InsertEdge(DT, nullptr, From, To);
1574}
1575
1576template <class DomTreeT>
1577void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
1578 typename DomTreeT::NodePtr To) {
1579 if (DT.isPostDominator()) std::swap(From, To);
1580 SemiNCAInfo<DomTreeT>::DeleteEdge(DT, nullptr, From, To);
1581}
1582
1583template <class DomTreeT>
1584void ApplyUpdates(DomTreeT &DT,
1585 GraphDiff<typename DomTreeT::NodePtr,
1586 DomTreeT::IsPostDominator> &PreViewCFG,
1587 GraphDiff<typename DomTreeT::NodePtr,
1588 DomTreeT::IsPostDominator> *PostViewCFG) {
1589 SemiNCAInfo<DomTreeT>::ApplyUpdates(DT, PreViewCFG, PostViewCFG);
1590}
1591
1592template <class DomTreeT>
1593bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL) {
1594 SemiNCAInfo<DomTreeT> SNCA(nullptr);
1595
1596 // Simplist check is to compare against a new tree. This will also
1597 // usefully print the old and new trees, if they are different.
1598 if (!SNCA.IsSameAsFreshTree(DT))
1599 return false;
1600
1601 // Common checks to verify the properties of the tree. O(N log N) at worst.
1602 if (!SNCA.verifyRoots(DT) || !SNCA.verifyReachability(DT) ||
1603 !SNCA.VerifyLevels(DT) || !SNCA.VerifyDFSNumbers(DT))
1604 return false;
1605
1606 // Extra checks depending on VerificationLevel. Up to O(N^3).
1607 if (VL == DomTreeT::VerificationLevel::Basic ||
1608 VL == DomTreeT::VerificationLevel::Full)
1609 if (!SNCA.verifyParentProperty(DT))
1610 return false;
1611 if (VL == DomTreeT::VerificationLevel::Full)
1612 if (!SNCA.verifySiblingProperty(DT))
1613 return false;
1614
1615 return true;
1616}
1617
1618} // namespace DomTreeBuilder
1619} // namespace llvm
1620
1621#undef DEBUG_TYPE
1622
1623#endif
Unify divergent function exit nodes
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
Loop::LoopBounds::Direction Direction
Definition: LoopInfo.cpp:230
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
ppc ctr loops PowerPC CTR Loops Verify
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Base class for the actual dominator tree node.
iterator_range< iterator > children()
void setIDom(DomTreeNodeBase *NewIDom)
DomTreeNodeBase * getIDom() const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
size_t getNumChildren() const
NodeT * getBlock() const
unsigned getLevel() const
cfg::Update< NodePtr > popUpdateForIncrementalUpdates()
Definition: CFGDiff.h:113
unsigned getNumLegalizedUpdates() const
Definition: CFGDiff.h:111
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:360
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void reserve(size_type N)
Definition: SmallVector.h:676
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
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: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
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:1742
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition: STLExtras.h:2059
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1736
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define N
BatchUpdateInfo(GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG=nullptr)
friend raw_ostream & operator<<(raw_ostream &O, const BlockNamePrinter &BP)
std::priority_queue< TreeNodePtr, SmallVector< TreeNodePtr, 8 >, Compare > Bucket
static SmallVector< NodePtr, 8 > getChildren(NodePtr N)
static void UpdateInsertion(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr NCD, InsertionInfo &II)
static void DeleteEdge(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr From, const NodePtr To)
void doFullDFSWalk(const DomTreeT &DT, DescendCondition DC)
DenseMap< NodePtr, unsigned > NodeOrderMap
static RootsT FindRoots(const DomTreeT &DT, BatchUpdatePtr BUI)
static SmallVector< NodePtr, 8 > getChildren(NodePtr N, BatchUpdatePtr BUI)
static void ComputeUnreachableDominators(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr Root, const TreeNodePtr Incoming, SmallVectorImpl< std::pair< NodePtr, TreeNodePtr > > &DiscoveredConnectingEdges)
static bool VerifyLevels(const DomTreeT &DT)
unsigned eval(unsigned V, unsigned LastLinked, SmallVectorImpl< InfoRec * > &Stack, ArrayRef< InfoRec * > NumToInfo)
static bool IsSameAsFreshTree(const DomTreeT &DT)
static void EraseNode(DomTreeT &DT, const TreeNodePtr TN)
static void ApplyUpdates(DomTreeT &DT, GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG)
typename DomTreeT::UpdateKind UpdateKind
static bool UpdateRootsBeforeInsertion(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const TreeNodePtr To)
void reattachExistingSubtree(DomTreeT &DT, const TreeNodePtr AttachTo)
static NodePtr GetEntryNode(const DomTreeT &DT)
static bool AlwaysDescend(NodePtr, NodePtr)
static void UpdateRootsAfterUpdate(DomTreeT &DT, const BatchUpdatePtr BUI)
unsigned runDFS(NodePtr V, unsigned LastNum, DescendCondition Condition, unsigned AttachToNum, const NodeOrderMap *SuccOrder=nullptr)
static void DeleteReachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr FromTN, const TreeNodePtr ToTN)
static void RemoveRedundantRoots(const DomTreeT &DT, BatchUpdatePtr BUI, RootsT &Roots)
static bool HasProperSupport(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr TN)
static bool isPermutation(const SmallVectorImpl< NodePtr > &A, const SmallVectorImpl< NodePtr > &B)
static void CalculateFromScratch(DomTreeT &DT, BatchUpdatePtr BUI)
TreeNodePtr getNodeForBlock(NodePtr BB, DomTreeT &DT)
typename DomTreeT::UpdateType UpdateT
static void InsertReachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const TreeNodePtr To)
static bool HasForwardSuccessors(const NodePtr N, BatchUpdatePtr BUI)
static void InsertUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const NodePtr To)
static void ApplyNextUpdate(DomTreeT &DT, BatchUpdateInfo &BUI)
DenseMap< NodePtr, InfoRec > NodeToInfo
static bool VerifyDFSNumbers(const DomTreeT &DT)
static void DeleteUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr ToTN)
void attachNewSubtree(DomTreeT &DT, const TreeNodePtr AttachTo)
static void InsertEdge(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr From, const NodePtr To)
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...