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