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/Support/Casting.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/TimeProfiler.h"
27 #include <algorithm>
28 #include <cassert>
29 #include <iterator>
30 
31 #define DEBUG_TYPE "cgscc"
32 
33 using namespace llvm;
34 
35 // Explicit template instantiations and specialization definitions for core
36 // template typedefs.
37 namespace llvm {
38 
39 // Explicit instantiations for the core proxy templates.
40 template class AllAnalysesOn<LazyCallGraph::SCC>;
41 template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
42 template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
43                            LazyCallGraph &, CGSCCUpdateResult &>;
44 template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
45 template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
46                                          LazyCallGraph::SCC, LazyCallGraph &>;
47 template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
48 
49 /// Explicitly specialize the pass manager run method to handle call graph
50 /// updates.
51 template <>
52 PreservedAnalyses
53 PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
54             CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
55                                       CGSCCAnalysisManager &AM,
56                                       LazyCallGraph &G, CGSCCUpdateResult &UR) {
57   // Request PassInstrumentation from analysis manager, will use it to run
58   // instrumenting callbacks for the passes later.
59   PassInstrumentation PI =
60       AM.getResult<PassInstrumentationAnalysis>(InitialC, G);
61 
62   PreservedAnalyses PA = PreservedAnalyses::all();
63 
64   if (DebugLogging)
65     dbgs() << "Starting CGSCC pass manager run.\n";
66 
67   // The SCC may be refined while we are running passes over it, so set up
68   // a pointer that we can update.
69   LazyCallGraph::SCC *C = &InitialC;
70 
71   // Get Function analysis manager from its proxy.
72   FunctionAnalysisManager &FAM =
73       AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*C)->getManager();
74 
75   for (auto &Pass : Passes) {
76     // Check the PassInstrumentation's BeforePass callbacks before running the
77     // pass, skip its execution completely if asked to (callback returns false).
78     if (!PI.runBeforePass(*Pass, *C))
79       continue;
80 
81     PreservedAnalyses PassPA;
82     {
83       TimeTraceScope TimeScope(Pass->name());
84       PassPA = Pass->run(*C, AM, G, UR);
85     }
86 
87     if (UR.InvalidatedSCCs.count(C))
88       PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA);
89     else
90       PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
91 
92     // Update the SCC if necessary.
93     C = UR.UpdatedC ? UR.UpdatedC : C;
94     if (UR.UpdatedC) {
95       // If C is updated, also create a proxy and update FAM inside the result.
96       auto *ResultFAMCP =
97           &AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
98       ResultFAMCP->updateFAM(FAM);
99     }
100 
101     // If the CGSCC pass wasn't able to provide a valid updated SCC, the
102     // current SCC may simply need to be skipped if invalid.
103     if (UR.InvalidatedSCCs.count(C)) {
104       LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
105       break;
106     }
107     // Check that we didn't miss any update scenario.
108     assert(C->begin() != C->end() && "Cannot have an empty SCC!");
109 
110     // Update the analysis manager as each pass runs and potentially
111     // invalidates analyses.
112     AM.invalidate(*C, PassPA);
113 
114     // Finally, we intersect the final preserved analyses to compute the
115     // aggregate preserved set for this pass manager.
116     PA.intersect(std::move(PassPA));
117 
118     // FIXME: Historically, the pass managers all called the LLVM context's
119     // yield function here. We don't have a generic way to acquire the
120     // context and it isn't yet clear what the right pattern is for yielding
121     // in the new pass manager so it is currently omitted.
122     // ...getContext().yield();
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   if (DebugLogging)
138     dbgs() << "Finished CGSCC pass manager run.\n";
139 
140   return PA;
141 }
142 
143 bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
144     Module &M, const PreservedAnalyses &PA,
145     ModuleAnalysisManager::Invalidator &Inv) {
146   // If literally everything is preserved, we're done.
147   if (PA.areAllPreserved())
148     return false; // This is still a valid proxy.
149 
150   // If this proxy or the call graph is going to be invalidated, we also need
151   // to clear all the keys coming from that analysis.
152   //
153   // We also directly invalidate the FAM's module proxy if necessary, and if
154   // that proxy isn't preserved we can't preserve this proxy either. We rely on
155   // it to handle module -> function analysis invalidation in the face of
156   // structural changes and so if it's unavailable we conservatively clear the
157   // entire SCC layer as well rather than trying to do invalidation ourselves.
158   auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
159   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
160       Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
161       Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
162     InnerAM->clear();
163 
164     // And the proxy itself should be marked as invalid so that we can observe
165     // the new call graph. This isn't strictly necessary because we cheat
166     // above, but is still useful.
167     return true;
168   }
169 
170   // Directly check if the relevant set is preserved so we can short circuit
171   // invalidating SCCs below.
172   bool AreSCCAnalysesPreserved =
173       PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
174 
175   // Ok, we have a graph, so we can propagate the invalidation down into it.
176   G->buildRefSCCs();
177   for (auto &RC : G->postorder_ref_sccs())
178     for (auto &C : RC) {
179       Optional<PreservedAnalyses> InnerPA;
180 
181       // Check to see whether the preserved set needs to be adjusted based on
182       // module-level analysis invalidation triggering deferred invalidation
183       // for this SCC.
184       if (auto *OuterProxy =
185               InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
186         for (const auto &OuterInvalidationPair :
187              OuterProxy->getOuterInvalidations()) {
188           AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
189           const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
190           if (Inv.invalidate(OuterAnalysisID, M, PA)) {
191             if (!InnerPA)
192               InnerPA = PA;
193             for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
194               InnerPA->abandon(InnerAnalysisID);
195           }
196         }
197 
198       // Check if we needed a custom PA set. If so we'll need to run the inner
199       // invalidation.
200       if (InnerPA) {
201         InnerAM->invalidate(C, *InnerPA);
202         continue;
203       }
204 
205       // Otherwise we only need to do invalidation if the original PA set didn't
206       // preserve all SCC analyses.
207       if (!AreSCCAnalysesPreserved)
208         InnerAM->invalidate(C, PA);
209     }
210 
211   // Return false to indicate that this result is still a valid proxy.
212   return false;
213 }
214 
215 template <>
216 CGSCCAnalysisManagerModuleProxy::Result
217 CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
218   // Force the Function analysis manager to also be available so that it can
219   // be accessed in an SCC analysis and proxied onward to function passes.
220   // FIXME: It is pretty awkward to just drop the result here and assert that
221   // we can find it again later.
222   (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
223 
224   return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
225 }
226 
227 AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
228 
229 FunctionAnalysisManagerCGSCCProxy::Result
230 FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
231                                        CGSCCAnalysisManager &AM,
232                                        LazyCallGraph &CG) {
233   // Note: unconditionally getting checking that the proxy exists may get it at
234   // this point. There are cases when this is being run unnecessarily, but
235   // it is cheap and having the assertion in place is more valuable.
236   auto &MAMProxy = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG);
237   Module &M = *C.begin()->getFunction().getParent();
238   bool ProxyExists =
239       MAMProxy.cachedResultExists<FunctionAnalysisManagerModuleProxy>(M);
240   assert(ProxyExists &&
241          "The CGSCC pass manager requires that the FAM module proxy is run "
242          "on the module prior to entering the CGSCC walk");
243   (void)ProxyExists;
244 
245   // We just return an empty result. The caller will use the updateFAM interface
246   // to correctly register the relevant FunctionAnalysisManager based on the
247   // context in which this proxy is run.
248   return Result();
249 }
250 
251 bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
252     LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
253     CGSCCAnalysisManager::Invalidator &Inv) {
254   // If literally everything is preserved, we're done.
255   if (PA.areAllPreserved())
256     return false; // This is still a valid proxy.
257 
258   // All updates to preserve valid results are done below, so we don't need to
259   // invalidate this proxy.
260   //
261   // Note that in order to preserve this proxy, a module pass must ensure that
262   // the FAM has been completely updated to handle the deletion of functions.
263   // Specifically, any FAM-cached results for those functions need to have been
264   // forcibly cleared. When preserved, this proxy will only invalidate results
265   // cached on functions *still in the module* at the end of the module pass.
266   auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
267   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
268     for (LazyCallGraph::Node &N : C)
269       FAM->clear(N.getFunction(), N.getFunction().getName());
270 
271     return false;
272   }
273 
274   // Directly check if the relevant set is preserved.
275   bool AreFunctionAnalysesPreserved =
276       PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
277 
278   // Now walk all the functions to see if any inner analysis invalidation is
279   // necessary.
280   for (LazyCallGraph::Node &N : C) {
281     Function &F = N.getFunction();
282     Optional<PreservedAnalyses> FunctionPA;
283 
284     // Check to see whether the preserved set needs to be pruned based on
285     // SCC-level analysis invalidation that triggers deferred invalidation
286     // registered with the outer analysis manager proxy for this function.
287     if (auto *OuterProxy =
288             FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
289       for (const auto &OuterInvalidationPair :
290            OuterProxy->getOuterInvalidations()) {
291         AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
292         const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
293         if (Inv.invalidate(OuterAnalysisID, C, PA)) {
294           if (!FunctionPA)
295             FunctionPA = PA;
296           for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
297             FunctionPA->abandon(InnerAnalysisID);
298         }
299       }
300 
301     // Check if we needed a custom PA set, and if so we'll need to run the
302     // inner invalidation.
303     if (FunctionPA) {
304       FAM->invalidate(F, *FunctionPA);
305       continue;
306     }
307 
308     // Otherwise we only need to do invalidation if the original PA set didn't
309     // preserve all function analyses.
310     if (!AreFunctionAnalysesPreserved)
311       FAM->invalidate(F, PA);
312   }
313 
314   // Return false to indicate that this result is still a valid proxy.
315   return false;
316 }
317 
318 } // end namespace llvm
319 
320 /// When a new SCC is created for the graph we first update the
321 /// FunctionAnalysisManager in the Proxy's result.
322 /// As there might be function analysis results cached for the functions now in
323 /// that SCC, two forms of  updates are required.
324 ///
325 /// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
326 /// created so that any subsequent invalidation events to the SCC are
327 /// propagated to the function analysis results cached for functions within it.
328 ///
329 /// Second, if any of the functions within the SCC have analysis results with
330 /// outer analysis dependencies, then those dependencies would point to the
331 /// *wrong* SCC's analysis result. We forcibly invalidate the necessary
332 /// function analyses so that they don't retain stale handles.
333 static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
334                                          LazyCallGraph &G,
335                                          CGSCCAnalysisManager &AM,
336                                          FunctionAnalysisManager &FAM) {
337   AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).updateFAM(FAM);
338 
339   // Now walk the functions in this SCC and invalidate any function analysis
340   // results that might have outer dependencies on an SCC analysis.
341   for (LazyCallGraph::Node &N : C) {
342     Function &F = N.getFunction();
343 
344     auto *OuterProxy =
345         FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
346     if (!OuterProxy)
347       // No outer analyses were queried, nothing to do.
348       continue;
349 
350     // Forcibly abandon all the inner analyses with dependencies, but
351     // invalidate nothing else.
352     auto PA = PreservedAnalyses::all();
353     for (const auto &OuterInvalidationPair :
354          OuterProxy->getOuterInvalidations()) {
355       const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
356       for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
357         PA.abandon(InnerAnalysisID);
358     }
359 
360     // Now invalidate anything we found.
361     FAM.invalidate(F, PA);
362   }
363 }
364 
365 /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
366 /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
367 /// added SCCs.
368 ///
369 /// The range of new SCCs must be in postorder already. The SCC they were split
370 /// out of must be provided as \p C. The current node being mutated and
371 /// triggering updates must be passed as \p N.
372 ///
373 /// This function returns the SCC containing \p N. This will be either \p C if
374 /// no new SCCs have been split out, or it will be the new SCC containing \p N.
375 template <typename SCCRangeT>
376 static LazyCallGraph::SCC *
377 incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
378                        LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
379                        CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
380   using SCC = LazyCallGraph::SCC;
381 
382   if (NewSCCRange.begin() == NewSCCRange.end())
383     return C;
384 
385   // Add the current SCC to the worklist as its shape has changed.
386   UR.CWorklist.insert(C);
387   LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
388                     << "\n");
389 
390   SCC *OldC = C;
391 
392   // Update the current SCC. Note that if we have new SCCs, this must actually
393   // change the SCC.
394   assert(C != &*NewSCCRange.begin() &&
395          "Cannot insert new SCCs without changing current SCC!");
396   C = &*NewSCCRange.begin();
397   assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
398 
399   // If we had a cached FAM proxy originally, we will want to create more of
400   // them for each SCC that was split off.
401   FunctionAnalysisManager *FAM = nullptr;
402   if (auto *FAMProxy =
403           AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC))
404     FAM = &FAMProxy->getManager();
405 
406   // We need to propagate an invalidation call to all but the newly current SCC
407   // because the outer pass manager won't do that for us after splitting them.
408   // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
409   // there are preserved analysis we can avoid invalidating them here for
410   // split-off SCCs.
411   // We know however that this will preserve any FAM proxy so go ahead and mark
412   // that.
413   PreservedAnalyses PA;
414   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
415   AM.invalidate(*OldC, PA);
416 
417   // Ensure the now-current SCC's function analyses are updated.
418   if (FAM)
419     updateNewSCCFunctionAnalyses(*C, G, AM, *FAM);
420 
421   for (SCC &NewC : llvm::reverse(make_range(std::next(NewSCCRange.begin()),
422                                             NewSCCRange.end()))) {
423     assert(C != &NewC && "No need to re-visit the current SCC!");
424     assert(OldC != &NewC && "Already handled the original SCC!");
425     UR.CWorklist.insert(&NewC);
426     LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
427 
428     // Ensure new SCCs' function analyses are updated.
429     if (FAM)
430       updateNewSCCFunctionAnalyses(NewC, G, AM, *FAM);
431 
432     // Also propagate a normal invalidation to the new SCC as only the current
433     // will get one from the pass manager infrastructure.
434     AM.invalidate(NewC, PA);
435   }
436   return C;
437 }
438 
439 static LazyCallGraph::SCC &updateCGAndAnalysisManagerForPass(
440     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
441     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
442     FunctionAnalysisManager &FAM, bool FunctionPass) {
443   using Node = LazyCallGraph::Node;
444   using Edge = LazyCallGraph::Edge;
445   using SCC = LazyCallGraph::SCC;
446   using RefSCC = LazyCallGraph::RefSCC;
447 
448   RefSCC &InitialRC = InitialC.getOuterRefSCC();
449   SCC *C = &InitialC;
450   RefSCC *RC = &InitialRC;
451   Function &F = N.getFunction();
452 
453   // Walk the function body and build up the set of retained, promoted, and
454   // demoted edges.
455   SmallVector<Constant *, 16> Worklist;
456   SmallPtrSet<Constant *, 16> Visited;
457   SmallPtrSet<Node *, 16> RetainedEdges;
458   SmallSetVector<Node *, 4> PromotedRefTargets;
459   SmallSetVector<Node *, 4> DemotedCallTargets;
460   SmallSetVector<Node *, 4> NewCallEdges;
461   SmallSetVector<Node *, 4> NewRefEdges;
462 
463   // First walk the function and handle all called functions. We do this first
464   // because if there is a single call edge, whether there are ref edges is
465   // irrelevant.
466   for (Instruction &I : instructions(F))
467     if (auto *CB = dyn_cast<CallBase>(&I))
468       if (Function *Callee = CB->getCalledFunction())
469         if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
470           Node &CalleeN = *G.lookup(*Callee);
471           Edge *E = N->lookup(CalleeN);
472           assert((E || !FunctionPass) &&
473                  "No function transformations should introduce *new* "
474                  "call edges! Any new calls should be modeled as "
475                  "promoted existing ref edges!");
476           bool Inserted = RetainedEdges.insert(&CalleeN).second;
477           (void)Inserted;
478           assert(Inserted && "We should never visit a function twice.");
479           if (!E)
480             NewCallEdges.insert(&CalleeN);
481           else if (!E->isCall())
482             PromotedRefTargets.insert(&CalleeN);
483         }
484 
485   // Now walk all references.
486   for (Instruction &I : instructions(F))
487     for (Value *Op : I.operand_values())
488       if (auto *C = dyn_cast<Constant>(Op))
489         if (Visited.insert(C).second)
490           Worklist.push_back(C);
491 
492   auto VisitRef = [&](Function &Referee) {
493     Node &RefereeN = *G.lookup(Referee);
494     Edge *E = N->lookup(RefereeN);
495     assert((E || !FunctionPass) &&
496            "No function transformations should introduce *new* ref "
497            "edges! Any new ref edges would require IPO which "
498            "function passes aren't allowed to do!");
499     bool Inserted = RetainedEdges.insert(&RefereeN).second;
500     (void)Inserted;
501     assert(Inserted && "We should never visit a function twice.");
502     if (!E)
503       NewRefEdges.insert(&RefereeN);
504     else if (E->isCall())
505       DemotedCallTargets.insert(&RefereeN);
506   };
507   LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
508 
509   // Handle new ref edges.
510   for (Node *RefTarget : NewRefEdges) {
511     SCC &TargetC = *G.lookupSCC(*RefTarget);
512     RefSCC &TargetRC = TargetC.getOuterRefSCC();
513     (void)TargetRC;
514     // TODO: This only allows trivial edges to be added for now.
515     assert((RC == &TargetRC ||
516            RC->isAncestorOf(TargetRC)) && "New ref edge is not trivial!");
517     RC->insertTrivialRefEdge(N, *RefTarget);
518   }
519 
520   // Handle new call edges.
521   for (Node *CallTarget : NewCallEdges) {
522     SCC &TargetC = *G.lookupSCC(*CallTarget);
523     RefSCC &TargetRC = TargetC.getOuterRefSCC();
524     (void)TargetRC;
525     // TODO: This only allows trivial edges to be added for now.
526     assert((RC == &TargetRC ||
527            RC->isAncestorOf(TargetRC)) && "New call edge is not trivial!");
528     RC->insertTrivialCallEdge(N, *CallTarget);
529   }
530 
531   // Include synthetic reference edges to known, defined lib functions.
532   for (auto *F : G.getLibFunctions())
533     // While the list of lib functions doesn't have repeats, don't re-visit
534     // anything handled above.
535     if (!Visited.count(F))
536       VisitRef(*F);
537 
538   // First remove all of the edges that are no longer present in this function.
539   // The first step makes these edges uniformly ref edges and accumulates them
540   // into a separate data structure so removal doesn't invalidate anything.
541   SmallVector<Node *, 4> DeadTargets;
542   for (Edge &E : *N) {
543     if (RetainedEdges.count(&E.getNode()))
544       continue;
545 
546     SCC &TargetC = *G.lookupSCC(E.getNode());
547     RefSCC &TargetRC = TargetC.getOuterRefSCC();
548     if (&TargetRC == RC && E.isCall()) {
549       if (C != &TargetC) {
550         // For separate SCCs this is trivial.
551         RC->switchTrivialInternalEdgeToRef(N, E.getNode());
552       } else {
553         // Now update the call graph.
554         C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
555                                    G, N, C, AM, UR);
556       }
557     }
558 
559     // Now that this is ready for actual removal, put it into our list.
560     DeadTargets.push_back(&E.getNode());
561   }
562   // Remove the easy cases quickly and actually pull them out of our list.
563   DeadTargets.erase(
564       llvm::remove_if(DeadTargets,
565                       [&](Node *TargetN) {
566                         SCC &TargetC = *G.lookupSCC(*TargetN);
567                         RefSCC &TargetRC = TargetC.getOuterRefSCC();
568 
569                         // We can't trivially remove internal targets, so skip
570                         // those.
571                         if (&TargetRC == RC)
572                           return false;
573 
574                         RC->removeOutgoingEdge(N, *TargetN);
575                         LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '"
576                                           << N << "' to '" << TargetN << "'\n");
577                         return true;
578                       }),
579       DeadTargets.end());
580 
581   // Now do a batch removal of the internal ref edges left.
582   auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets);
583   if (!NewRefSCCs.empty()) {
584     // The old RefSCC is dead, mark it as such.
585     UR.InvalidatedRefSCCs.insert(RC);
586 
587     // Note that we don't bother to invalidate analyses as ref-edge
588     // connectivity is not really observable in any way and is intended
589     // exclusively to be used for ordering of transforms rather than for
590     // analysis conclusions.
591 
592     // Update RC to the "bottom".
593     assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
594     RC = &C->getOuterRefSCC();
595     assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
596 
597     // The RC worklist is in reverse postorder, so we enqueue the new ones in
598     // RPO except for the one which contains the source node as that is the
599     // "bottom" we will continue processing in the bottom-up walk.
600     assert(NewRefSCCs.front() == RC &&
601            "New current RefSCC not first in the returned list!");
602     for (RefSCC *NewRC : llvm::reverse(make_range(std::next(NewRefSCCs.begin()),
603                                                   NewRefSCCs.end()))) {
604       assert(NewRC != RC && "Should not encounter the current RefSCC further "
605                             "in the postorder list of new RefSCCs.");
606       UR.RCWorklist.insert(NewRC);
607       LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "
608                         << *NewRC << "\n");
609     }
610   }
611 
612   // Next demote all the call edges that are now ref edges. This helps make
613   // the SCCs small which should minimize the work below as we don't want to
614   // form cycles that this would break.
615   for (Node *RefTarget : DemotedCallTargets) {
616     SCC &TargetC = *G.lookupSCC(*RefTarget);
617     RefSCC &TargetRC = TargetC.getOuterRefSCC();
618 
619     // The easy case is when the target RefSCC is not this RefSCC. This is
620     // only supported when the target RefSCC is a child of this RefSCC.
621     if (&TargetRC != RC) {
622       assert(RC->isAncestorOf(TargetRC) &&
623              "Cannot potentially form RefSCC cycles here!");
624       RC->switchOutgoingEdgeToRef(N, *RefTarget);
625       LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
626                         << "' to '" << *RefTarget << "'\n");
627       continue;
628     }
629 
630     // We are switching an internal call edge to a ref edge. This may split up
631     // some SCCs.
632     if (C != &TargetC) {
633       // For separate SCCs this is trivial.
634       RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
635       continue;
636     }
637 
638     // Now update the call graph.
639     C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
640                                C, AM, UR);
641   }
642 
643   // Now promote ref edges into call edges.
644   for (Node *CallTarget : PromotedRefTargets) {
645     SCC &TargetC = *G.lookupSCC(*CallTarget);
646     RefSCC &TargetRC = TargetC.getOuterRefSCC();
647 
648     // The easy case is when the target RefSCC is not this RefSCC. This is
649     // only supported when the target RefSCC is a child of this RefSCC.
650     if (&TargetRC != RC) {
651       assert(RC->isAncestorOf(TargetRC) &&
652              "Cannot potentially form RefSCC cycles here!");
653       RC->switchOutgoingEdgeToCall(N, *CallTarget);
654       LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
655                         << "' to '" << *CallTarget << "'\n");
656       continue;
657     }
658     LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
659                       << N << "' to '" << *CallTarget << "'\n");
660 
661     // Otherwise we are switching an internal ref edge to a call edge. This
662     // may merge away some SCCs, and we add those to the UpdateResult. We also
663     // need to make sure to update the worklist in the event SCCs have moved
664     // before the current one in the post-order sequence
665     bool HasFunctionAnalysisProxy = false;
666     auto InitialSCCIndex = RC->find(*C) - RC->begin();
667     bool FormedCycle = RC->switchInternalEdgeToCall(
668         N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
669           for (SCC *MergedC : MergedSCCs) {
670             assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
671 
672             HasFunctionAnalysisProxy |=
673                 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
674                     *MergedC) != nullptr;
675 
676             // Mark that this SCC will no longer be valid.
677             UR.InvalidatedSCCs.insert(MergedC);
678 
679             // FIXME: We should really do a 'clear' here to forcibly release
680             // memory, but we don't have a good way of doing that and
681             // preserving the function analyses.
682             auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
683             PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
684             AM.invalidate(*MergedC, PA);
685           }
686         });
687 
688     // If we formed a cycle by creating this call, we need to update more data
689     // structures.
690     if (FormedCycle) {
691       C = &TargetC;
692       assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
693 
694       // If one of the invalidated SCCs had a cached proxy to a function
695       // analysis manager, we need to create a proxy in the new current SCC as
696       // the invalidated SCCs had their functions moved.
697       if (HasFunctionAnalysisProxy)
698         AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G).updateFAM(FAM);
699 
700       // Any analyses cached for this SCC are no longer precise as the shape
701       // has changed by introducing this cycle. However, we have taken care to
702       // update the proxies so it remains valide.
703       auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
704       PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
705       AM.invalidate(*C, PA);
706     }
707     auto NewSCCIndex = RC->find(*C) - RC->begin();
708     // If we have actually moved an SCC to be topologically "below" the current
709     // one due to merging, we will need to revisit the current SCC after
710     // visiting those moved SCCs.
711     //
712     // It is critical that we *do not* revisit the current SCC unless we
713     // actually move SCCs in the process of merging because otherwise we may
714     // form a cycle where an SCC is split apart, merged, split, merged and so
715     // on infinitely.
716     if (InitialSCCIndex < NewSCCIndex) {
717       // Put our current SCC back onto the worklist as we'll visit other SCCs
718       // that are now definitively ordered prior to the current one in the
719       // post-order sequence, and may end up observing more precise context to
720       // optimize the current SCC.
721       UR.CWorklist.insert(C);
722       LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
723                         << "\n");
724       // Enqueue in reverse order as we pop off the back of the worklist.
725       for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
726                                                   RC->begin() + NewSCCIndex))) {
727         UR.CWorklist.insert(&MovedC);
728         LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
729                           << MovedC << "\n");
730       }
731     }
732   }
733 
734   assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
735   assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
736   assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
737 
738   // Record the current RefSCC and SCC for higher layers of the CGSCC pass
739   // manager now that all the updates have been applied.
740   if (RC != &InitialRC)
741     UR.UpdatedRC = RC;
742   if (C != &InitialC)
743     UR.UpdatedC = C;
744 
745   return *C;
746 }
747 
748 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
749     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
750     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
751     FunctionAnalysisManager &FAM) {
752   return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
753                                            /* FunctionPass */ true);
754 }
755 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForCGSCCPass(
756     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
757     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
758     FunctionAnalysisManager &FAM) {
759   return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
760                                            /* FunctionPass */ false);
761 }
762