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