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