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