1 //===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
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/CGSCCPassManager.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/Analysis/LazyCallGraph.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/InstIterator.h"
20 #include "llvm/IR/Instruction.h"
21 #include "llvm/IR/PassManager.h"
22 #include "llvm/IR/PassManagerImpl.h"
23 #include "llvm/IR/ValueHandle.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/TimeProfiler.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <iterator>
33 
34 #define DEBUG_TYPE "cgscc"
35 
36 using namespace llvm;
37 
38 // Explicit template instantiations and specialization definitions for core
39 // template typedefs.
40 namespace llvm {
41 extern cl::opt<bool> EagerlyInvalidateAnalyses;
42 
43 static cl::opt<bool> AbortOnMaxDevirtIterationsReached(
44     "abort-on-max-devirt-iterations-reached",
45     cl::desc("Abort when the max iterations for devirtualization CGSCC repeat "
46              "pass is reached"));
47 
48 // Explicit instantiations for the core proxy templates.
49 template class AllAnalysesOn<LazyCallGraph::SCC>;
50 template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
51 template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
52                            LazyCallGraph &, CGSCCUpdateResult &>;
53 template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
54 template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
55                                          LazyCallGraph::SCC, LazyCallGraph &>;
56 template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
57 
58 /// Explicitly specialize the pass manager run method to handle call graph
59 /// updates.
60 template <>
61 PreservedAnalyses
62 PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
63             CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
64                                       CGSCCAnalysisManager &AM,
65                                       LazyCallGraph &G, CGSCCUpdateResult &UR) {
66   // Request PassInstrumentation from analysis manager, will use it to run
67   // instrumenting callbacks for the passes later.
68   PassInstrumentation PI =
69       AM.getResult<PassInstrumentationAnalysis>(InitialC, G);
70 
71   PreservedAnalyses PA = PreservedAnalyses::all();
72 
73   // The SCC may be refined while we are running passes over it, so set up
74   // a pointer that we can update.
75   LazyCallGraph::SCC *C = &InitialC;
76 
77   // Get Function analysis manager from its proxy.
78   FunctionAnalysisManager &FAM =
79       AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*C)->getManager();
80 
81   for (auto &Pass : Passes) {
82     // Check the PassInstrumentation's BeforePass callbacks before running the
83     // pass, skip its execution completely if asked to (callback returns false).
84     if (!PI.runBeforePass(*Pass, *C))
85       continue;
86 
87     PreservedAnalyses PassPA;
88     {
89       TimeTraceScope TimeScope(Pass->name());
90       PassPA = Pass->run(*C, AM, G, UR);
91     }
92 
93     if (UR.InvalidatedSCCs.count(C))
94       PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA);
95     else
96       PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
97 
98     // Update the SCC if necessary.
99     C = UR.UpdatedC ? UR.UpdatedC : C;
100     if (UR.UpdatedC) {
101       // If C is updated, also create a proxy and update FAM inside the result.
102       auto *ResultFAMCP =
103           &AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
104       ResultFAMCP->updateFAM(FAM);
105     }
106 
107     // If the CGSCC pass wasn't able to provide a valid updated SCC, the
108     // current SCC may simply need to be skipped if invalid.
109     if (UR.InvalidatedSCCs.count(C)) {
110       LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
111       break;
112     }
113     // Check that we didn't miss any update scenario.
114     assert(C->begin() != C->end() && "Cannot have an empty SCC!");
115 
116     // Update the analysis manager as each pass runs and potentially
117     // invalidates analyses.
118     AM.invalidate(*C, PassPA);
119 
120     // Finally, we intersect the final preserved analyses to compute the
121     // aggregate preserved set for this pass manager.
122     PA.intersect(std::move(PassPA));
123   }
124 
125   // Before we mark all of *this* SCC's analyses as preserved below, intersect
126   // this with the cross-SCC preserved analysis set. This is used to allow
127   // CGSCC passes to mutate ancestor SCCs and still trigger proper invalidation
128   // for them.
129   UR.CrossSCCPA.intersect(PA);
130 
131   // Invalidation was handled after each pass in the above loop for the current
132   // SCC. Therefore, the remaining analysis results in the AnalysisManager are
133   // preserved. We mark this with a set so that we don't need to inspect each
134   // one individually.
135   PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
136 
137   return PA;
138 }
139 
140 PreservedAnalyses
141 ModuleToPostOrderCGSCCPassAdaptor::run(Module &M, ModuleAnalysisManager &AM) {
142   // Setup the CGSCC analysis manager from its proxy.
143   CGSCCAnalysisManager &CGAM =
144       AM.getResult<CGSCCAnalysisManagerModuleProxy>(M).getManager();
145 
146   // Get the call graph for this module.
147   LazyCallGraph &CG = AM.getResult<LazyCallGraphAnalysis>(M);
148 
149   // Get Function analysis manager from its proxy.
150   FunctionAnalysisManager &FAM =
151       AM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M)->getManager();
152 
153   // We keep worklists to allow us to push more work onto the pass manager as
154   // the passes are run.
155   SmallPriorityWorklist<LazyCallGraph::RefSCC *, 1> RCWorklist;
156   SmallPriorityWorklist<LazyCallGraph::SCC *, 1> CWorklist;
157 
158   // Keep sets for invalidated SCCs and RefSCCs that should be skipped when
159   // iterating off the worklists.
160   SmallPtrSet<LazyCallGraph::RefSCC *, 4> InvalidRefSCCSet;
161   SmallPtrSet<LazyCallGraph::SCC *, 4> InvalidSCCSet;
162 
163   SmallDenseSet<std::pair<LazyCallGraph::Node *, LazyCallGraph::SCC *>, 4>
164       InlinedInternalEdges;
165 
166   CGSCCUpdateResult UR = {
167       RCWorklist, CWorklist, InvalidRefSCCSet,         InvalidSCCSet,
168       nullptr,    nullptr,   PreservedAnalyses::all(), InlinedInternalEdges,
169       {}};
170 
171   // Request PassInstrumentation from analysis manager, will use it to run
172   // instrumenting callbacks for the passes later.
173   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(M);
174 
175   PreservedAnalyses PA = PreservedAnalyses::all();
176   CG.buildRefSCCs();
177   for (auto RCI = CG.postorder_ref_scc_begin(),
178             RCE = CG.postorder_ref_scc_end();
179        RCI != RCE;) {
180     assert(RCWorklist.empty() &&
181            "Should always start with an empty RefSCC worklist");
182     // The postorder_ref_sccs range we are walking is lazily constructed, so
183     // we only push the first one onto the worklist. The worklist allows us
184     // to capture *new* RefSCCs created during transformations.
185     //
186     // We really want to form RefSCCs lazily because that makes them cheaper
187     // to update as the program is simplified and allows us to have greater
188     // cache locality as forming a RefSCC touches all the parts of all the
189     // functions within that RefSCC.
190     //
191     // We also eagerly increment the iterator to the next position because
192     // the CGSCC passes below may delete the current RefSCC.
193     RCWorklist.insert(&*RCI++);
194 
195     do {
196       LazyCallGraph::RefSCC *RC = RCWorklist.pop_back_val();
197       if (InvalidRefSCCSet.count(RC)) {
198         LLVM_DEBUG(dbgs() << "Skipping an invalid RefSCC...\n");
199         continue;
200       }
201 
202       assert(CWorklist.empty() &&
203              "Should always start with an empty SCC worklist");
204 
205       LLVM_DEBUG(dbgs() << "Running an SCC pass across the RefSCC: " << *RC
206                         << "\n");
207 
208       // The top of the worklist may *also* be the same SCC we just ran over
209       // (and invalidated for). Keep track of that last SCC we processed due
210       // to SCC update to avoid redundant processing when an SCC is both just
211       // updated itself and at the top of the worklist.
212       LazyCallGraph::SCC *LastUpdatedC = nullptr;
213 
214       // Push the initial SCCs in reverse post-order as we'll pop off the
215       // back and so see this in post-order.
216       for (LazyCallGraph::SCC &C : llvm::reverse(*RC))
217         CWorklist.insert(&C);
218 
219       do {
220         LazyCallGraph::SCC *C = CWorklist.pop_back_val();
221         // Due to call graph mutations, we may have invalid SCCs or SCCs from
222         // other RefSCCs in the worklist. The invalid ones are dead and the
223         // other RefSCCs should be queued above, so we just need to skip both
224         // scenarios here.
225         if (InvalidSCCSet.count(C)) {
226           LLVM_DEBUG(dbgs() << "Skipping an invalid SCC...\n");
227           continue;
228         }
229         if (LastUpdatedC == C) {
230           LLVM_DEBUG(dbgs() << "Skipping redundant run on SCC: " << *C << "\n");
231           continue;
232         }
233         if (&C->getOuterRefSCC() != RC) {
234           LLVM_DEBUG(dbgs() << "Skipping an SCC that is now part of some other "
235                                "RefSCC...\n");
236           continue;
237         }
238 
239         // Ensure we can proxy analysis updates from the CGSCC analysis manager
240         // into the the Function analysis manager by getting a proxy here.
241         // This also needs to update the FunctionAnalysisManager, as this may be
242         // the first time we see this SCC.
243         CGAM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, CG).updateFAM(
244             FAM);
245 
246         // Each time we visit a new SCC pulled off the worklist,
247         // a transformation of a child SCC may have also modified this parent
248         // and invalidated analyses. So we invalidate using the update record's
249         // cross-SCC preserved set. This preserved set is intersected by any
250         // CGSCC pass that handles invalidation (primarily pass managers) prior
251         // to marking its SCC as preserved. That lets us track everything that
252         // might need invalidation across SCCs without excessive invalidations
253         // on a single SCC.
254         //
255         // This essentially allows SCC passes to freely invalidate analyses
256         // of any ancestor SCC. If this becomes detrimental to successfully
257         // caching analyses, we could force each SCC pass to manually
258         // invalidate the analyses for any SCCs other than themselves which
259         // are mutated. However, that seems to lose the robustness of the
260         // pass-manager driven invalidation scheme.
261         CGAM.invalidate(*C, UR.CrossSCCPA);
262 
263         do {
264           // Check that we didn't miss any update scenario.
265           assert(!InvalidSCCSet.count(C) && "Processing an invalid SCC!");
266           assert(C->begin() != C->end() && "Cannot have an empty SCC!");
267           assert(&C->getOuterRefSCC() == RC &&
268                  "Processing an SCC in a different RefSCC!");
269 
270           LastUpdatedC = UR.UpdatedC;
271           UR.UpdatedRC = nullptr;
272           UR.UpdatedC = nullptr;
273 
274           // Check the PassInstrumentation's BeforePass callbacks before
275           // running the pass, skip its execution completely if asked to
276           // (callback returns false).
277           if (!PI.runBeforePass<LazyCallGraph::SCC>(*Pass, *C))
278             continue;
279 
280           PreservedAnalyses PassPA;
281           {
282             TimeTraceScope TimeScope(Pass->name());
283             PassPA = Pass->run(*C, CGAM, CG, UR);
284           }
285 
286           if (UR.InvalidatedSCCs.count(C))
287             PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA);
288           else
289             PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
290 
291           // Update the SCC and RefSCC if necessary.
292           C = UR.UpdatedC ? UR.UpdatedC : C;
293           RC = UR.UpdatedRC ? UR.UpdatedRC : RC;
294 
295           if (UR.UpdatedC) {
296             // If we're updating the SCC, also update the FAM inside the proxy's
297             // result.
298             CGAM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, CG).updateFAM(
299                 FAM);
300           }
301 
302           // If the CGSCC pass wasn't able to provide a valid updated SCC,
303           // the current SCC may simply need to be skipped if invalid.
304           if (UR.InvalidatedSCCs.count(C)) {
305             LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
306             break;
307           }
308           // Check that we didn't miss any update scenario.
309           assert(C->begin() != C->end() && "Cannot have an empty SCC!");
310 
311           // We handle invalidating the CGSCC analysis manager's information
312           // for the (potentially updated) SCC here. Note that any other SCCs
313           // whose structure has changed should have been invalidated by
314           // whatever was updating the call graph. This SCC gets invalidated
315           // late as it contains the nodes that were actively being
316           // processed.
317           CGAM.invalidate(*C, PassPA);
318 
319           // Then intersect the preserved set so that invalidation of module
320           // analyses will eventually occur when the module pass completes.
321           // Also intersect with the cross-SCC preserved set to capture any
322           // cross-SCC invalidation.
323           UR.CrossSCCPA.intersect(PassPA);
324           PA.intersect(std::move(PassPA));
325 
326           // The pass may have restructured the call graph and refined the
327           // current SCC and/or RefSCC. We need to update our current SCC and
328           // RefSCC pointers to follow these. Also, when the current SCC is
329           // refined, re-run the SCC pass over the newly refined SCC in order
330           // to observe the most precise SCC model available. This inherently
331           // cannot cycle excessively as it only happens when we split SCCs
332           // apart, at most converging on a DAG of single nodes.
333           // FIXME: If we ever start having RefSCC passes, we'll want to
334           // iterate there too.
335           if (UR.UpdatedC)
336             LLVM_DEBUG(dbgs()
337                        << "Re-running SCC passes after a refinement of the "
338                           "current SCC: "
339                        << *UR.UpdatedC << "\n");
340 
341           // Note that both `C` and `RC` may at this point refer to deleted,
342           // invalid SCC and RefSCCs respectively. But we will short circuit
343           // the processing when we check them in the loop above.
344         } while (UR.UpdatedC);
345       } while (!CWorklist.empty());
346 
347       // We only need to keep internal inlined edge information within
348       // a RefSCC, clear it to save on space and let the next time we visit
349       // any of these functions have a fresh start.
350       InlinedInternalEdges.clear();
351     } while (!RCWorklist.empty());
352   }
353 
354   // By definition we preserve the call garph, all SCC analyses, and the
355   // analysis proxies by handling them above and in any nested pass managers.
356   PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
357   PA.preserve<LazyCallGraphAnalysis>();
358   PA.preserve<CGSCCAnalysisManagerModuleProxy>();
359   PA.preserve<FunctionAnalysisManagerModuleProxy>();
360   return PA;
361 }
362 
363 PreservedAnalyses DevirtSCCRepeatedPass::run(LazyCallGraph::SCC &InitialC,
364                                              CGSCCAnalysisManager &AM,
365                                              LazyCallGraph &CG,
366                                              CGSCCUpdateResult &UR) {
367   PreservedAnalyses PA = PreservedAnalyses::all();
368   PassInstrumentation PI =
369       AM.getResult<PassInstrumentationAnalysis>(InitialC, CG);
370 
371   // The SCC may be refined while we are running passes over it, so set up
372   // a pointer that we can update.
373   LazyCallGraph::SCC *C = &InitialC;
374 
375   // Struct to track the counts of direct and indirect calls in each function
376   // of the SCC.
377   struct CallCount {
378     int Direct;
379     int Indirect;
380   };
381 
382   // Put value handles on all of the indirect calls and return the number of
383   // direct calls for each function in the SCC.
384   auto ScanSCC = [](LazyCallGraph::SCC &C,
385                     SmallMapVector<Value *, WeakTrackingVH, 16> &CallHandles) {
386     assert(CallHandles.empty() && "Must start with a clear set of handles.");
387 
388     SmallDenseMap<Function *, CallCount> CallCounts;
389     CallCount CountLocal = {0, 0};
390     for (LazyCallGraph::Node &N : C) {
391       CallCount &Count =
392           CallCounts.insert(std::make_pair(&N.getFunction(), CountLocal))
393               .first->second;
394       for (Instruction &I : instructions(N.getFunction()))
395         if (auto *CB = dyn_cast<CallBase>(&I)) {
396           if (CB->getCalledFunction()) {
397             ++Count.Direct;
398           } else {
399             ++Count.Indirect;
400             CallHandles.insert({CB, WeakTrackingVH(CB)});
401           }
402         }
403     }
404 
405     return CallCounts;
406   };
407 
408   UR.IndirectVHs.clear();
409   // Populate the initial call handles and get the initial call counts.
410   auto CallCounts = ScanSCC(*C, UR.IndirectVHs);
411 
412   for (int Iteration = 0;; ++Iteration) {
413     if (!PI.runBeforePass<LazyCallGraph::SCC>(*Pass, *C))
414       continue;
415 
416     PreservedAnalyses PassPA = Pass->run(*C, AM, CG, UR);
417 
418     if (UR.InvalidatedSCCs.count(C))
419       PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA);
420     else
421       PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
422 
423     // If the SCC structure has changed, bail immediately and let the outer
424     // CGSCC layer handle any iteration to reflect the refined structure.
425     if (UR.UpdatedC && UR.UpdatedC != C) {
426       PA.intersect(std::move(PassPA));
427       break;
428     }
429 
430     // If the CGSCC pass wasn't able to provide a valid updated SCC, the
431     // current SCC may simply need to be skipped if invalid.
432     if (UR.InvalidatedSCCs.count(C)) {
433       LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
434       break;
435     }
436 
437     assert(C->begin() != C->end() && "Cannot have an empty SCC!");
438 
439     // Check whether any of the handles were devirtualized.
440     bool Devirt = llvm::any_of(UR.IndirectVHs, [](auto &P) -> bool {
441       if (P.second) {
442         if (CallBase *CB = dyn_cast<CallBase>(P.second)) {
443           if (CB->getCalledFunction()) {
444             LLVM_DEBUG(dbgs() << "Found devirtualized call: " << *CB << "\n");
445             return true;
446           }
447         }
448       }
449       return false;
450     });
451 
452     // Rescan to build up a new set of handles and count how many direct
453     // calls remain. If we decide to iterate, this also sets up the input to
454     // the next iteration.
455     UR.IndirectVHs.clear();
456     auto NewCallCounts = ScanSCC(*C, UR.IndirectVHs);
457 
458     // If we haven't found an explicit devirtualization already see if we
459     // have decreased the number of indirect calls and increased the number
460     // of direct calls for any function in the SCC. This can be fooled by all
461     // manner of transformations such as DCE and other things, but seems to
462     // work well in practice.
463     if (!Devirt)
464       // Iterate over the keys in NewCallCounts, if Function also exists in
465       // CallCounts, make the check below.
466       for (auto &Pair : NewCallCounts) {
467         auto &CallCountNew = Pair.second;
468         auto CountIt = CallCounts.find(Pair.first);
469         if (CountIt != CallCounts.end()) {
470           const auto &CallCountOld = CountIt->second;
471           if (CallCountOld.Indirect > CallCountNew.Indirect &&
472               CallCountOld.Direct < CallCountNew.Direct) {
473             Devirt = true;
474             break;
475           }
476         }
477       }
478 
479     if (!Devirt) {
480       PA.intersect(std::move(PassPA));
481       break;
482     }
483 
484     // Otherwise, if we've already hit our max, we're done.
485     if (Iteration >= MaxIterations) {
486       if (AbortOnMaxDevirtIterationsReached)
487         report_fatal_error("Max devirtualization iterations reached");
488       LLVM_DEBUG(
489           dbgs() << "Found another devirtualization after hitting the max "
490                     "number of repetitions ("
491                  << MaxIterations << ") on SCC: " << *C << "\n");
492       PA.intersect(std::move(PassPA));
493       break;
494     }
495 
496     LLVM_DEBUG(
497         dbgs() << "Repeating an SCC pass after finding a devirtualization in: "
498                << *C << "\n");
499 
500     // Move over the new call counts in preparation for iterating.
501     CallCounts = std::move(NewCallCounts);
502 
503     // Update the analysis manager with each run and intersect the total set
504     // of preserved analyses so we're ready to iterate.
505     AM.invalidate(*C, PassPA);
506 
507     PA.intersect(std::move(PassPA));
508   }
509 
510   // Note that we don't add any preserved entries here unlike a more normal
511   // "pass manager" because we only handle invalidation *between* iterations,
512   // not after the last iteration.
513   return PA;
514 }
515 
516 PreservedAnalyses CGSCCToFunctionPassAdaptor::run(LazyCallGraph::SCC &C,
517                                                   CGSCCAnalysisManager &AM,
518                                                   LazyCallGraph &CG,
519                                                   CGSCCUpdateResult &UR) {
520   // Setup the function analysis manager from its proxy.
521   FunctionAnalysisManager &FAM =
522       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
523 
524   SmallVector<LazyCallGraph::Node *, 4> Nodes;
525   for (LazyCallGraph::Node &N : C)
526     Nodes.push_back(&N);
527 
528   // The SCC may get split while we are optimizing functions due to deleting
529   // edges. If this happens, the current SCC can shift, so keep track of
530   // a pointer we can overwrite.
531   LazyCallGraph::SCC *CurrentC = &C;
532 
533   LLVM_DEBUG(dbgs() << "Running function passes across an SCC: " << C << "\n");
534 
535   PreservedAnalyses PA = PreservedAnalyses::all();
536   for (LazyCallGraph::Node *N : Nodes) {
537     // Skip nodes from other SCCs. These may have been split out during
538     // processing. We'll eventually visit those SCCs and pick up the nodes
539     // there.
540     if (CG.lookupSCC(*N) != CurrentC)
541       continue;
542 
543     Function &F = N->getFunction();
544 
545     PassInstrumentation PI = FAM.getResult<PassInstrumentationAnalysis>(F);
546     if (!PI.runBeforePass<Function>(*Pass, F))
547       continue;
548 
549     PreservedAnalyses PassPA;
550     {
551       TimeTraceScope TimeScope(Pass->name());
552       PassPA = Pass->run(F, FAM);
553     }
554 
555     PI.runAfterPass<Function>(*Pass, F, PassPA);
556 
557     // We know that the function pass couldn't have invalidated any other
558     // function's analyses (that's the contract of a function pass), so
559     // directly handle the function analysis manager's invalidation here.
560     FAM.invalidate(F, EagerlyInvalidateAnalyses ? PreservedAnalyses::none()
561                                                 : PassPA);
562 
563     // Then intersect the preserved set so that invalidation of module
564     // analyses will eventually occur when the module pass completes.
565     PA.intersect(std::move(PassPA));
566 
567     // If the call graph hasn't been preserved, update it based on this
568     // function pass. This may also update the current SCC to point to
569     // a smaller, more refined SCC.
570     auto PAC = PA.getChecker<LazyCallGraphAnalysis>();
571     if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Module>>()) {
572       CurrentC = &updateCGAndAnalysisManagerForFunctionPass(CG, *CurrentC, *N,
573                                                             AM, UR, FAM);
574       assert(CG.lookupSCC(*N) == CurrentC &&
575              "Current SCC not updated to the SCC containing the current node!");
576     }
577   }
578 
579   // By definition we preserve the proxy. And we preserve all analyses on
580   // Functions. This precludes *any* invalidation of function analyses by the
581   // proxy, but that's OK because we've taken care to invalidate analyses in
582   // the function analysis manager incrementally above.
583   PA.preserveSet<AllAnalysesOn<Function>>();
584   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
585 
586   // We've also ensured that we updated the call graph along the way.
587   PA.preserve<LazyCallGraphAnalysis>();
588 
589   return PA;
590 }
591 
592 bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
593     Module &M, const PreservedAnalyses &PA,
594     ModuleAnalysisManager::Invalidator &Inv) {
595   // If literally everything is preserved, we're done.
596   if (PA.areAllPreserved())
597     return false; // This is still a valid proxy.
598 
599   // If this proxy or the call graph is going to be invalidated, we also need
600   // to clear all the keys coming from that analysis.
601   //
602   // We also directly invalidate the FAM's module proxy if necessary, and if
603   // that proxy isn't preserved we can't preserve this proxy either. We rely on
604   // it to handle module -> function analysis invalidation in the face of
605   // structural changes and so if it's unavailable we conservatively clear the
606   // entire SCC layer as well rather than trying to do invalidation ourselves.
607   auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
608   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
609       Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
610       Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
611     InnerAM->clear();
612 
613     // And the proxy itself should be marked as invalid so that we can observe
614     // the new call graph. This isn't strictly necessary because we cheat
615     // above, but is still useful.
616     return true;
617   }
618 
619   // Directly check if the relevant set is preserved so we can short circuit
620   // invalidating SCCs below.
621   bool AreSCCAnalysesPreserved =
622       PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
623 
624   // Ok, we have a graph, so we can propagate the invalidation down into it.
625   G->buildRefSCCs();
626   for (auto &RC : G->postorder_ref_sccs())
627     for (auto &C : RC) {
628       Optional<PreservedAnalyses> InnerPA;
629 
630       // Check to see whether the preserved set needs to be adjusted based on
631       // module-level analysis invalidation triggering deferred invalidation
632       // for this SCC.
633       if (auto *OuterProxy =
634               InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
635         for (const auto &OuterInvalidationPair :
636              OuterProxy->getOuterInvalidations()) {
637           AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
638           const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
639           if (Inv.invalidate(OuterAnalysisID, M, PA)) {
640             if (!InnerPA)
641               InnerPA = PA;
642             for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
643               InnerPA->abandon(InnerAnalysisID);
644           }
645         }
646 
647       // Check if we needed a custom PA set. If so we'll need to run the inner
648       // invalidation.
649       if (InnerPA) {
650         InnerAM->invalidate(C, *InnerPA);
651         continue;
652       }
653 
654       // Otherwise we only need to do invalidation if the original PA set didn't
655       // preserve all SCC analyses.
656       if (!AreSCCAnalysesPreserved)
657         InnerAM->invalidate(C, PA);
658     }
659 
660   // Return false to indicate that this result is still a valid proxy.
661   return false;
662 }
663 
664 template <>
665 CGSCCAnalysisManagerModuleProxy::Result
666 CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
667   // Force the Function analysis manager to also be available so that it can
668   // be accessed in an SCC analysis and proxied onward to function passes.
669   // FIXME: It is pretty awkward to just drop the result here and assert that
670   // we can find it again later.
671   (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
672 
673   return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
674 }
675 
676 AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
677 
678 FunctionAnalysisManagerCGSCCProxy::Result
679 FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
680                                        CGSCCAnalysisManager &AM,
681                                        LazyCallGraph &CG) {
682   // Note: unconditionally getting checking that the proxy exists may get it at
683   // this point. There are cases when this is being run unnecessarily, but
684   // it is cheap and having the assertion in place is more valuable.
685   auto &MAMProxy = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG);
686   Module &M = *C.begin()->getFunction().getParent();
687   bool ProxyExists =
688       MAMProxy.cachedResultExists<FunctionAnalysisManagerModuleProxy>(M);
689   assert(ProxyExists &&
690          "The CGSCC pass manager requires that the FAM module proxy is run "
691          "on the module prior to entering the CGSCC walk");
692   (void)ProxyExists;
693 
694   // We just return an empty result. The caller will use the updateFAM interface
695   // to correctly register the relevant FunctionAnalysisManager based on the
696   // context in which this proxy is run.
697   return Result();
698 }
699 
700 bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
701     LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
702     CGSCCAnalysisManager::Invalidator &Inv) {
703   // If literally everything is preserved, we're done.
704   if (PA.areAllPreserved())
705     return false; // This is still a valid proxy.
706 
707   // All updates to preserve valid results are done below, so we don't need to
708   // invalidate this proxy.
709   //
710   // Note that in order to preserve this proxy, a module pass must ensure that
711   // the FAM has been completely updated to handle the deletion of functions.
712   // Specifically, any FAM-cached results for those functions need to have been
713   // forcibly cleared. When preserved, this proxy will only invalidate results
714   // cached on functions *still in the module* at the end of the module pass.
715   auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
716   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
717     for (LazyCallGraph::Node &N : C)
718       FAM->invalidate(N.getFunction(), PA);
719 
720     return false;
721   }
722 
723   // Directly check if the relevant set is preserved.
724   bool AreFunctionAnalysesPreserved =
725       PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
726 
727   // Now walk all the functions to see if any inner analysis invalidation is
728   // necessary.
729   for (LazyCallGraph::Node &N : C) {
730     Function &F = N.getFunction();
731     Optional<PreservedAnalyses> FunctionPA;
732 
733     // Check to see whether the preserved set needs to be pruned based on
734     // SCC-level analysis invalidation that triggers deferred invalidation
735     // registered with the outer analysis manager proxy for this function.
736     if (auto *OuterProxy =
737             FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
738       for (const auto &OuterInvalidationPair :
739            OuterProxy->getOuterInvalidations()) {
740         AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
741         const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
742         if (Inv.invalidate(OuterAnalysisID, C, PA)) {
743           if (!FunctionPA)
744             FunctionPA = PA;
745           for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
746             FunctionPA->abandon(InnerAnalysisID);
747         }
748       }
749 
750     // Check if we needed a custom PA set, and if so we'll need to run the
751     // inner invalidation.
752     if (FunctionPA) {
753       FAM->invalidate(F, *FunctionPA);
754       continue;
755     }
756 
757     // Otherwise we only need to do invalidation if the original PA set didn't
758     // preserve all function analyses.
759     if (!AreFunctionAnalysesPreserved)
760       FAM->invalidate(F, PA);
761   }
762 
763   // Return false to indicate that this result is still a valid proxy.
764   return false;
765 }
766 
767 } // end namespace llvm
768 
769 /// When a new SCC is created for the graph we first update the
770 /// FunctionAnalysisManager in the Proxy's result.
771 /// As there might be function analysis results cached for the functions now in
772 /// that SCC, two forms of  updates are required.
773 ///
774 /// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
775 /// created so that any subsequent invalidation events to the SCC are
776 /// propagated to the function analysis results cached for functions within it.
777 ///
778 /// Second, if any of the functions within the SCC have analysis results with
779 /// outer analysis dependencies, then those dependencies would point to the
780 /// *wrong* SCC's analysis result. We forcibly invalidate the necessary
781 /// function analyses so that they don't retain stale handles.
782 static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
783                                          LazyCallGraph &G,
784                                          CGSCCAnalysisManager &AM,
785                                          FunctionAnalysisManager &FAM) {
786   AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).updateFAM(FAM);
787 
788   // Now walk the functions in this SCC and invalidate any function analysis
789   // results that might have outer dependencies on an SCC analysis.
790   for (LazyCallGraph::Node &N : C) {
791     Function &F = N.getFunction();
792 
793     auto *OuterProxy =
794         FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
795     if (!OuterProxy)
796       // No outer analyses were queried, nothing to do.
797       continue;
798 
799     // Forcibly abandon all the inner analyses with dependencies, but
800     // invalidate nothing else.
801     auto PA = PreservedAnalyses::all();
802     for (const auto &OuterInvalidationPair :
803          OuterProxy->getOuterInvalidations()) {
804       const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
805       for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
806         PA.abandon(InnerAnalysisID);
807     }
808 
809     // Now invalidate anything we found.
810     FAM.invalidate(F, PA);
811   }
812 }
813 
814 /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
815 /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
816 /// added SCCs.
817 ///
818 /// The range of new SCCs must be in postorder already. The SCC they were split
819 /// out of must be provided as \p C. The current node being mutated and
820 /// triggering updates must be passed as \p N.
821 ///
822 /// This function returns the SCC containing \p N. This will be either \p C if
823 /// no new SCCs have been split out, or it will be the new SCC containing \p N.
824 template <typename SCCRangeT>
825 static LazyCallGraph::SCC *
826 incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
827                        LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
828                        CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
829   using SCC = LazyCallGraph::SCC;
830 
831   if (NewSCCRange.empty())
832     return C;
833 
834   // Add the current SCC to the worklist as its shape has changed.
835   UR.CWorklist.insert(C);
836   LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
837                     << "\n");
838 
839   SCC *OldC = C;
840 
841   // Update the current SCC. Note that if we have new SCCs, this must actually
842   // change the SCC.
843   assert(C != &*NewSCCRange.begin() &&
844          "Cannot insert new SCCs without changing current SCC!");
845   C = &*NewSCCRange.begin();
846   assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
847 
848   // If we had a cached FAM proxy originally, we will want to create more of
849   // them for each SCC that was split off.
850   FunctionAnalysisManager *FAM = nullptr;
851   if (auto *FAMProxy =
852           AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC))
853     FAM = &FAMProxy->getManager();
854 
855   // We need to propagate an invalidation call to all but the newly current SCC
856   // because the outer pass manager won't do that for us after splitting them.
857   // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
858   // there are preserved analysis we can avoid invalidating them here for
859   // split-off SCCs.
860   // We know however that this will preserve any FAM proxy so go ahead and mark
861   // that.
862   PreservedAnalyses PA;
863   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
864   AM.invalidate(*OldC, PA);
865 
866   // Ensure the now-current SCC's function analyses are updated.
867   if (FAM)
868     updateNewSCCFunctionAnalyses(*C, G, AM, *FAM);
869 
870   for (SCC &NewC : llvm::reverse(llvm::drop_begin(NewSCCRange))) {
871     assert(C != &NewC && "No need to re-visit the current SCC!");
872     assert(OldC != &NewC && "Already handled the original SCC!");
873     UR.CWorklist.insert(&NewC);
874     LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
875 
876     // Ensure new SCCs' function analyses are updated.
877     if (FAM)
878       updateNewSCCFunctionAnalyses(NewC, G, AM, *FAM);
879 
880     // Also propagate a normal invalidation to the new SCC as only the current
881     // will get one from the pass manager infrastructure.
882     AM.invalidate(NewC, PA);
883   }
884   return C;
885 }
886 
887 static LazyCallGraph::SCC &updateCGAndAnalysisManagerForPass(
888     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
889     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
890     FunctionAnalysisManager &FAM, bool FunctionPass) {
891   using Node = LazyCallGraph::Node;
892   using Edge = LazyCallGraph::Edge;
893   using SCC = LazyCallGraph::SCC;
894   using RefSCC = LazyCallGraph::RefSCC;
895 
896   RefSCC &InitialRC = InitialC.getOuterRefSCC();
897   SCC *C = &InitialC;
898   RefSCC *RC = &InitialRC;
899   Function &F = N.getFunction();
900 
901   // Walk the function body and build up the set of retained, promoted, and
902   // demoted edges.
903   SmallVector<Constant *, 16> Worklist;
904   SmallPtrSet<Constant *, 16> Visited;
905   SmallPtrSet<Node *, 16> RetainedEdges;
906   SmallSetVector<Node *, 4> PromotedRefTargets;
907   SmallSetVector<Node *, 4> DemotedCallTargets;
908   SmallSetVector<Node *, 4> NewCallEdges;
909   SmallSetVector<Node *, 4> NewRefEdges;
910 
911   // First walk the function and handle all called functions. We do this first
912   // because if there is a single call edge, whether there are ref edges is
913   // irrelevant.
914   for (Instruction &I : instructions(F)) {
915     if (auto *CB = dyn_cast<CallBase>(&I)) {
916       if (Function *Callee = CB->getCalledFunction()) {
917         if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
918           Node *CalleeN = G.lookup(*Callee);
919           assert(CalleeN &&
920                  "Visited function should already have an associated node");
921           Edge *E = N->lookup(*CalleeN);
922           assert((E || !FunctionPass) &&
923                  "No function transformations should introduce *new* "
924                  "call edges! Any new calls should be modeled as "
925                  "promoted existing ref edges!");
926           bool Inserted = RetainedEdges.insert(CalleeN).second;
927           (void)Inserted;
928           assert(Inserted && "We should never visit a function twice.");
929           if (!E)
930             NewCallEdges.insert(CalleeN);
931           else if (!E->isCall())
932             PromotedRefTargets.insert(CalleeN);
933         }
934       } else {
935         // We can miss devirtualization if an indirect call is created then
936         // promoted before updateCGAndAnalysisManagerForPass runs.
937         auto *Entry = UR.IndirectVHs.find(CB);
938         if (Entry == UR.IndirectVHs.end())
939           UR.IndirectVHs.insert({CB, WeakTrackingVH(CB)});
940         else if (!Entry->second)
941           Entry->second = WeakTrackingVH(CB);
942       }
943     }
944   }
945 
946   // Now walk all references.
947   for (Instruction &I : instructions(F))
948     for (Value *Op : I.operand_values())
949       if (auto *OpC = dyn_cast<Constant>(Op))
950         if (Visited.insert(OpC).second)
951           Worklist.push_back(OpC);
952 
953   auto VisitRef = [&](Function &Referee) {
954     Node *RefereeN = G.lookup(Referee);
955     assert(RefereeN &&
956            "Visited function should already have an associated node");
957     Edge *E = N->lookup(*RefereeN);
958     assert((E || !FunctionPass) &&
959            "No function transformations should introduce *new* ref "
960            "edges! Any new ref edges would require IPO which "
961            "function passes aren't allowed to do!");
962     bool Inserted = RetainedEdges.insert(RefereeN).second;
963     (void)Inserted;
964     assert(Inserted && "We should never visit a function twice.");
965     if (!E)
966       NewRefEdges.insert(RefereeN);
967     else if (E->isCall())
968       DemotedCallTargets.insert(RefereeN);
969   };
970   LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
971 
972   // Handle new ref edges.
973   for (Node *RefTarget : NewRefEdges) {
974     SCC &TargetC = *G.lookupSCC(*RefTarget);
975     RefSCC &TargetRC = TargetC.getOuterRefSCC();
976     (void)TargetRC;
977     // TODO: This only allows trivial edges to be added for now.
978 #ifdef EXPENSIVE_CHECKS
979     assert((RC == &TargetRC ||
980            RC->isAncestorOf(TargetRC)) && "New ref edge is not trivial!");
981 #endif
982     RC->insertTrivialRefEdge(N, *RefTarget);
983   }
984 
985   // Handle new call edges.
986   for (Node *CallTarget : NewCallEdges) {
987     SCC &TargetC = *G.lookupSCC(*CallTarget);
988     RefSCC &TargetRC = TargetC.getOuterRefSCC();
989     (void)TargetRC;
990     // TODO: This only allows trivial edges to be added for now.
991 #ifdef EXPENSIVE_CHECKS
992     assert((RC == &TargetRC ||
993            RC->isAncestorOf(TargetRC)) && "New call edge is not trivial!");
994 #endif
995     // Add a trivial ref edge to be promoted later on alongside
996     // PromotedRefTargets.
997     RC->insertTrivialRefEdge(N, *CallTarget);
998   }
999 
1000   // Include synthetic reference edges to known, defined lib functions.
1001   for (auto *LibFn : G.getLibFunctions())
1002     // While the list of lib functions doesn't have repeats, don't re-visit
1003     // anything handled above.
1004     if (!Visited.count(LibFn))
1005       VisitRef(*LibFn);
1006 
1007   // First remove all of the edges that are no longer present in this function.
1008   // The first step makes these edges uniformly ref edges and accumulates them
1009   // into a separate data structure so removal doesn't invalidate anything.
1010   SmallVector<Node *, 4> DeadTargets;
1011   for (Edge &E : *N) {
1012     if (RetainedEdges.count(&E.getNode()))
1013       continue;
1014 
1015     SCC &TargetC = *G.lookupSCC(E.getNode());
1016     RefSCC &TargetRC = TargetC.getOuterRefSCC();
1017     if (&TargetRC == RC && E.isCall()) {
1018       if (C != &TargetC) {
1019         // For separate SCCs this is trivial.
1020         RC->switchTrivialInternalEdgeToRef(N, E.getNode());
1021       } else {
1022         // Now update the call graph.
1023         C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
1024                                    G, N, C, AM, UR);
1025       }
1026     }
1027 
1028     // Now that this is ready for actual removal, put it into our list.
1029     DeadTargets.push_back(&E.getNode());
1030   }
1031   // Remove the easy cases quickly and actually pull them out of our list.
1032   llvm::erase_if(DeadTargets, [&](Node *TargetN) {
1033     SCC &TargetC = *G.lookupSCC(*TargetN);
1034     RefSCC &TargetRC = TargetC.getOuterRefSCC();
1035 
1036     // We can't trivially remove internal targets, so skip
1037     // those.
1038     if (&TargetRC == RC)
1039       return false;
1040 
1041     LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '" << N << "' to '"
1042                       << *TargetN << "'\n");
1043     RC->removeOutgoingEdge(N, *TargetN);
1044     return true;
1045   });
1046 
1047   // Now do a batch removal of the internal ref edges left.
1048   auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets);
1049   if (!NewRefSCCs.empty()) {
1050     // The old RefSCC is dead, mark it as such.
1051     UR.InvalidatedRefSCCs.insert(RC);
1052 
1053     // Note that we don't bother to invalidate analyses as ref-edge
1054     // connectivity is not really observable in any way and is intended
1055     // exclusively to be used for ordering of transforms rather than for
1056     // analysis conclusions.
1057 
1058     // Update RC to the "bottom".
1059     assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
1060     RC = &C->getOuterRefSCC();
1061     assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
1062 
1063     // The RC worklist is in reverse postorder, so we enqueue the new ones in
1064     // RPO except for the one which contains the source node as that is the
1065     // "bottom" we will continue processing in the bottom-up walk.
1066     assert(NewRefSCCs.front() == RC &&
1067            "New current RefSCC not first in the returned list!");
1068     for (RefSCC *NewRC : llvm::reverse(llvm::drop_begin(NewRefSCCs))) {
1069       assert(NewRC != RC && "Should not encounter the current RefSCC further "
1070                             "in the postorder list of new RefSCCs.");
1071       UR.RCWorklist.insert(NewRC);
1072       LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "
1073                         << *NewRC << "\n");
1074     }
1075   }
1076 
1077   // Next demote all the call edges that are now ref edges. This helps make
1078   // the SCCs small which should minimize the work below as we don't want to
1079   // form cycles that this would break.
1080   for (Node *RefTarget : DemotedCallTargets) {
1081     SCC &TargetC = *G.lookupSCC(*RefTarget);
1082     RefSCC &TargetRC = TargetC.getOuterRefSCC();
1083 
1084     // The easy case is when the target RefSCC is not this RefSCC. This is
1085     // only supported when the target RefSCC is a child of this RefSCC.
1086     if (&TargetRC != RC) {
1087 #ifdef EXPENSIVE_CHECKS
1088       assert(RC->isAncestorOf(TargetRC) &&
1089              "Cannot potentially form RefSCC cycles here!");
1090 #endif
1091       RC->switchOutgoingEdgeToRef(N, *RefTarget);
1092       LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
1093                         << "' to '" << *RefTarget << "'\n");
1094       continue;
1095     }
1096 
1097     // We are switching an internal call edge to a ref edge. This may split up
1098     // some SCCs.
1099     if (C != &TargetC) {
1100       // For separate SCCs this is trivial.
1101       RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
1102       continue;
1103     }
1104 
1105     // Now update the call graph.
1106     C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
1107                                C, AM, UR);
1108   }
1109 
1110   // We added a ref edge earlier for new call edges, promote those to call edges
1111   // alongside PromotedRefTargets.
1112   for (Node *E : NewCallEdges)
1113     PromotedRefTargets.insert(E);
1114 
1115   // Now promote ref edges into call edges.
1116   for (Node *CallTarget : PromotedRefTargets) {
1117     SCC &TargetC = *G.lookupSCC(*CallTarget);
1118     RefSCC &TargetRC = TargetC.getOuterRefSCC();
1119 
1120     // The easy case is when the target RefSCC is not this RefSCC. This is
1121     // only supported when the target RefSCC is a child of this RefSCC.
1122     if (&TargetRC != RC) {
1123 #ifdef EXPENSIVE_CHECKS
1124       assert(RC->isAncestorOf(TargetRC) &&
1125              "Cannot potentially form RefSCC cycles here!");
1126 #endif
1127       RC->switchOutgoingEdgeToCall(N, *CallTarget);
1128       LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
1129                         << "' to '" << *CallTarget << "'\n");
1130       continue;
1131     }
1132     LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
1133                       << N << "' to '" << *CallTarget << "'\n");
1134 
1135     // Otherwise we are switching an internal ref edge to a call edge. This
1136     // may merge away some SCCs, and we add those to the UpdateResult. We also
1137     // need to make sure to update the worklist in the event SCCs have moved
1138     // before the current one in the post-order sequence
1139     bool HasFunctionAnalysisProxy = false;
1140     auto InitialSCCIndex = RC->find(*C) - RC->begin();
1141     bool FormedCycle = RC->switchInternalEdgeToCall(
1142         N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
1143           for (SCC *MergedC : MergedSCCs) {
1144             assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
1145 
1146             HasFunctionAnalysisProxy |=
1147                 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
1148                     *MergedC) != nullptr;
1149 
1150             // Mark that this SCC will no longer be valid.
1151             UR.InvalidatedSCCs.insert(MergedC);
1152 
1153             // FIXME: We should really do a 'clear' here to forcibly release
1154             // memory, but we don't have a good way of doing that and
1155             // preserving the function analyses.
1156             auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1157             PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1158             AM.invalidate(*MergedC, PA);
1159           }
1160         });
1161 
1162     // If we formed a cycle by creating this call, we need to update more data
1163     // structures.
1164     if (FormedCycle) {
1165       C = &TargetC;
1166       assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
1167 
1168       // If one of the invalidated SCCs had a cached proxy to a function
1169       // analysis manager, we need to create a proxy in the new current SCC as
1170       // the invalidated SCCs had their functions moved.
1171       if (HasFunctionAnalysisProxy)
1172         AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G).updateFAM(FAM);
1173 
1174       // Any analyses cached for this SCC are no longer precise as the shape
1175       // has changed by introducing this cycle. However, we have taken care to
1176       // update the proxies so it remains valide.
1177       auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1178       PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1179       AM.invalidate(*C, PA);
1180     }
1181     auto NewSCCIndex = RC->find(*C) - RC->begin();
1182     // If we have actually moved an SCC to be topologically "below" the current
1183     // one due to merging, we will need to revisit the current SCC after
1184     // visiting those moved SCCs.
1185     //
1186     // It is critical that we *do not* revisit the current SCC unless we
1187     // actually move SCCs in the process of merging because otherwise we may
1188     // form a cycle where an SCC is split apart, merged, split, merged and so
1189     // on infinitely.
1190     if (InitialSCCIndex < NewSCCIndex) {
1191       // Put our current SCC back onto the worklist as we'll visit other SCCs
1192       // that are now definitively ordered prior to the current one in the
1193       // post-order sequence, and may end up observing more precise context to
1194       // optimize the current SCC.
1195       UR.CWorklist.insert(C);
1196       LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
1197                         << "\n");
1198       // Enqueue in reverse order as we pop off the back of the worklist.
1199       for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
1200                                                   RC->begin() + NewSCCIndex))) {
1201         UR.CWorklist.insert(&MovedC);
1202         LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
1203                           << MovedC << "\n");
1204       }
1205     }
1206   }
1207 
1208   assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
1209   assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
1210   assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
1211 
1212   // Record the current RefSCC and SCC for higher layers of the CGSCC pass
1213   // manager now that all the updates have been applied.
1214   if (RC != &InitialRC)
1215     UR.UpdatedRC = RC;
1216   if (C != &InitialC)
1217     UR.UpdatedC = C;
1218 
1219   return *C;
1220 }
1221 
1222 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
1223     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
1224     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1225     FunctionAnalysisManager &FAM) {
1226   return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1227                                            /* FunctionPass */ true);
1228 }
1229 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForCGSCCPass(
1230     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
1231     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1232     FunctionAnalysisManager &FAM) {
1233   return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1234                                            /* FunctionPass */ false);
1235 }
1236