1 //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
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 
9 #include "llvm/Analysis/LazyCallGraph.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/ScopeExit.h"
13 #include "llvm/ADT/Sequence.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/Analysis/TargetLibraryInfo.h"
18 #include "llvm/Analysis/VectorUtils.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <cassert>
33 #include <cstddef>
34 #include <iterator>
35 #include <string>
36 #include <tuple>
37 #include <utility>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "lcg"
42 
43 void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
44                                                      Edge::Kind EK) {
45   EdgeIndexMap.insert({&TargetN, Edges.size()});
46   Edges.emplace_back(TargetN, EK);
47 }
48 
49 void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) {
50   Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
51 }
52 
53 bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
54   auto IndexMapI = EdgeIndexMap.find(&TargetN);
55   if (IndexMapI == EdgeIndexMap.end())
56     return false;
57 
58   Edges[IndexMapI->second] = Edge();
59   EdgeIndexMap.erase(IndexMapI);
60   return true;
61 }
62 
63 static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
64                     DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap,
65                     LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) {
66   if (!EdgeIndexMap.insert({&N, Edges.size()}).second)
67     return;
68 
69   LLVM_DEBUG(dbgs() << "    Added callable function: " << N.getName() << "\n");
70   Edges.emplace_back(LazyCallGraph::Edge(N, EK));
71 }
72 
73 LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
74   assert(!Edges && "Must not have already populated the edges for this node!");
75 
76   LLVM_DEBUG(dbgs() << "  Adding functions called by '" << getName()
77                     << "' to the graph.\n");
78 
79   Edges = EdgeSequence();
80 
81   SmallVector<Constant *, 16> Worklist;
82   SmallPtrSet<Function *, 4> Callees;
83   SmallPtrSet<Constant *, 16> Visited;
84 
85   // Find all the potential call graph edges in this function. We track both
86   // actual call edges and indirect references to functions. The direct calls
87   // are trivially added, but to accumulate the latter we walk the instructions
88   // and add every operand which is a constant to the worklist to process
89   // afterward.
90   //
91   // Note that we consider *any* function with a definition to be a viable
92   // edge. Even if the function's definition is subject to replacement by
93   // some other module (say, a weak definition) there may still be
94   // optimizations which essentially speculate based on the definition and
95   // a way to check that the specific definition is in fact the one being
96   // used. For example, this could be done by moving the weak definition to
97   // a strong (internal) definition and making the weak definition be an
98   // alias. Then a test of the address of the weak function against the new
99   // strong definition's address would be an effective way to determine the
100   // safety of optimizing a direct call edge.
101   for (BasicBlock &BB : *F)
102     for (Instruction &I : BB) {
103       if (auto CS = CallSite(&I))
104         if (Function *Callee = CS.getCalledFunction())
105           if (!Callee->isDeclaration())
106             if (Callees.insert(Callee).second) {
107               Visited.insert(Callee);
108               addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
109                       LazyCallGraph::Edge::Call);
110             }
111 
112       for (Value *Op : I.operand_values())
113         if (Constant *C = dyn_cast<Constant>(Op))
114           if (Visited.insert(C).second)
115             Worklist.push_back(C);
116     }
117 
118   // We've collected all the constant (and thus potentially function or
119   // function containing) operands to all of the instructions in the function.
120   // Process them (recursively) collecting every function found.
121   visitReferences(Worklist, Visited, [&](Function &F) {
122     addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
123             LazyCallGraph::Edge::Ref);
124   });
125 
126   // Add implicit reference edges to any defined libcall functions (if we
127   // haven't found an explicit edge).
128   for (auto *F : G->LibFunctions)
129     if (!Visited.count(F))
130       addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*F),
131               LazyCallGraph::Edge::Ref);
132 
133   return *Edges;
134 }
135 
136 void LazyCallGraph::Node::replaceFunction(Function &NewF) {
137   assert(F != &NewF && "Must not replace a function with itself!");
138   F = &NewF;
139 }
140 
141 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
142 LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
143   dbgs() << *this << '\n';
144 }
145 #endif
146 
147 static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
148   LibFunc LF;
149 
150   // Either this is a normal library function or a "vectorizable"
151   // function.  Not using the VFDatabase here because this query
152   // is related only to libraries handled via the TLI.
153   return TLI.getLibFunc(F, LF) ||
154          TLI.isKnownVectorFunctionInLibrary(F.getName());
155 }
156 
157 LazyCallGraph::LazyCallGraph(
158     Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
159   LLVM_DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
160                     << "\n");
161   for (Function &F : M) {
162     if (F.isDeclaration())
163       continue;
164     // If this function is a known lib function to LLVM then we want to
165     // synthesize reference edges to it to model the fact that LLVM can turn
166     // arbitrary code into a library function call.
167     if (isKnownLibFunction(F, GetTLI(F)))
168       LibFunctions.insert(&F);
169 
170     if (F.hasLocalLinkage())
171       continue;
172 
173     // External linkage defined functions have edges to them from other
174     // modules.
175     LLVM_DEBUG(dbgs() << "  Adding '" << F.getName()
176                       << "' to entry set of the graph.\n");
177     addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
178   }
179 
180   // Externally visible aliases of internal functions are also viable entry
181   // edges to the module.
182   for (auto &A : M.aliases()) {
183     if (A.hasLocalLinkage())
184       continue;
185     if (Function* F = dyn_cast<Function>(A.getAliasee())) {
186       LLVM_DEBUG(dbgs() << "  Adding '" << F->getName()
187                         << "' with alias '" << A.getName()
188                         << "' to entry set of the graph.\n");
189       addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(*F), Edge::Ref);
190     }
191   }
192 
193   // Now add entry nodes for functions reachable via initializers to globals.
194   SmallVector<Constant *, 16> Worklist;
195   SmallPtrSet<Constant *, 16> Visited;
196   for (GlobalVariable &GV : M.globals())
197     if (GV.hasInitializer())
198       if (Visited.insert(GV.getInitializer()).second)
199         Worklist.push_back(GV.getInitializer());
200 
201   LLVM_DEBUG(
202       dbgs() << "  Adding functions referenced by global initializers to the "
203                 "entry set.\n");
204   visitReferences(Worklist, Visited, [&](Function &F) {
205     addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
206             LazyCallGraph::Edge::Ref);
207   });
208 }
209 
210 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
211     : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
212       EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
213       SCCMap(std::move(G.SCCMap)),
214       LibFunctions(std::move(G.LibFunctions)) {
215   updateGraphPtrs();
216 }
217 
218 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
219   BPA = std::move(G.BPA);
220   NodeMap = std::move(G.NodeMap);
221   EntryEdges = std::move(G.EntryEdges);
222   SCCBPA = std::move(G.SCCBPA);
223   SCCMap = std::move(G.SCCMap);
224   LibFunctions = std::move(G.LibFunctions);
225   updateGraphPtrs();
226   return *this;
227 }
228 
229 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
230 LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
231   dbgs() << *this << '\n';
232 }
233 #endif
234 
235 #ifndef NDEBUG
236 void LazyCallGraph::SCC::verify() {
237   assert(OuterRefSCC && "Can't have a null RefSCC!");
238   assert(!Nodes.empty() && "Can't have an empty SCC!");
239 
240   for (Node *N : Nodes) {
241     assert(N && "Can't have a null node!");
242     assert(OuterRefSCC->G->lookupSCC(*N) == this &&
243            "Node does not map to this SCC!");
244     assert(N->DFSNumber == -1 &&
245            "Must set DFS numbers to -1 when adding a node to an SCC!");
246     assert(N->LowLink == -1 &&
247            "Must set low link to -1 when adding a node to an SCC!");
248     for (Edge &E : **N)
249       assert(E.getNode().isPopulated() && "Can't have an unpopulated node!");
250   }
251 }
252 #endif
253 
254 bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
255   if (this == &C)
256     return false;
257 
258   for (Node &N : *this)
259     for (Edge &E : N->calls())
260       if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
261         return true;
262 
263   // No edges found.
264   return false;
265 }
266 
267 bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
268   if (this == &TargetC)
269     return false;
270 
271   LazyCallGraph &G = *OuterRefSCC->G;
272 
273   // Start with this SCC.
274   SmallPtrSet<const SCC *, 16> Visited = {this};
275   SmallVector<const SCC *, 16> Worklist = {this};
276 
277   // Walk down the graph until we run out of edges or find a path to TargetC.
278   do {
279     const SCC &C = *Worklist.pop_back_val();
280     for (Node &N : C)
281       for (Edge &E : N->calls()) {
282         SCC *CalleeC = G.lookupSCC(E.getNode());
283         if (!CalleeC)
284           continue;
285 
286         // If the callee's SCC is the TargetC, we're done.
287         if (CalleeC == &TargetC)
288           return true;
289 
290         // If this is the first time we've reached this SCC, put it on the
291         // worklist to recurse through.
292         if (Visited.insert(CalleeC).second)
293           Worklist.push_back(CalleeC);
294       }
295   } while (!Worklist.empty());
296 
297   // No paths found.
298   return false;
299 }
300 
301 LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
302 
303 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
304 LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
305   dbgs() << *this << '\n';
306 }
307 #endif
308 
309 #ifndef NDEBUG
310 void LazyCallGraph::RefSCC::verify() {
311   assert(G && "Can't have a null graph!");
312   assert(!SCCs.empty() && "Can't have an empty SCC!");
313 
314   // Verify basic properties of the SCCs.
315   SmallPtrSet<SCC *, 4> SCCSet;
316   for (SCC *C : SCCs) {
317     assert(C && "Can't have a null SCC!");
318     C->verify();
319     assert(&C->getOuterRefSCC() == this &&
320            "SCC doesn't think it is inside this RefSCC!");
321     bool Inserted = SCCSet.insert(C).second;
322     assert(Inserted && "Found a duplicate SCC!");
323     auto IndexIt = SCCIndices.find(C);
324     assert(IndexIt != SCCIndices.end() &&
325            "Found an SCC that doesn't have an index!");
326   }
327 
328   // Check that our indices map correctly.
329   for (auto &SCCIndexPair : SCCIndices) {
330     SCC *C = SCCIndexPair.first;
331     int i = SCCIndexPair.second;
332     assert(C && "Can't have a null SCC in the indices!");
333     assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
334     assert(SCCs[i] == C && "Index doesn't point to SCC!");
335   }
336 
337   // Check that the SCCs are in fact in post-order.
338   for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
339     SCC &SourceSCC = *SCCs[i];
340     for (Node &N : SourceSCC)
341       for (Edge &E : *N) {
342         if (!E.isCall())
343           continue;
344         SCC &TargetSCC = *G->lookupSCC(E.getNode());
345         if (&TargetSCC.getOuterRefSCC() == this) {
346           assert(SCCIndices.find(&TargetSCC)->second <= i &&
347                  "Edge between SCCs violates post-order relationship.");
348           continue;
349         }
350       }
351   }
352 }
353 #endif
354 
355 bool LazyCallGraph::RefSCC::isParentOf(const RefSCC &RC) const {
356   if (&RC == this)
357     return false;
358 
359   // Search all edges to see if this is a parent.
360   for (SCC &C : *this)
361     for (Node &N : C)
362       for (Edge &E : *N)
363         if (G->lookupRefSCC(E.getNode()) == &RC)
364           return true;
365 
366   return false;
367 }
368 
369 bool LazyCallGraph::RefSCC::isAncestorOf(const RefSCC &RC) const {
370   if (&RC == this)
371     return false;
372 
373   // For each descendant of this RefSCC, see if one of its children is the
374   // argument. If not, add that descendant to the worklist and continue
375   // searching.
376   SmallVector<const RefSCC *, 4> Worklist;
377   SmallPtrSet<const RefSCC *, 4> Visited;
378   Worklist.push_back(this);
379   Visited.insert(this);
380   do {
381     const RefSCC &DescendantRC = *Worklist.pop_back_val();
382     for (SCC &C : DescendantRC)
383       for (Node &N : C)
384         for (Edge &E : *N) {
385           auto *ChildRC = G->lookupRefSCC(E.getNode());
386           if (ChildRC == &RC)
387             return true;
388           if (!ChildRC || !Visited.insert(ChildRC).second)
389             continue;
390           Worklist.push_back(ChildRC);
391         }
392   } while (!Worklist.empty());
393 
394   return false;
395 }
396 
397 /// Generic helper that updates a postorder sequence of SCCs for a potentially
398 /// cycle-introducing edge insertion.
399 ///
400 /// A postorder sequence of SCCs of a directed graph has one fundamental
401 /// property: all deges in the DAG of SCCs point "up" the sequence. That is,
402 /// all edges in the SCC DAG point to prior SCCs in the sequence.
403 ///
404 /// This routine both updates a postorder sequence and uses that sequence to
405 /// compute the set of SCCs connected into a cycle. It should only be called to
406 /// insert a "downward" edge which will require changing the sequence to
407 /// restore it to a postorder.
408 ///
409 /// When inserting an edge from an earlier SCC to a later SCC in some postorder
410 /// sequence, all of the SCCs which may be impacted are in the closed range of
411 /// those two within the postorder sequence. The algorithm used here to restore
412 /// the state is as follows:
413 ///
414 /// 1) Starting from the source SCC, construct a set of SCCs which reach the
415 ///    source SCC consisting of just the source SCC. Then scan toward the
416 ///    target SCC in postorder and for each SCC, if it has an edge to an SCC
417 ///    in the set, add it to the set. Otherwise, the source SCC is not
418 ///    a successor, move it in the postorder sequence to immediately before
419 ///    the source SCC, shifting the source SCC and all SCCs in the set one
420 ///    position toward the target SCC. Stop scanning after processing the
421 ///    target SCC.
422 /// 2) If the source SCC is now past the target SCC in the postorder sequence,
423 ///    and thus the new edge will flow toward the start, we are done.
424 /// 3) Otherwise, starting from the target SCC, walk all edges which reach an
425 ///    SCC between the source and the target, and add them to the set of
426 ///    connected SCCs, then recurse through them. Once a complete set of the
427 ///    SCCs the target connects to is known, hoist the remaining SCCs between
428 ///    the source and the target to be above the target. Note that there is no
429 ///    need to process the source SCC, it is already known to connect.
430 /// 4) At this point, all of the SCCs in the closed range between the source
431 ///    SCC and the target SCC in the postorder sequence are connected,
432 ///    including the target SCC and the source SCC. Inserting the edge from
433 ///    the source SCC to the target SCC will form a cycle out of precisely
434 ///    these SCCs. Thus we can merge all of the SCCs in this closed range into
435 ///    a single SCC.
436 ///
437 /// This process has various important properties:
438 /// - Only mutates the SCCs when adding the edge actually changes the SCC
439 ///   structure.
440 /// - Never mutates SCCs which are unaffected by the change.
441 /// - Updates the postorder sequence to correctly satisfy the postorder
442 ///   constraint after the edge is inserted.
443 /// - Only reorders SCCs in the closed postorder sequence from the source to
444 ///   the target, so easy to bound how much has changed even in the ordering.
445 /// - Big-O is the number of edges in the closed postorder range of SCCs from
446 ///   source to target.
447 ///
448 /// This helper routine, in addition to updating the postorder sequence itself
449 /// will also update a map from SCCs to indices within that sequence.
450 ///
451 /// The sequence and the map must operate on pointers to the SCC type.
452 ///
453 /// Two callbacks must be provided. The first computes the subset of SCCs in
454 /// the postorder closed range from the source to the target which connect to
455 /// the source SCC via some (transitive) set of edges. The second computes the
456 /// subset of the same range which the target SCC connects to via some
457 /// (transitive) set of edges. Both callbacks should populate the set argument
458 /// provided.
459 template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
460           typename ComputeSourceConnectedSetCallableT,
461           typename ComputeTargetConnectedSetCallableT>
462 static iterator_range<typename PostorderSequenceT::iterator>
463 updatePostorderSequenceForEdgeInsertion(
464     SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
465     SCCIndexMapT &SCCIndices,
466     ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
467     ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
468   int SourceIdx = SCCIndices[&SourceSCC];
469   int TargetIdx = SCCIndices[&TargetSCC];
470   assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
471 
472   SmallPtrSet<SCCT *, 4> ConnectedSet;
473 
474   // Compute the SCCs which (transitively) reach the source.
475   ComputeSourceConnectedSet(ConnectedSet);
476 
477   // Partition the SCCs in this part of the port-order sequence so only SCCs
478   // connecting to the source remain between it and the target. This is
479   // a benign partition as it preserves postorder.
480   auto SourceI = std::stable_partition(
481       SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
482       [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
483   for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
484     SCCIndices.find(SCCs[i])->second = i;
485 
486   // If the target doesn't connect to the source, then we've corrected the
487   // post-order and there are no cycles formed.
488   if (!ConnectedSet.count(&TargetSCC)) {
489     assert(SourceI > (SCCs.begin() + SourceIdx) &&
490            "Must have moved the source to fix the post-order.");
491     assert(*std::prev(SourceI) == &TargetSCC &&
492            "Last SCC to move should have bene the target.");
493 
494     // Return an empty range at the target SCC indicating there is nothing to
495     // merge.
496     return make_range(std::prev(SourceI), std::prev(SourceI));
497   }
498 
499   assert(SCCs[TargetIdx] == &TargetSCC &&
500          "Should not have moved target if connected!");
501   SourceIdx = SourceI - SCCs.begin();
502   assert(SCCs[SourceIdx] == &SourceSCC &&
503          "Bad updated index computation for the source SCC!");
504 
505 
506   // See whether there are any remaining intervening SCCs between the source
507   // and target. If so we need to make sure they all are reachable form the
508   // target.
509   if (SourceIdx + 1 < TargetIdx) {
510     ConnectedSet.clear();
511     ComputeTargetConnectedSet(ConnectedSet);
512 
513     // Partition SCCs so that only SCCs reached from the target remain between
514     // the source and the target. This preserves postorder.
515     auto TargetI = std::stable_partition(
516         SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
517         [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
518     for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
519       SCCIndices.find(SCCs[i])->second = i;
520     TargetIdx = std::prev(TargetI) - SCCs.begin();
521     assert(SCCs[TargetIdx] == &TargetSCC &&
522            "Should always end with the target!");
523   }
524 
525   // At this point, we know that connecting source to target forms a cycle
526   // because target connects back to source, and we know that all of the SCCs
527   // between the source and target in the postorder sequence participate in that
528   // cycle.
529   return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
530 }
531 
532 bool
533 LazyCallGraph::RefSCC::switchInternalEdgeToCall(
534     Node &SourceN, Node &TargetN,
535     function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
536   assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
537   SmallVector<SCC *, 1> DeletedSCCs;
538 
539 #ifndef NDEBUG
540   // In a debug build, verify the RefSCC is valid to start with and when this
541   // routine finishes.
542   verify();
543   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
544 #endif
545 
546   SCC &SourceSCC = *G->lookupSCC(SourceN);
547   SCC &TargetSCC = *G->lookupSCC(TargetN);
548 
549   // If the two nodes are already part of the same SCC, we're also done as
550   // we've just added more connectivity.
551   if (&SourceSCC == &TargetSCC) {
552     SourceN->setEdgeKind(TargetN, Edge::Call);
553     return false; // No new cycle.
554   }
555 
556   // At this point we leverage the postorder list of SCCs to detect when the
557   // insertion of an edge changes the SCC structure in any way.
558   //
559   // First and foremost, we can eliminate the need for any changes when the
560   // edge is toward the beginning of the postorder sequence because all edges
561   // flow in that direction already. Thus adding a new one cannot form a cycle.
562   int SourceIdx = SCCIndices[&SourceSCC];
563   int TargetIdx = SCCIndices[&TargetSCC];
564   if (TargetIdx < SourceIdx) {
565     SourceN->setEdgeKind(TargetN, Edge::Call);
566     return false; // No new cycle.
567   }
568 
569   // Compute the SCCs which (transitively) reach the source.
570   auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
571 #ifndef NDEBUG
572     // Check that the RefSCC is still valid before computing this as the
573     // results will be nonsensical of we've broken its invariants.
574     verify();
575 #endif
576     ConnectedSet.insert(&SourceSCC);
577     auto IsConnected = [&](SCC &C) {
578       for (Node &N : C)
579         for (Edge &E : N->calls())
580           if (ConnectedSet.count(G->lookupSCC(E.getNode())))
581             return true;
582 
583       return false;
584     };
585 
586     for (SCC *C :
587          make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
588       if (IsConnected(*C))
589         ConnectedSet.insert(C);
590   };
591 
592   // Use a normal worklist to find which SCCs the target connects to. We still
593   // bound the search based on the range in the postorder list we care about,
594   // but because this is forward connectivity we just "recurse" through the
595   // edges.
596   auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
597 #ifndef NDEBUG
598     // Check that the RefSCC is still valid before computing this as the
599     // results will be nonsensical of we've broken its invariants.
600     verify();
601 #endif
602     ConnectedSet.insert(&TargetSCC);
603     SmallVector<SCC *, 4> Worklist;
604     Worklist.push_back(&TargetSCC);
605     do {
606       SCC &C = *Worklist.pop_back_val();
607       for (Node &N : C)
608         for (Edge &E : *N) {
609           if (!E.isCall())
610             continue;
611           SCC &EdgeC = *G->lookupSCC(E.getNode());
612           if (&EdgeC.getOuterRefSCC() != this)
613             // Not in this RefSCC...
614             continue;
615           if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
616             // Not in the postorder sequence between source and target.
617             continue;
618 
619           if (ConnectedSet.insert(&EdgeC).second)
620             Worklist.push_back(&EdgeC);
621         }
622     } while (!Worklist.empty());
623   };
624 
625   // Use a generic helper to update the postorder sequence of SCCs and return
626   // a range of any SCCs connected into a cycle by inserting this edge. This
627   // routine will also take care of updating the indices into the postorder
628   // sequence.
629   auto MergeRange = updatePostorderSequenceForEdgeInsertion(
630       SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
631       ComputeTargetConnectedSet);
632 
633   // Run the user's callback on the merged SCCs before we actually merge them.
634   if (MergeCB)
635     MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
636 
637   // If the merge range is empty, then adding the edge didn't actually form any
638   // new cycles. We're done.
639   if (MergeRange.empty()) {
640     // Now that the SCC structure is finalized, flip the kind to call.
641     SourceN->setEdgeKind(TargetN, Edge::Call);
642     return false; // No new cycle.
643   }
644 
645 #ifndef NDEBUG
646   // Before merging, check that the RefSCC remains valid after all the
647   // postorder updates.
648   verify();
649 #endif
650 
651   // Otherwise we need to merge all of the SCCs in the cycle into a single
652   // result SCC.
653   //
654   // NB: We merge into the target because all of these functions were already
655   // reachable from the target, meaning any SCC-wide properties deduced about it
656   // other than the set of functions within it will not have changed.
657   for (SCC *C : MergeRange) {
658     assert(C != &TargetSCC &&
659            "We merge *into* the target and shouldn't process it here!");
660     SCCIndices.erase(C);
661     TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
662     for (Node *N : C->Nodes)
663       G->SCCMap[N] = &TargetSCC;
664     C->clear();
665     DeletedSCCs.push_back(C);
666   }
667 
668   // Erase the merged SCCs from the list and update the indices of the
669   // remaining SCCs.
670   int IndexOffset = MergeRange.end() - MergeRange.begin();
671   auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
672   for (SCC *C : make_range(EraseEnd, SCCs.end()))
673     SCCIndices[C] -= IndexOffset;
674 
675   // Now that the SCC structure is finalized, flip the kind to call.
676   SourceN->setEdgeKind(TargetN, Edge::Call);
677 
678   // And we're done, but we did form a new cycle.
679   return true;
680 }
681 
682 void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
683                                                            Node &TargetN) {
684   assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
685 
686 #ifndef NDEBUG
687   // In a debug build, verify the RefSCC is valid to start with and when this
688   // routine finishes.
689   verify();
690   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
691 #endif
692 
693   assert(G->lookupRefSCC(SourceN) == this &&
694          "Source must be in this RefSCC.");
695   assert(G->lookupRefSCC(TargetN) == this &&
696          "Target must be in this RefSCC.");
697   assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
698          "Source and Target must be in separate SCCs for this to be trivial!");
699 
700   // Set the edge kind.
701   SourceN->setEdgeKind(TargetN, Edge::Ref);
702 }
703 
704 iterator_range<LazyCallGraph::RefSCC::iterator>
705 LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
706   assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
707 
708 #ifndef NDEBUG
709   // In a debug build, verify the RefSCC is valid to start with and when this
710   // routine finishes.
711   verify();
712   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
713 #endif
714 
715   assert(G->lookupRefSCC(SourceN) == this &&
716          "Source must be in this RefSCC.");
717   assert(G->lookupRefSCC(TargetN) == this &&
718          "Target must be in this RefSCC.");
719 
720   SCC &TargetSCC = *G->lookupSCC(TargetN);
721   assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
722                                                 "the same SCC to require the "
723                                                 "full CG update.");
724 
725   // Set the edge kind.
726   SourceN->setEdgeKind(TargetN, Edge::Ref);
727 
728   // Otherwise we are removing a call edge from a single SCC. This may break
729   // the cycle. In order to compute the new set of SCCs, we need to do a small
730   // DFS over the nodes within the SCC to form any sub-cycles that remain as
731   // distinct SCCs and compute a postorder over the resulting SCCs.
732   //
733   // However, we specially handle the target node. The target node is known to
734   // reach all other nodes in the original SCC by definition. This means that
735   // we want the old SCC to be replaced with an SCC containing that node as it
736   // will be the root of whatever SCC DAG results from the DFS. Assumptions
737   // about an SCC such as the set of functions called will continue to hold,
738   // etc.
739 
740   SCC &OldSCC = TargetSCC;
741   SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
742   SmallVector<Node *, 16> PendingSCCStack;
743   SmallVector<SCC *, 4> NewSCCs;
744 
745   // Prepare the nodes for a fresh DFS.
746   SmallVector<Node *, 16> Worklist;
747   Worklist.swap(OldSCC.Nodes);
748   for (Node *N : Worklist) {
749     N->DFSNumber = N->LowLink = 0;
750     G->SCCMap.erase(N);
751   }
752 
753   // Force the target node to be in the old SCC. This also enables us to take
754   // a very significant short-cut in the standard Tarjan walk to re-form SCCs
755   // below: whenever we build an edge that reaches the target node, we know
756   // that the target node eventually connects back to all other nodes in our
757   // walk. As a consequence, we can detect and handle participants in that
758   // cycle without walking all the edges that form this connection, and instead
759   // by relying on the fundamental guarantee coming into this operation (all
760   // nodes are reachable from the target due to previously forming an SCC).
761   TargetN.DFSNumber = TargetN.LowLink = -1;
762   OldSCC.Nodes.push_back(&TargetN);
763   G->SCCMap[&TargetN] = &OldSCC;
764 
765   // Scan down the stack and DFS across the call edges.
766   for (Node *RootN : Worklist) {
767     assert(DFSStack.empty() &&
768            "Cannot begin a new root with a non-empty DFS stack!");
769     assert(PendingSCCStack.empty() &&
770            "Cannot begin a new root with pending nodes for an SCC!");
771 
772     // Skip any nodes we've already reached in the DFS.
773     if (RootN->DFSNumber != 0) {
774       assert(RootN->DFSNumber == -1 &&
775              "Shouldn't have any mid-DFS root nodes!");
776       continue;
777     }
778 
779     RootN->DFSNumber = RootN->LowLink = 1;
780     int NextDFSNumber = 2;
781 
782     DFSStack.push_back({RootN, (*RootN)->call_begin()});
783     do {
784       Node *N;
785       EdgeSequence::call_iterator I;
786       std::tie(N, I) = DFSStack.pop_back_val();
787       auto E = (*N)->call_end();
788       while (I != E) {
789         Node &ChildN = I->getNode();
790         if (ChildN.DFSNumber == 0) {
791           // We haven't yet visited this child, so descend, pushing the current
792           // node onto the stack.
793           DFSStack.push_back({N, I});
794 
795           assert(!G->SCCMap.count(&ChildN) &&
796                  "Found a node with 0 DFS number but already in an SCC!");
797           ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
798           N = &ChildN;
799           I = (*N)->call_begin();
800           E = (*N)->call_end();
801           continue;
802         }
803 
804         // Check for the child already being part of some component.
805         if (ChildN.DFSNumber == -1) {
806           if (G->lookupSCC(ChildN) == &OldSCC) {
807             // If the child is part of the old SCC, we know that it can reach
808             // every other node, so we have formed a cycle. Pull the entire DFS
809             // and pending stacks into it. See the comment above about setting
810             // up the old SCC for why we do this.
811             int OldSize = OldSCC.size();
812             OldSCC.Nodes.push_back(N);
813             OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
814             PendingSCCStack.clear();
815             while (!DFSStack.empty())
816               OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
817             for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
818               N.DFSNumber = N.LowLink = -1;
819               G->SCCMap[&N] = &OldSCC;
820             }
821             N = nullptr;
822             break;
823           }
824 
825           // If the child has already been added to some child component, it
826           // couldn't impact the low-link of this parent because it isn't
827           // connected, and thus its low-link isn't relevant so skip it.
828           ++I;
829           continue;
830         }
831 
832         // Track the lowest linked child as the lowest link for this node.
833         assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
834         if (ChildN.LowLink < N->LowLink)
835           N->LowLink = ChildN.LowLink;
836 
837         // Move to the next edge.
838         ++I;
839       }
840       if (!N)
841         // Cleared the DFS early, start another round.
842         break;
843 
844       // We've finished processing N and its descendants, put it on our pending
845       // SCC stack to eventually get merged into an SCC of nodes.
846       PendingSCCStack.push_back(N);
847 
848       // If this node is linked to some lower entry, continue walking up the
849       // stack.
850       if (N->LowLink != N->DFSNumber)
851         continue;
852 
853       // Otherwise, we've completed an SCC. Append it to our post order list of
854       // SCCs.
855       int RootDFSNumber = N->DFSNumber;
856       // Find the range of the node stack by walking down until we pass the
857       // root DFS number.
858       auto SCCNodes = make_range(
859           PendingSCCStack.rbegin(),
860           find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
861             return N->DFSNumber < RootDFSNumber;
862           }));
863 
864       // Form a new SCC out of these nodes and then clear them off our pending
865       // stack.
866       NewSCCs.push_back(G->createSCC(*this, SCCNodes));
867       for (Node &N : *NewSCCs.back()) {
868         N.DFSNumber = N.LowLink = -1;
869         G->SCCMap[&N] = NewSCCs.back();
870       }
871       PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
872     } while (!DFSStack.empty());
873   }
874 
875   // Insert the remaining SCCs before the old one. The old SCC can reach all
876   // other SCCs we form because it contains the target node of the removed edge
877   // of the old SCC. This means that we will have edges into all of the new
878   // SCCs, which means the old one must come last for postorder.
879   int OldIdx = SCCIndices[&OldSCC];
880   SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
881 
882   // Update the mapping from SCC* to index to use the new SCC*s, and remove the
883   // old SCC from the mapping.
884   for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
885     SCCIndices[SCCs[Idx]] = Idx;
886 
887   return make_range(SCCs.begin() + OldIdx,
888                     SCCs.begin() + OldIdx + NewSCCs.size());
889 }
890 
891 void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
892                                                      Node &TargetN) {
893   assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
894 
895   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
896   assert(G->lookupRefSCC(TargetN) != this &&
897          "Target must not be in this RefSCC.");
898 #ifdef EXPENSIVE_CHECKS
899   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
900          "Target must be a descendant of the Source.");
901 #endif
902 
903   // Edges between RefSCCs are the same regardless of call or ref, so we can
904   // just flip the edge here.
905   SourceN->setEdgeKind(TargetN, Edge::Call);
906 
907 #ifndef NDEBUG
908   // Check that the RefSCC is still valid.
909   verify();
910 #endif
911 }
912 
913 void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
914                                                     Node &TargetN) {
915   assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
916 
917   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
918   assert(G->lookupRefSCC(TargetN) != this &&
919          "Target must not be in this RefSCC.");
920 #ifdef EXPENSIVE_CHECKS
921   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
922          "Target must be a descendant of the Source.");
923 #endif
924 
925   // Edges between RefSCCs are the same regardless of call or ref, so we can
926   // just flip the edge here.
927   SourceN->setEdgeKind(TargetN, Edge::Ref);
928 
929 #ifndef NDEBUG
930   // Check that the RefSCC is still valid.
931   verify();
932 #endif
933 }
934 
935 void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
936                                                   Node &TargetN) {
937   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
938   assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
939 
940   SourceN->insertEdgeInternal(TargetN, Edge::Ref);
941 
942 #ifndef NDEBUG
943   // Check that the RefSCC is still valid.
944   verify();
945 #endif
946 }
947 
948 void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
949                                                Edge::Kind EK) {
950   // First insert it into the caller.
951   SourceN->insertEdgeInternal(TargetN, EK);
952 
953   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
954 
955   assert(G->lookupRefSCC(TargetN) != this &&
956          "Target must not be in this RefSCC.");
957 #ifdef EXPENSIVE_CHECKS
958   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
959          "Target must be a descendant of the Source.");
960 #endif
961 
962 #ifndef NDEBUG
963   // Check that the RefSCC is still valid.
964   verify();
965 #endif
966 }
967 
968 SmallVector<LazyCallGraph::RefSCC *, 1>
969 LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
970   assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
971   RefSCC &SourceC = *G->lookupRefSCC(SourceN);
972   assert(&SourceC != this && "Source must not be in this RefSCC.");
973 #ifdef EXPENSIVE_CHECKS
974   assert(SourceC.isDescendantOf(*this) &&
975          "Source must be a descendant of the Target.");
976 #endif
977 
978   SmallVector<RefSCC *, 1> DeletedRefSCCs;
979 
980 #ifndef NDEBUG
981   // In a debug build, verify the RefSCC is valid to start with and when this
982   // routine finishes.
983   verify();
984   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
985 #endif
986 
987   int SourceIdx = G->RefSCCIndices[&SourceC];
988   int TargetIdx = G->RefSCCIndices[this];
989   assert(SourceIdx < TargetIdx &&
990          "Postorder list doesn't see edge as incoming!");
991 
992   // Compute the RefSCCs which (transitively) reach the source. We do this by
993   // working backwards from the source using the parent set in each RefSCC,
994   // skipping any RefSCCs that don't fall in the postorder range. This has the
995   // advantage of walking the sparser parent edge (in high fan-out graphs) but
996   // more importantly this removes examining all forward edges in all RefSCCs
997   // within the postorder range which aren't in fact connected. Only connected
998   // RefSCCs (and their edges) are visited here.
999   auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
1000     Set.insert(&SourceC);
1001     auto IsConnected = [&](RefSCC &RC) {
1002       for (SCC &C : RC)
1003         for (Node &N : C)
1004           for (Edge &E : *N)
1005             if (Set.count(G->lookupRefSCC(E.getNode())))
1006               return true;
1007 
1008       return false;
1009     };
1010 
1011     for (RefSCC *C : make_range(G->PostOrderRefSCCs.begin() + SourceIdx + 1,
1012                                 G->PostOrderRefSCCs.begin() + TargetIdx + 1))
1013       if (IsConnected(*C))
1014         Set.insert(C);
1015   };
1016 
1017   // Use a normal worklist to find which SCCs the target connects to. We still
1018   // bound the search based on the range in the postorder list we care about,
1019   // but because this is forward connectivity we just "recurse" through the
1020   // edges.
1021   auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
1022     Set.insert(this);
1023     SmallVector<RefSCC *, 4> Worklist;
1024     Worklist.push_back(this);
1025     do {
1026       RefSCC &RC = *Worklist.pop_back_val();
1027       for (SCC &C : RC)
1028         for (Node &N : C)
1029           for (Edge &E : *N) {
1030             RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
1031             if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
1032               // Not in the postorder sequence between source and target.
1033               continue;
1034 
1035             if (Set.insert(&EdgeRC).second)
1036               Worklist.push_back(&EdgeRC);
1037           }
1038     } while (!Worklist.empty());
1039   };
1040 
1041   // Use a generic helper to update the postorder sequence of RefSCCs and return
1042   // a range of any RefSCCs connected into a cycle by inserting this edge. This
1043   // routine will also take care of updating the indices into the postorder
1044   // sequence.
1045   iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
1046       updatePostorderSequenceForEdgeInsertion(
1047           SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
1048           ComputeSourceConnectedSet, ComputeTargetConnectedSet);
1049 
1050   // Build a set so we can do fast tests for whether a RefSCC will end up as
1051   // part of the merged RefSCC.
1052   SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
1053 
1054   // This RefSCC will always be part of that set, so just insert it here.
1055   MergeSet.insert(this);
1056 
1057   // Now that we have identified all of the SCCs which need to be merged into
1058   // a connected set with the inserted edge, merge all of them into this SCC.
1059   SmallVector<SCC *, 16> MergedSCCs;
1060   int SCCIndex = 0;
1061   for (RefSCC *RC : MergeRange) {
1062     assert(RC != this && "We're merging into the target RefSCC, so it "
1063                          "shouldn't be in the range.");
1064 
1065     // Walk the inner SCCs to update their up-pointer and walk all the edges to
1066     // update any parent sets.
1067     // FIXME: We should try to find a way to avoid this (rather expensive) edge
1068     // walk by updating the parent sets in some other manner.
1069     for (SCC &InnerC : *RC) {
1070       InnerC.OuterRefSCC = this;
1071       SCCIndices[&InnerC] = SCCIndex++;
1072       for (Node &N : InnerC)
1073         G->SCCMap[&N] = &InnerC;
1074     }
1075 
1076     // Now merge in the SCCs. We can actually move here so try to reuse storage
1077     // the first time through.
1078     if (MergedSCCs.empty())
1079       MergedSCCs = std::move(RC->SCCs);
1080     else
1081       MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
1082     RC->SCCs.clear();
1083     DeletedRefSCCs.push_back(RC);
1084   }
1085 
1086   // Append our original SCCs to the merged list and move it into place.
1087   for (SCC &InnerC : *this)
1088     SCCIndices[&InnerC] = SCCIndex++;
1089   MergedSCCs.append(SCCs.begin(), SCCs.end());
1090   SCCs = std::move(MergedSCCs);
1091 
1092   // Remove the merged away RefSCCs from the post order sequence.
1093   for (RefSCC *RC : MergeRange)
1094     G->RefSCCIndices.erase(RC);
1095   int IndexOffset = MergeRange.end() - MergeRange.begin();
1096   auto EraseEnd =
1097       G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1098   for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
1099     G->RefSCCIndices[RC] -= IndexOffset;
1100 
1101   // At this point we have a merged RefSCC with a post-order SCCs list, just
1102   // connect the nodes to form the new edge.
1103   SourceN->insertEdgeInternal(TargetN, Edge::Ref);
1104 
1105   // We return the list of SCCs which were merged so that callers can
1106   // invalidate any data they have associated with those SCCs. Note that these
1107   // SCCs are no longer in an interesting state (they are totally empty) but
1108   // the pointers will remain stable for the life of the graph itself.
1109   return DeletedRefSCCs;
1110 }
1111 
1112 void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1113   assert(G->lookupRefSCC(SourceN) == this &&
1114          "The source must be a member of this RefSCC.");
1115   assert(G->lookupRefSCC(TargetN) != this &&
1116          "The target must not be a member of this RefSCC");
1117 
1118 #ifndef NDEBUG
1119   // In a debug build, verify the RefSCC is valid to start with and when this
1120   // routine finishes.
1121   verify();
1122   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1123 #endif
1124 
1125   // First remove it from the node.
1126   bool Removed = SourceN->removeEdgeInternal(TargetN);
1127   (void)Removed;
1128   assert(Removed && "Target not in the edge set for this caller?");
1129 }
1130 
1131 SmallVector<LazyCallGraph::RefSCC *, 1>
1132 LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN,
1133                                              ArrayRef<Node *> TargetNs) {
1134   // We return a list of the resulting *new* RefSCCs in post-order.
1135   SmallVector<RefSCC *, 1> Result;
1136 
1137 #ifndef NDEBUG
1138   // In a debug build, verify the RefSCC is valid to start with and that either
1139   // we return an empty list of result RefSCCs and this RefSCC remains valid,
1140   // or we return new RefSCCs and this RefSCC is dead.
1141   verify();
1142   auto VerifyOnExit = make_scope_exit([&]() {
1143     // If we didn't replace our RefSCC with new ones, check that this one
1144     // remains valid.
1145     if (G)
1146       verify();
1147   });
1148 #endif
1149 
1150   // First remove the actual edges.
1151   for (Node *TargetN : TargetNs) {
1152     assert(!(*SourceN)[*TargetN].isCall() &&
1153            "Cannot remove a call edge, it must first be made a ref edge");
1154 
1155     bool Removed = SourceN->removeEdgeInternal(*TargetN);
1156     (void)Removed;
1157     assert(Removed && "Target not in the edge set for this caller?");
1158   }
1159 
1160   // Direct self references don't impact the ref graph at all.
1161   if (llvm::all_of(TargetNs,
1162                    [&](Node *TargetN) { return &SourceN == TargetN; }))
1163     return Result;
1164 
1165   // If all targets are in the same SCC as the source, because no call edges
1166   // were removed there is no RefSCC structure change.
1167   SCC &SourceC = *G->lookupSCC(SourceN);
1168   if (llvm::all_of(TargetNs, [&](Node *TargetN) {
1169         return G->lookupSCC(*TargetN) == &SourceC;
1170       }))
1171     return Result;
1172 
1173   // We build somewhat synthetic new RefSCCs by providing a postorder mapping
1174   // for each inner SCC. We store these inside the low-link field of the nodes
1175   // rather than associated with SCCs because this saves a round-trip through
1176   // the node->SCC map and in the common case, SCCs are small. We will verify
1177   // that we always give the same number to every node in the SCC such that
1178   // these are equivalent.
1179   int PostOrderNumber = 0;
1180 
1181   // Reset all the other nodes to prepare for a DFS over them, and add them to
1182   // our worklist.
1183   SmallVector<Node *, 8> Worklist;
1184   for (SCC *C : SCCs) {
1185     for (Node &N : *C)
1186       N.DFSNumber = N.LowLink = 0;
1187 
1188     Worklist.append(C->Nodes.begin(), C->Nodes.end());
1189   }
1190 
1191   // Track the number of nodes in this RefSCC so that we can quickly recognize
1192   // an important special case of the edge removal not breaking the cycle of
1193   // this RefSCC.
1194   const int NumRefSCCNodes = Worklist.size();
1195 
1196   SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
1197   SmallVector<Node *, 4> PendingRefSCCStack;
1198   do {
1199     assert(DFSStack.empty() &&
1200            "Cannot begin a new root with a non-empty DFS stack!");
1201     assert(PendingRefSCCStack.empty() &&
1202            "Cannot begin a new root with pending nodes for an SCC!");
1203 
1204     Node *RootN = Worklist.pop_back_val();
1205     // Skip any nodes we've already reached in the DFS.
1206     if (RootN->DFSNumber != 0) {
1207       assert(RootN->DFSNumber == -1 &&
1208              "Shouldn't have any mid-DFS root nodes!");
1209       continue;
1210     }
1211 
1212     RootN->DFSNumber = RootN->LowLink = 1;
1213     int NextDFSNumber = 2;
1214 
1215     DFSStack.push_back({RootN, (*RootN)->begin()});
1216     do {
1217       Node *N;
1218       EdgeSequence::iterator I;
1219       std::tie(N, I) = DFSStack.pop_back_val();
1220       auto E = (*N)->end();
1221 
1222       assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1223                                   "before processing a node.");
1224 
1225       while (I != E) {
1226         Node &ChildN = I->getNode();
1227         if (ChildN.DFSNumber == 0) {
1228           // Mark that we should start at this child when next this node is the
1229           // top of the stack. We don't start at the next child to ensure this
1230           // child's lowlink is reflected.
1231           DFSStack.push_back({N, I});
1232 
1233           // Continue, resetting to the child node.
1234           ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1235           N = &ChildN;
1236           I = ChildN->begin();
1237           E = ChildN->end();
1238           continue;
1239         }
1240         if (ChildN.DFSNumber == -1) {
1241           // If this child isn't currently in this RefSCC, no need to process
1242           // it.
1243           ++I;
1244           continue;
1245         }
1246 
1247         // Track the lowest link of the children, if any are still in the stack.
1248         // Any child not on the stack will have a LowLink of -1.
1249         assert(ChildN.LowLink != 0 &&
1250                "Low-link must not be zero with a non-zero DFS number.");
1251         if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1252           N->LowLink = ChildN.LowLink;
1253         ++I;
1254       }
1255 
1256       // We've finished processing N and its descendants, put it on our pending
1257       // stack to eventually get merged into a RefSCC.
1258       PendingRefSCCStack.push_back(N);
1259 
1260       // If this node is linked to some lower entry, continue walking up the
1261       // stack.
1262       if (N->LowLink != N->DFSNumber) {
1263         assert(!DFSStack.empty() &&
1264                "We never found a viable root for a RefSCC to pop off!");
1265         continue;
1266       }
1267 
1268       // Otherwise, form a new RefSCC from the top of the pending node stack.
1269       int RefSCCNumber = PostOrderNumber++;
1270       int RootDFSNumber = N->DFSNumber;
1271 
1272       // Find the range of the node stack by walking down until we pass the
1273       // root DFS number. Update the DFS numbers and low link numbers in the
1274       // process to avoid re-walking this list where possible.
1275       auto StackRI = find_if(reverse(PendingRefSCCStack), [&](Node *N) {
1276         if (N->DFSNumber < RootDFSNumber)
1277           // We've found the bottom.
1278           return true;
1279 
1280         // Update this node and keep scanning.
1281         N->DFSNumber = -1;
1282         // Save the post-order number in the lowlink field so that we can use
1283         // it to map SCCs into new RefSCCs after we finish the DFS.
1284         N->LowLink = RefSCCNumber;
1285         return false;
1286       });
1287       auto RefSCCNodes = make_range(StackRI.base(), PendingRefSCCStack.end());
1288 
1289       // If we find a cycle containing all nodes originally in this RefSCC then
1290       // the removal hasn't changed the structure at all. This is an important
1291       // special case and we can directly exit the entire routine more
1292       // efficiently as soon as we discover it.
1293       if (llvm::size(RefSCCNodes) == NumRefSCCNodes) {
1294         // Clear out the low link field as we won't need it.
1295         for (Node *N : RefSCCNodes)
1296           N->LowLink = -1;
1297         // Return the empty result immediately.
1298         return Result;
1299       }
1300 
1301       // We've already marked the nodes internally with the RefSCC number so
1302       // just clear them off the stack and continue.
1303       PendingRefSCCStack.erase(RefSCCNodes.begin(), PendingRefSCCStack.end());
1304     } while (!DFSStack.empty());
1305 
1306     assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
1307     assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
1308   } while (!Worklist.empty());
1309 
1310   assert(PostOrderNumber > 1 &&
1311          "Should never finish the DFS when the existing RefSCC remains valid!");
1312 
1313   // Otherwise we create a collection of new RefSCC nodes and build
1314   // a radix-sort style map from postorder number to these new RefSCCs. We then
1315   // append SCCs to each of these RefSCCs in the order they occurred in the
1316   // original SCCs container.
1317   for (int i = 0; i < PostOrderNumber; ++i)
1318     Result.push_back(G->createRefSCC(*G));
1319 
1320   // Insert the resulting postorder sequence into the global graph postorder
1321   // sequence before the current RefSCC in that sequence, and then remove the
1322   // current one.
1323   //
1324   // FIXME: It'd be nice to change the APIs so that we returned an iterator
1325   // range over the global postorder sequence and generally use that sequence
1326   // rather than building a separate result vector here.
1327   int Idx = G->getRefSCCIndex(*this);
1328   G->PostOrderRefSCCs.erase(G->PostOrderRefSCCs.begin() + Idx);
1329   G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx, Result.begin(),
1330                              Result.end());
1331   for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1332     G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
1333 
1334   for (SCC *C : SCCs) {
1335     // We store the SCC number in the node's low-link field above.
1336     int SCCNumber = C->begin()->LowLink;
1337     // Clear out all of the SCC's node's low-link fields now that we're done
1338     // using them as side-storage.
1339     for (Node &N : *C) {
1340       assert(N.LowLink == SCCNumber &&
1341              "Cannot have different numbers for nodes in the same SCC!");
1342       N.LowLink = -1;
1343     }
1344 
1345     RefSCC &RC = *Result[SCCNumber];
1346     int SCCIndex = RC.SCCs.size();
1347     RC.SCCs.push_back(C);
1348     RC.SCCIndices[C] = SCCIndex;
1349     C->OuterRefSCC = &RC;
1350   }
1351 
1352   // Now that we've moved things into the new RefSCCs, clear out our current
1353   // one.
1354   G = nullptr;
1355   SCCs.clear();
1356   SCCIndices.clear();
1357 
1358 #ifndef NDEBUG
1359   // Verify the new RefSCCs we've built.
1360   for (RefSCC *RC : Result)
1361     RC->verify();
1362 #endif
1363 
1364   // Return the new list of SCCs.
1365   return Result;
1366 }
1367 
1368 void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1369                                                        Node &TargetN) {
1370   // The only trivial case that requires any graph updates is when we add new
1371   // ref edge and may connect different RefSCCs along that path. This is only
1372   // because of the parents set. Every other part of the graph remains constant
1373   // after this edge insertion.
1374   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
1375   RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1376   if (&TargetRC == this)
1377     return;
1378 
1379 #ifdef EXPENSIVE_CHECKS
1380   assert(TargetRC.isDescendantOf(*this) &&
1381          "Target must be a descendant of the Source.");
1382 #endif
1383 }
1384 
1385 void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
1386                                                   Node &TargetN) {
1387 #ifndef NDEBUG
1388   // Check that the RefSCC is still valid when we finish.
1389   auto ExitVerifier = make_scope_exit([this] { verify(); });
1390 
1391 #ifdef EXPENSIVE_CHECKS
1392   // Check that we aren't breaking some invariants of the SCC graph. Note that
1393   // this is quadratic in the number of edges in the call graph!
1394   SCC &SourceC = *G->lookupSCC(SourceN);
1395   SCC &TargetC = *G->lookupSCC(TargetN);
1396   if (&SourceC != &TargetC)
1397     assert(SourceC.isAncestorOf(TargetC) &&
1398            "Call edge is not trivial in the SCC graph!");
1399 #endif // EXPENSIVE_CHECKS
1400 #endif // NDEBUG
1401 
1402   // First insert it into the source or find the existing edge.
1403   auto InsertResult =
1404       SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
1405   if (!InsertResult.second) {
1406     // Already an edge, just update it.
1407     Edge &E = SourceN->Edges[InsertResult.first->second];
1408     if (E.isCall())
1409       return; // Nothing to do!
1410     E.setKind(Edge::Call);
1411   } else {
1412     // Create the new edge.
1413     SourceN->Edges.emplace_back(TargetN, Edge::Call);
1414   }
1415 
1416   // Now that we have the edge, handle the graph fallout.
1417   handleTrivialEdgeInsertion(SourceN, TargetN);
1418 }
1419 
1420 void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1421 #ifndef NDEBUG
1422   // Check that the RefSCC is still valid when we finish.
1423   auto ExitVerifier = make_scope_exit([this] { verify(); });
1424 
1425 #ifdef EXPENSIVE_CHECKS
1426   // Check that we aren't breaking some invariants of the RefSCC graph.
1427   RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
1428   RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1429   if (&SourceRC != &TargetRC)
1430     assert(SourceRC.isAncestorOf(TargetRC) &&
1431            "Ref edge is not trivial in the RefSCC graph!");
1432 #endif // EXPENSIVE_CHECKS
1433 #endif // NDEBUG
1434 
1435   // First insert it into the source or find the existing edge.
1436   auto InsertResult =
1437       SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
1438   if (!InsertResult.second)
1439     // Already an edge, we're done.
1440     return;
1441 
1442   // Create the new edge.
1443   SourceN->Edges.emplace_back(TargetN, Edge::Ref);
1444 
1445   // Now that we have the edge, handle the graph fallout.
1446   handleTrivialEdgeInsertion(SourceN, TargetN);
1447 }
1448 
1449 void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1450   Function &OldF = N.getFunction();
1451 
1452 #ifndef NDEBUG
1453   // Check that the RefSCC is still valid when we finish.
1454   auto ExitVerifier = make_scope_exit([this] { verify(); });
1455 
1456   assert(G->lookupRefSCC(N) == this &&
1457          "Cannot replace the function of a node outside this RefSCC.");
1458 
1459   assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1460          "Must not have already walked the new function!'");
1461 
1462   // It is important that this replacement not introduce graph changes so we
1463   // insist that the caller has already removed every use of the original
1464   // function and that all uses of the new function correspond to existing
1465   // edges in the graph. The common and expected way to use this is when
1466   // replacing the function itself in the IR without changing the call graph
1467   // shape and just updating the analysis based on that.
1468   assert(&OldF != &NewF && "Cannot replace a function with itself!");
1469   assert(OldF.use_empty() &&
1470          "Must have moved all uses from the old function to the new!");
1471 #endif
1472 
1473   N.replaceFunction(NewF);
1474 
1475   // Update various call graph maps.
1476   G->NodeMap.erase(&OldF);
1477   G->NodeMap[&NewF] = &N;
1478 }
1479 
1480 void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
1481   assert(SCCMap.empty() &&
1482          "This method cannot be called after SCCs have been formed!");
1483 
1484   return SourceN->insertEdgeInternal(TargetN, EK);
1485 }
1486 
1487 void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1488   assert(SCCMap.empty() &&
1489          "This method cannot be called after SCCs have been formed!");
1490 
1491   bool Removed = SourceN->removeEdgeInternal(TargetN);
1492   (void)Removed;
1493   assert(Removed && "Target not in the edge set for this caller?");
1494 }
1495 
1496 void LazyCallGraph::removeDeadFunction(Function &F) {
1497   // FIXME: This is unnecessarily restrictive. We should be able to remove
1498   // functions which recursively call themselves.
1499   assert(F.use_empty() &&
1500          "This routine should only be called on trivially dead functions!");
1501 
1502   // We shouldn't remove library functions as they are never really dead while
1503   // the call graph is in use -- every function definition refers to them.
1504   assert(!isLibFunction(F) &&
1505          "Must not remove lib functions from the call graph!");
1506 
1507   auto NI = NodeMap.find(&F);
1508   if (NI == NodeMap.end())
1509     // Not in the graph at all!
1510     return;
1511 
1512   Node &N = *NI->second;
1513   NodeMap.erase(NI);
1514 
1515   // Remove this from the entry edges if present.
1516   EntryEdges.removeEdgeInternal(N);
1517 
1518   if (SCCMap.empty()) {
1519     // No SCCs have been formed, so removing this is fine and there is nothing
1520     // else necessary at this point but clearing out the node.
1521     N.clear();
1522     return;
1523   }
1524 
1525   // Cannot remove a function which has yet to be visited in the DFS walk, so
1526   // if we have a node at all then we must have an SCC and RefSCC.
1527   auto CI = SCCMap.find(&N);
1528   assert(CI != SCCMap.end() &&
1529          "Tried to remove a node without an SCC after DFS walk started!");
1530   SCC &C = *CI->second;
1531   SCCMap.erase(CI);
1532   RefSCC &RC = C.getOuterRefSCC();
1533 
1534   // This node must be the only member of its SCC as it has no callers, and
1535   // that SCC must be the only member of a RefSCC as it has no references.
1536   // Validate these properties first.
1537   assert(C.size() == 1 && "Dead functions must be in a singular SCC");
1538   assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
1539 
1540   auto RCIndexI = RefSCCIndices.find(&RC);
1541   int RCIndex = RCIndexI->second;
1542   PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1543   RefSCCIndices.erase(RCIndexI);
1544   for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i)
1545     RefSCCIndices[PostOrderRefSCCs[i]] = i;
1546 
1547   // Finally clear out all the data structures from the node down through the
1548   // components.
1549   N.clear();
1550   N.G = nullptr;
1551   N.F = nullptr;
1552   C.clear();
1553   RC.clear();
1554   RC.G = nullptr;
1555 
1556   // Nothing to delete as all the objects are allocated in stable bump pointer
1557   // allocators.
1558 }
1559 
1560 LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1561   return *new (MappedN = BPA.Allocate()) Node(*this, F);
1562 }
1563 
1564 void LazyCallGraph::updateGraphPtrs() {
1565   // Walk the node map to update their graph pointers. While this iterates in
1566   // an unstable order, the order has no effect so it remains correct.
1567   for (auto &FunctionNodePair : NodeMap)
1568     FunctionNodePair.second->G = this;
1569 
1570   for (auto *RC : PostOrderRefSCCs)
1571     RC->G = this;
1572 }
1573 
1574 template <typename RootsT, typename GetBeginT, typename GetEndT,
1575           typename GetNodeT, typename FormSCCCallbackT>
1576 void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1577                                      GetEndT &&GetEnd, GetNodeT &&GetNode,
1578                                      FormSCCCallbackT &&FormSCC) {
1579   using EdgeItT = decltype(GetBegin(std::declval<Node &>()));
1580 
1581   SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
1582   SmallVector<Node *, 16> PendingSCCStack;
1583 
1584   // Scan down the stack and DFS across the call edges.
1585   for (Node *RootN : Roots) {
1586     assert(DFSStack.empty() &&
1587            "Cannot begin a new root with a non-empty DFS stack!");
1588     assert(PendingSCCStack.empty() &&
1589            "Cannot begin a new root with pending nodes for an SCC!");
1590 
1591     // Skip any nodes we've already reached in the DFS.
1592     if (RootN->DFSNumber != 0) {
1593       assert(RootN->DFSNumber == -1 &&
1594              "Shouldn't have any mid-DFS root nodes!");
1595       continue;
1596     }
1597 
1598     RootN->DFSNumber = RootN->LowLink = 1;
1599     int NextDFSNumber = 2;
1600 
1601     DFSStack.push_back({RootN, GetBegin(*RootN)});
1602     do {
1603       Node *N;
1604       EdgeItT I;
1605       std::tie(N, I) = DFSStack.pop_back_val();
1606       auto E = GetEnd(*N);
1607       while (I != E) {
1608         Node &ChildN = GetNode(I);
1609         if (ChildN.DFSNumber == 0) {
1610           // We haven't yet visited this child, so descend, pushing the current
1611           // node onto the stack.
1612           DFSStack.push_back({N, I});
1613 
1614           ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1615           N = &ChildN;
1616           I = GetBegin(*N);
1617           E = GetEnd(*N);
1618           continue;
1619         }
1620 
1621         // If the child has already been added to some child component, it
1622         // couldn't impact the low-link of this parent because it isn't
1623         // connected, and thus its low-link isn't relevant so skip it.
1624         if (ChildN.DFSNumber == -1) {
1625           ++I;
1626           continue;
1627         }
1628 
1629         // Track the lowest linked child as the lowest link for this node.
1630         assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1631         if (ChildN.LowLink < N->LowLink)
1632           N->LowLink = ChildN.LowLink;
1633 
1634         // Move to the next edge.
1635         ++I;
1636       }
1637 
1638       // We've finished processing N and its descendants, put it on our pending
1639       // SCC stack to eventually get merged into an SCC of nodes.
1640       PendingSCCStack.push_back(N);
1641 
1642       // If this node is linked to some lower entry, continue walking up the
1643       // stack.
1644       if (N->LowLink != N->DFSNumber)
1645         continue;
1646 
1647       // Otherwise, we've completed an SCC. Append it to our post order list of
1648       // SCCs.
1649       int RootDFSNumber = N->DFSNumber;
1650       // Find the range of the node stack by walking down until we pass the
1651       // root DFS number.
1652       auto SCCNodes = make_range(
1653           PendingSCCStack.rbegin(),
1654           find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1655             return N->DFSNumber < RootDFSNumber;
1656           }));
1657       // Form a new SCC out of these nodes and then clear them off our pending
1658       // stack.
1659       FormSCC(SCCNodes);
1660       PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1661     } while (!DFSStack.empty());
1662   }
1663 }
1664 
1665 /// Build the internal SCCs for a RefSCC from a sequence of nodes.
1666 ///
1667 /// Appends the SCCs to the provided vector and updates the map with their
1668 /// indices. Both the vector and map must be empty when passed into this
1669 /// routine.
1670 void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1671   assert(RC.SCCs.empty() && "Already built SCCs!");
1672   assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1673 
1674   for (Node *N : Nodes) {
1675     assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1676            "We cannot have a low link in an SCC lower than its root on the "
1677            "stack!");
1678 
1679     // This node will go into the next RefSCC, clear out its DFS and low link
1680     // as we scan.
1681     N->DFSNumber = N->LowLink = 0;
1682   }
1683 
1684   // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1685   // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1686   // internal storage as we won't need it for the outer graph's DFS any longer.
1687   buildGenericSCCs(
1688       Nodes, [](Node &N) { return N->call_begin(); },
1689       [](Node &N) { return N->call_end(); },
1690       [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
1691       [this, &RC](node_stack_range Nodes) {
1692         RC.SCCs.push_back(createSCC(RC, Nodes));
1693         for (Node &N : *RC.SCCs.back()) {
1694           N.DFSNumber = N.LowLink = -1;
1695           SCCMap[&N] = RC.SCCs.back();
1696         }
1697       });
1698 
1699   // Wire up the SCC indices.
1700   for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1701     RC.SCCIndices[RC.SCCs[i]] = i;
1702 }
1703 
1704 void LazyCallGraph::buildRefSCCs() {
1705   if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1706     // RefSCCs are either non-existent or already built!
1707     return;
1708 
1709   assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
1710 
1711   SmallVector<Node *, 16> Roots;
1712   for (Edge &E : *this)
1713     Roots.push_back(&E.getNode());
1714 
1715   // The roots will be popped of a stack, so use reverse to get a less
1716   // surprising order. This doesn't change any of the semantics anywhere.
1717   std::reverse(Roots.begin(), Roots.end());
1718 
1719   buildGenericSCCs(
1720       Roots,
1721       [](Node &N) {
1722         // We need to populate each node as we begin to walk its edges.
1723         N.populate();
1724         return N->begin();
1725       },
1726       [](Node &N) { return N->end(); },
1727       [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
1728       [this](node_stack_range Nodes) {
1729         RefSCC *NewRC = createRefSCC(*this);
1730         buildSCCs(*NewRC, Nodes);
1731 
1732         // Push the new node into the postorder list and remember its position
1733         // in the index map.
1734         bool Inserted =
1735             RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
1736         (void)Inserted;
1737         assert(Inserted && "Cannot already have this RefSCC in the index map!");
1738         PostOrderRefSCCs.push_back(NewRC);
1739 #ifndef NDEBUG
1740         NewRC->verify();
1741 #endif
1742       });
1743 }
1744 
1745 AnalysisKey LazyCallGraphAnalysis::Key;
1746 
1747 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1748 
1749 static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
1750   OS << "  Edges in function: " << N.getFunction().getName() << "\n";
1751   for (LazyCallGraph::Edge &E : N.populate())
1752     OS << "    " << (E.isCall() ? "call" : "ref ") << " -> "
1753        << E.getFunction().getName() << "\n";
1754 
1755   OS << "\n";
1756 }
1757 
1758 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1759   OS << "    SCC with " << C.size() << " functions:\n";
1760 
1761   for (LazyCallGraph::Node &N : C)
1762     OS << "      " << N.getFunction().getName() << "\n";
1763 }
1764 
1765 static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1766   OS << "  RefSCC with " << C.size() << " call SCCs:\n";
1767 
1768   for (LazyCallGraph::SCC &InnerC : C)
1769     printSCC(OS, InnerC);
1770 
1771   OS << "\n";
1772 }
1773 
1774 PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
1775                                                 ModuleAnalysisManager &AM) {
1776   LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1777 
1778   OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1779      << "\n\n";
1780 
1781   for (Function &F : M)
1782     printNode(OS, G.get(F));
1783 
1784   G.buildRefSCCs();
1785   for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1786     printRefSCC(OS, C);
1787 
1788   return PreservedAnalyses::all();
1789 }
1790 
1791 LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1792     : OS(OS) {}
1793 
1794 static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1795   std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1796 
1797   for (LazyCallGraph::Edge &E : N.populate()) {
1798     OS << "  " << Name << " -> \""
1799        << DOT::EscapeString(E.getFunction().getName()) << "\"";
1800     if (!E.isCall()) // It is a ref edge.
1801       OS << " [style=dashed,label=\"ref\"]";
1802     OS << ";\n";
1803   }
1804 
1805   OS << "\n";
1806 }
1807 
1808 PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1809                                                    ModuleAnalysisManager &AM) {
1810   LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1811 
1812   OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1813 
1814   for (Function &F : M)
1815     printNodeDOT(OS, G.get(F));
1816 
1817   OS << "}\n";
1818 
1819   return PreservedAnalyses::all();
1820 }
1821