191bc56edSDimitry Andric //===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
291bc56edSDimitry Andric //
391bc56edSDimitry Andric //                     The LLVM Compiler Infrastructure
491bc56edSDimitry Andric //
591bc56edSDimitry Andric // This file is distributed under the University of Illinois Open Source
691bc56edSDimitry Andric // License. See LICENSE.TXT for details.
791bc56edSDimitry Andric //
891bc56edSDimitry Andric //===----------------------------------------------------------------------===//
991bc56edSDimitry Andric 
1091bc56edSDimitry Andric #include "llvm/Analysis/CGSCCPassManager.h"
112cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
122cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
132cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
142cab237bSDimitry Andric #include "llvm/ADT/SetVector.h"
152cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
162cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
172cab237bSDimitry Andric #include "llvm/ADT/iterator_range.h"
182cab237bSDimitry Andric #include "llvm/Analysis/LazyCallGraph.h"
19d88c1a5aSDimitry Andric #include "llvm/IR/CallSite.h"
202cab237bSDimitry Andric #include "llvm/IR/Constant.h"
21d88c1a5aSDimitry Andric #include "llvm/IR/InstIterator.h"
222cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
232cab237bSDimitry Andric #include "llvm/IR/PassManager.h"
242cab237bSDimitry Andric #include "llvm/Support/Casting.h"
252cab237bSDimitry Andric #include "llvm/Support/Debug.h"
262cab237bSDimitry Andric #include "llvm/Support/raw_ostream.h"
272cab237bSDimitry Andric #include <algorithm>
282cab237bSDimitry Andric #include <cassert>
292cab237bSDimitry Andric #include <iterator>
302cab237bSDimitry Andric 
312cab237bSDimitry Andric #define DEBUG_TYPE "cgscc"
3291bc56edSDimitry Andric 
3391bc56edSDimitry Andric using namespace llvm;
3491bc56edSDimitry Andric 
354ba319b5SDimitry Andric // Explicit template instantiations and specialization definitions for core
36d88c1a5aSDimitry Andric // template typedefs.
373ca95b02SDimitry Andric namespace llvm {
38d88c1a5aSDimitry Andric 
39d88c1a5aSDimitry Andric // Explicit instantiations for the core proxy templates.
40d88c1a5aSDimitry Andric template class AllAnalysesOn<LazyCallGraph::SCC>;
41d88c1a5aSDimitry Andric template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
42d88c1a5aSDimitry Andric template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
43d88c1a5aSDimitry Andric                            LazyCallGraph &, CGSCCUpdateResult &>;
443ca95b02SDimitry Andric template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
453ca95b02SDimitry Andric template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
46d88c1a5aSDimitry Andric                                          LazyCallGraph::SCC, LazyCallGraph &>;
473ca95b02SDimitry Andric template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
48d88c1a5aSDimitry Andric 
49d88c1a5aSDimitry Andric /// Explicitly specialize the pass manager run method to handle call graph
50d88c1a5aSDimitry Andric /// updates.
51d88c1a5aSDimitry Andric template <>
52d88c1a5aSDimitry Andric PreservedAnalyses
53d88c1a5aSDimitry Andric PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
run(LazyCallGraph::SCC & InitialC,CGSCCAnalysisManager & AM,LazyCallGraph & G,CGSCCUpdateResult & UR)54d88c1a5aSDimitry Andric             CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
55d88c1a5aSDimitry Andric                                       CGSCCAnalysisManager &AM,
56d88c1a5aSDimitry Andric                                       LazyCallGraph &G, CGSCCUpdateResult &UR) {
57*b5893f02SDimitry Andric   // Request PassInstrumentation from analysis manager, will use it to run
58*b5893f02SDimitry Andric   // instrumenting callbacks for the passes later.
59*b5893f02SDimitry Andric   PassInstrumentation PI =
60*b5893f02SDimitry Andric       AM.getResult<PassInstrumentationAnalysis>(InitialC, G);
61*b5893f02SDimitry Andric 
62d88c1a5aSDimitry Andric   PreservedAnalyses PA = PreservedAnalyses::all();
63d88c1a5aSDimitry Andric 
64d88c1a5aSDimitry Andric   if (DebugLogging)
65d88c1a5aSDimitry Andric     dbgs() << "Starting CGSCC pass manager run.\n";
66d88c1a5aSDimitry Andric 
67d88c1a5aSDimitry Andric   // The SCC may be refined while we are running passes over it, so set up
68d88c1a5aSDimitry Andric   // a pointer that we can update.
69d88c1a5aSDimitry Andric   LazyCallGraph::SCC *C = &InitialC;
70d88c1a5aSDimitry Andric 
71d88c1a5aSDimitry Andric   for (auto &Pass : Passes) {
72d88c1a5aSDimitry Andric     if (DebugLogging)
73d88c1a5aSDimitry Andric       dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";
74d88c1a5aSDimitry Andric 
75*b5893f02SDimitry Andric     // Check the PassInstrumentation's BeforePass callbacks before running the
76*b5893f02SDimitry Andric     // pass, skip its execution completely if asked to (callback returns false).
77*b5893f02SDimitry Andric     if (!PI.runBeforePass(*Pass, *C))
78*b5893f02SDimitry Andric       continue;
79*b5893f02SDimitry Andric 
80d88c1a5aSDimitry Andric     PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
81d88c1a5aSDimitry Andric 
82*b5893f02SDimitry Andric     if (UR.InvalidatedSCCs.count(C))
83*b5893f02SDimitry Andric       PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass);
84*b5893f02SDimitry Andric     else
85*b5893f02SDimitry Andric       PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C);
86*b5893f02SDimitry Andric 
87d88c1a5aSDimitry Andric     // Update the SCC if necessary.
88d88c1a5aSDimitry Andric     C = UR.UpdatedC ? UR.UpdatedC : C;
89d88c1a5aSDimitry Andric 
902cab237bSDimitry Andric     // If the CGSCC pass wasn't able to provide a valid updated SCC, the
912cab237bSDimitry Andric     // current SCC may simply need to be skipped if invalid.
922cab237bSDimitry Andric     if (UR.InvalidatedSCCs.count(C)) {
934ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
942cab237bSDimitry Andric       break;
952cab237bSDimitry Andric     }
96d88c1a5aSDimitry Andric     // Check that we didn't miss any update scenario.
97d88c1a5aSDimitry Andric     assert(C->begin() != C->end() && "Cannot have an empty SCC!");
98d88c1a5aSDimitry Andric 
99d88c1a5aSDimitry Andric     // Update the analysis manager as each pass runs and potentially
100d88c1a5aSDimitry Andric     // invalidates analyses.
101d88c1a5aSDimitry Andric     AM.invalidate(*C, PassPA);
102d88c1a5aSDimitry Andric 
103d88c1a5aSDimitry Andric     // Finally, we intersect the final preserved analyses to compute the
104d88c1a5aSDimitry Andric     // aggregate preserved set for this pass manager.
105d88c1a5aSDimitry Andric     PA.intersect(std::move(PassPA));
106d88c1a5aSDimitry Andric 
107d88c1a5aSDimitry Andric     // FIXME: Historically, the pass managers all called the LLVM context's
108d88c1a5aSDimitry Andric     // yield function here. We don't have a generic way to acquire the
109d88c1a5aSDimitry Andric     // context and it isn't yet clear what the right pattern is for yielding
110d88c1a5aSDimitry Andric     // in the new pass manager so it is currently omitted.
111d88c1a5aSDimitry Andric     // ...getContext().yield();
112d88c1a5aSDimitry Andric   }
113d88c1a5aSDimitry Andric 
1144ba319b5SDimitry Andric   // Invalidation was handled after each pass in the above loop for the current
115d88c1a5aSDimitry Andric   // SCC. Therefore, the remaining analysis results in the AnalysisManager are
116d88c1a5aSDimitry Andric   // preserved. We mark this with a set so that we don't need to inspect each
117d88c1a5aSDimitry Andric   // one individually.
118d88c1a5aSDimitry Andric   PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
119d88c1a5aSDimitry Andric 
120d88c1a5aSDimitry Andric   if (DebugLogging)
121d88c1a5aSDimitry Andric     dbgs() << "Finished CGSCC pass manager run.\n";
122d88c1a5aSDimitry Andric 
123d88c1a5aSDimitry Andric   return PA;
124d88c1a5aSDimitry Andric }
125d88c1a5aSDimitry Andric 
invalidate(Module & M,const PreservedAnalyses & PA,ModuleAnalysisManager::Invalidator & Inv)126d88c1a5aSDimitry Andric bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
127d88c1a5aSDimitry Andric     Module &M, const PreservedAnalyses &PA,
128d88c1a5aSDimitry Andric     ModuleAnalysisManager::Invalidator &Inv) {
129d88c1a5aSDimitry Andric   // If literally everything is preserved, we're done.
130d88c1a5aSDimitry Andric   if (PA.areAllPreserved())
131d88c1a5aSDimitry Andric     return false; // This is still a valid proxy.
132d88c1a5aSDimitry Andric 
133d88c1a5aSDimitry Andric   // If this proxy or the call graph is going to be invalidated, we also need
134d88c1a5aSDimitry Andric   // to clear all the keys coming from that analysis.
135d88c1a5aSDimitry Andric   //
136d88c1a5aSDimitry Andric   // We also directly invalidate the FAM's module proxy if necessary, and if
137d88c1a5aSDimitry Andric   // that proxy isn't preserved we can't preserve this proxy either. We rely on
138d88c1a5aSDimitry Andric   // it to handle module -> function analysis invalidation in the face of
139d88c1a5aSDimitry Andric   // structural changes and so if it's unavailable we conservatively clear the
140d88c1a5aSDimitry Andric   // entire SCC layer as well rather than trying to do invalidation ourselves.
141d88c1a5aSDimitry Andric   auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
142d88c1a5aSDimitry Andric   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
143d88c1a5aSDimitry Andric       Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
144d88c1a5aSDimitry Andric       Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
145d88c1a5aSDimitry Andric     InnerAM->clear();
146d88c1a5aSDimitry Andric 
147d88c1a5aSDimitry Andric     // And the proxy itself should be marked as invalid so that we can observe
148d88c1a5aSDimitry Andric     // the new call graph. This isn't strictly necessary because we cheat
149d88c1a5aSDimitry Andric     // above, but is still useful.
150d88c1a5aSDimitry Andric     return true;
151d88c1a5aSDimitry Andric   }
152d88c1a5aSDimitry Andric 
153d88c1a5aSDimitry Andric   // Directly check if the relevant set is preserved so we can short circuit
154d88c1a5aSDimitry Andric   // invalidating SCCs below.
155d88c1a5aSDimitry Andric   bool AreSCCAnalysesPreserved =
156d88c1a5aSDimitry Andric       PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
157d88c1a5aSDimitry Andric 
158d88c1a5aSDimitry Andric   // Ok, we have a graph, so we can propagate the invalidation down into it.
1597a7e6055SDimitry Andric   G->buildRefSCCs();
160d88c1a5aSDimitry Andric   for (auto &RC : G->postorder_ref_sccs())
161d88c1a5aSDimitry Andric     for (auto &C : RC) {
162d88c1a5aSDimitry Andric       Optional<PreservedAnalyses> InnerPA;
163d88c1a5aSDimitry Andric 
164d88c1a5aSDimitry Andric       // Check to see whether the preserved set needs to be adjusted based on
165d88c1a5aSDimitry Andric       // module-level analysis invalidation triggering deferred invalidation
166d88c1a5aSDimitry Andric       // for this SCC.
167d88c1a5aSDimitry Andric       if (auto *OuterProxy =
168d88c1a5aSDimitry Andric               InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
169d88c1a5aSDimitry Andric         for (const auto &OuterInvalidationPair :
170d88c1a5aSDimitry Andric              OuterProxy->getOuterInvalidations()) {
171d88c1a5aSDimitry Andric           AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
172d88c1a5aSDimitry Andric           const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
173d88c1a5aSDimitry Andric           if (Inv.invalidate(OuterAnalysisID, M, PA)) {
174d88c1a5aSDimitry Andric             if (!InnerPA)
175d88c1a5aSDimitry Andric               InnerPA = PA;
176d88c1a5aSDimitry Andric             for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
177d88c1a5aSDimitry Andric               InnerPA->abandon(InnerAnalysisID);
178d88c1a5aSDimitry Andric           }
179d88c1a5aSDimitry Andric         }
180d88c1a5aSDimitry Andric 
181d88c1a5aSDimitry Andric       // Check if we needed a custom PA set. If so we'll need to run the inner
182d88c1a5aSDimitry Andric       // invalidation.
183d88c1a5aSDimitry Andric       if (InnerPA) {
184d88c1a5aSDimitry Andric         InnerAM->invalidate(C, *InnerPA);
185d88c1a5aSDimitry Andric         continue;
186d88c1a5aSDimitry Andric       }
187d88c1a5aSDimitry Andric 
188d88c1a5aSDimitry Andric       // Otherwise we only need to do invalidation if the original PA set didn't
189d88c1a5aSDimitry Andric       // preserve all SCC analyses.
190d88c1a5aSDimitry Andric       if (!AreSCCAnalysesPreserved)
191d88c1a5aSDimitry Andric         InnerAM->invalidate(C, PA);
192d88c1a5aSDimitry Andric     }
193d88c1a5aSDimitry Andric 
194d88c1a5aSDimitry Andric   // Return false to indicate that this result is still a valid proxy.
195d88c1a5aSDimitry Andric   return false;
196d88c1a5aSDimitry Andric }
197d88c1a5aSDimitry Andric 
198d88c1a5aSDimitry Andric template <>
199d88c1a5aSDimitry Andric CGSCCAnalysisManagerModuleProxy::Result
run(Module & M,ModuleAnalysisManager & AM)200d88c1a5aSDimitry Andric CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
201d88c1a5aSDimitry Andric   // Force the Function analysis manager to also be available so that it can
202d88c1a5aSDimitry Andric   // be accessed in an SCC analysis and proxied onward to function passes.
203d88c1a5aSDimitry Andric   // FIXME: It is pretty awkward to just drop the result here and assert that
204d88c1a5aSDimitry Andric   // we can find it again later.
205d88c1a5aSDimitry Andric   (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
206d88c1a5aSDimitry Andric 
207d88c1a5aSDimitry Andric   return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
208d88c1a5aSDimitry Andric }
209d88c1a5aSDimitry Andric 
210d88c1a5aSDimitry Andric AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
211d88c1a5aSDimitry Andric 
212d88c1a5aSDimitry Andric FunctionAnalysisManagerCGSCCProxy::Result
run(LazyCallGraph::SCC & C,CGSCCAnalysisManager & AM,LazyCallGraph & CG)213d88c1a5aSDimitry Andric FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
214d88c1a5aSDimitry Andric                                        CGSCCAnalysisManager &AM,
215d88c1a5aSDimitry Andric                                        LazyCallGraph &CG) {
216d88c1a5aSDimitry Andric   // Collect the FunctionAnalysisManager from the Module layer and use that to
217d88c1a5aSDimitry Andric   // build the proxy result.
218d88c1a5aSDimitry Andric   //
219d88c1a5aSDimitry Andric   // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to
220d88c1a5aSDimitry Andric   // invalidate the function analyses.
221d88c1a5aSDimitry Andric   auto &MAM = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG).getManager();
222d88c1a5aSDimitry Andric   Module &M = *C.begin()->getFunction().getParent();
223d88c1a5aSDimitry Andric   auto *FAMProxy = MAM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M);
224d88c1a5aSDimitry Andric   assert(FAMProxy && "The CGSCC pass manager requires that the FAM module "
225d88c1a5aSDimitry Andric                      "proxy is run on the module prior to entering the CGSCC "
226d88c1a5aSDimitry Andric                      "walk.");
227d88c1a5aSDimitry Andric 
228d88c1a5aSDimitry Andric   // Note that we special-case invalidation handling of this proxy in the CGSCC
229d88c1a5aSDimitry Andric   // analysis manager's Module proxy. This avoids the need to do anything
230d88c1a5aSDimitry Andric   // special here to recompute all of this if ever the FAM's module proxy goes
231d88c1a5aSDimitry Andric   // away.
232d88c1a5aSDimitry Andric   return Result(FAMProxy->getManager());
233d88c1a5aSDimitry Andric }
234d88c1a5aSDimitry Andric 
invalidate(LazyCallGraph::SCC & C,const PreservedAnalyses & PA,CGSCCAnalysisManager::Invalidator & Inv)235d88c1a5aSDimitry Andric bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
236d88c1a5aSDimitry Andric     LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
237d88c1a5aSDimitry Andric     CGSCCAnalysisManager::Invalidator &Inv) {
238c4394386SDimitry Andric   // If literally everything is preserved, we're done.
239c4394386SDimitry Andric   if (PA.areAllPreserved())
240c4394386SDimitry Andric     return false; // This is still a valid proxy.
241d88c1a5aSDimitry Andric 
242c4394386SDimitry Andric   // If this proxy isn't marked as preserved, then even if the result remains
243c4394386SDimitry Andric   // valid, the key itself may no longer be valid, so we clear everything.
244c4394386SDimitry Andric   //
245c4394386SDimitry Andric   // Note that in order to preserve this proxy, a module pass must ensure that
246c4394386SDimitry Andric   // the FAM has been completely updated to handle the deletion of functions.
247c4394386SDimitry Andric   // Specifically, any FAM-cached results for those functions need to have been
248c4394386SDimitry Andric   // forcibly cleared. When preserved, this proxy will only invalidate results
249c4394386SDimitry Andric   // cached on functions *still in the module* at the end of the module pass.
250c4394386SDimitry Andric   auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
251c4394386SDimitry Andric   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
252c4394386SDimitry Andric     for (LazyCallGraph::Node &N : C)
2532cab237bSDimitry Andric       FAM->clear(N.getFunction(), N.getFunction().getName());
254c4394386SDimitry Andric 
255c4394386SDimitry Andric     return true;
256c4394386SDimitry Andric   }
257c4394386SDimitry Andric 
258c4394386SDimitry Andric   // Directly check if the relevant set is preserved.
259c4394386SDimitry Andric   bool AreFunctionAnalysesPreserved =
260c4394386SDimitry Andric       PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
261c4394386SDimitry Andric 
262c4394386SDimitry Andric   // Now walk all the functions to see if any inner analysis invalidation is
263c4394386SDimitry Andric   // necessary.
264c4394386SDimitry Andric   for (LazyCallGraph::Node &N : C) {
265c4394386SDimitry Andric     Function &F = N.getFunction();
266c4394386SDimitry Andric     Optional<PreservedAnalyses> FunctionPA;
267c4394386SDimitry Andric 
268c4394386SDimitry Andric     // Check to see whether the preserved set needs to be pruned based on
269c4394386SDimitry Andric     // SCC-level analysis invalidation that triggers deferred invalidation
270c4394386SDimitry Andric     // registered with the outer analysis manager proxy for this function.
271c4394386SDimitry Andric     if (auto *OuterProxy =
272c4394386SDimitry Andric             FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
273c4394386SDimitry Andric       for (const auto &OuterInvalidationPair :
274c4394386SDimitry Andric            OuterProxy->getOuterInvalidations()) {
275c4394386SDimitry Andric         AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
276c4394386SDimitry Andric         const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
277c4394386SDimitry Andric         if (Inv.invalidate(OuterAnalysisID, C, PA)) {
278c4394386SDimitry Andric           if (!FunctionPA)
279c4394386SDimitry Andric             FunctionPA = PA;
280c4394386SDimitry Andric           for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
281c4394386SDimitry Andric             FunctionPA->abandon(InnerAnalysisID);
282c4394386SDimitry Andric         }
283c4394386SDimitry Andric       }
284c4394386SDimitry Andric 
285c4394386SDimitry Andric     // Check if we needed a custom PA set, and if so we'll need to run the
286c4394386SDimitry Andric     // inner invalidation.
287c4394386SDimitry Andric     if (FunctionPA) {
288c4394386SDimitry Andric       FAM->invalidate(F, *FunctionPA);
289c4394386SDimitry Andric       continue;
290c4394386SDimitry Andric     }
291c4394386SDimitry Andric 
292c4394386SDimitry Andric     // Otherwise we only need to do invalidation if the original PA set didn't
293c4394386SDimitry Andric     // preserve all function analyses.
294c4394386SDimitry Andric     if (!AreFunctionAnalysesPreserved)
295c4394386SDimitry Andric       FAM->invalidate(F, PA);
296c4394386SDimitry Andric   }
297c4394386SDimitry Andric 
298c4394386SDimitry Andric   // Return false to indicate that this result is still a valid proxy.
299d88c1a5aSDimitry Andric   return false;
300d88c1a5aSDimitry Andric }
301d88c1a5aSDimitry Andric 
3022cab237bSDimitry Andric } // end namespace llvm
303d88c1a5aSDimitry Andric 
304c4394386SDimitry Andric /// When a new SCC is created for the graph and there might be function
305c4394386SDimitry Andric /// analysis results cached for the functions now in that SCC two forms of
306c4394386SDimitry Andric /// updates are required.
307c4394386SDimitry Andric ///
308c4394386SDimitry Andric /// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
309c4394386SDimitry Andric /// created so that any subsequent invalidation events to the SCC are
310c4394386SDimitry Andric /// propagated to the function analysis results cached for functions within it.
311c4394386SDimitry Andric ///
312c4394386SDimitry Andric /// Second, if any of the functions within the SCC have analysis results with
313c4394386SDimitry Andric /// outer analysis dependencies, then those dependencies would point to the
314c4394386SDimitry Andric /// *wrong* SCC's analysis result. We forcibly invalidate the necessary
315c4394386SDimitry Andric /// function analyses so that they don't retain stale handles.
updateNewSCCFunctionAnalyses(LazyCallGraph::SCC & C,LazyCallGraph & G,CGSCCAnalysisManager & AM)316c4394386SDimitry Andric static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
317c4394386SDimitry Andric                                          LazyCallGraph &G,
318c4394386SDimitry Andric                                          CGSCCAnalysisManager &AM) {
319c4394386SDimitry Andric   // Get the relevant function analysis manager.
320c4394386SDimitry Andric   auto &FAM =
321c4394386SDimitry Andric       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).getManager();
322c4394386SDimitry Andric 
323c4394386SDimitry Andric   // Now walk the functions in this SCC and invalidate any function analysis
324c4394386SDimitry Andric   // results that might have outer dependencies on an SCC analysis.
325c4394386SDimitry Andric   for (LazyCallGraph::Node &N : C) {
326c4394386SDimitry Andric     Function &F = N.getFunction();
327c4394386SDimitry Andric 
328c4394386SDimitry Andric     auto *OuterProxy =
329c4394386SDimitry Andric         FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
330c4394386SDimitry Andric     if (!OuterProxy)
331c4394386SDimitry Andric       // No outer analyses were queried, nothing to do.
332c4394386SDimitry Andric       continue;
333c4394386SDimitry Andric 
334c4394386SDimitry Andric     // Forcibly abandon all the inner analyses with dependencies, but
335c4394386SDimitry Andric     // invalidate nothing else.
336c4394386SDimitry Andric     auto PA = PreservedAnalyses::all();
337c4394386SDimitry Andric     for (const auto &OuterInvalidationPair :
338c4394386SDimitry Andric          OuterProxy->getOuterInvalidations()) {
339c4394386SDimitry Andric       const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
340c4394386SDimitry Andric       for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
341c4394386SDimitry Andric         PA.abandon(InnerAnalysisID);
342c4394386SDimitry Andric     }
343c4394386SDimitry Andric 
344c4394386SDimitry Andric     // Now invalidate anything we found.
345c4394386SDimitry Andric     FAM.invalidate(F, PA);
346c4394386SDimitry Andric   }
347c4394386SDimitry Andric }
348c4394386SDimitry Andric 
349d88c1a5aSDimitry Andric /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
350d88c1a5aSDimitry Andric /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
351d88c1a5aSDimitry Andric /// added SCCs.
352d88c1a5aSDimitry Andric ///
353d88c1a5aSDimitry Andric /// The range of new SCCs must be in postorder already. The SCC they were split
354d88c1a5aSDimitry Andric /// out of must be provided as \p C. The current node being mutated and
355d88c1a5aSDimitry Andric /// triggering updates must be passed as \p N.
356d88c1a5aSDimitry Andric ///
357d88c1a5aSDimitry Andric /// This function returns the SCC containing \p N. This will be either \p C if
358d88c1a5aSDimitry Andric /// no new SCCs have been split out, or it will be the new SCC containing \p N.
359d88c1a5aSDimitry Andric template <typename SCCRangeT>
3602cab237bSDimitry Andric static LazyCallGraph::SCC *
incorporateNewSCCRange(const SCCRangeT & NewSCCRange,LazyCallGraph & G,LazyCallGraph::Node & N,LazyCallGraph::SCC * C,CGSCCAnalysisManager & AM,CGSCCUpdateResult & UR)361d88c1a5aSDimitry Andric incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
362d88c1a5aSDimitry Andric                        LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
3632cab237bSDimitry Andric                        CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
3642cab237bSDimitry Andric   using SCC = LazyCallGraph::SCC;
365d88c1a5aSDimitry Andric 
366d88c1a5aSDimitry Andric   if (NewSCCRange.begin() == NewSCCRange.end())
367d88c1a5aSDimitry Andric     return C;
368d88c1a5aSDimitry Andric 
369d88c1a5aSDimitry Andric   // Add the current SCC to the worklist as its shape has changed.
370d88c1a5aSDimitry Andric   UR.CWorklist.insert(C);
3714ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
3724ba319b5SDimitry Andric                     << "\n");
373d88c1a5aSDimitry Andric 
374d88c1a5aSDimitry Andric   SCC *OldC = C;
375d88c1a5aSDimitry Andric 
376d88c1a5aSDimitry Andric   // Update the current SCC. Note that if we have new SCCs, this must actually
377d88c1a5aSDimitry Andric   // change the SCC.
378d88c1a5aSDimitry Andric   assert(C != &*NewSCCRange.begin() &&
379d88c1a5aSDimitry Andric          "Cannot insert new SCCs without changing current SCC!");
380d88c1a5aSDimitry Andric   C = &*NewSCCRange.begin();
381d88c1a5aSDimitry Andric   assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
382d88c1a5aSDimitry Andric 
383c4394386SDimitry Andric   // If we had a cached FAM proxy originally, we will want to create more of
384c4394386SDimitry Andric   // them for each SCC that was split off.
385c4394386SDimitry Andric   bool NeedFAMProxy =
386c4394386SDimitry Andric       AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC) != nullptr;
387c4394386SDimitry Andric 
388c4394386SDimitry Andric   // We need to propagate an invalidation call to all but the newly current SCC
389c4394386SDimitry Andric   // because the outer pass manager won't do that for us after splitting them.
390c4394386SDimitry Andric   // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
3914ba319b5SDimitry Andric   // there are preserved analysis we can avoid invalidating them here for
392c4394386SDimitry Andric   // split-off SCCs.
393c4394386SDimitry Andric   // We know however that this will preserve any FAM proxy so go ahead and mark
394c4394386SDimitry Andric   // that.
395c4394386SDimitry Andric   PreservedAnalyses PA;
396c4394386SDimitry Andric   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
397c4394386SDimitry Andric   AM.invalidate(*OldC, PA);
398c4394386SDimitry Andric 
399c4394386SDimitry Andric   // Ensure the now-current SCC's function analyses are updated.
400c4394386SDimitry Andric   if (NeedFAMProxy)
401c4394386SDimitry Andric     updateNewSCCFunctionAnalyses(*C, G, AM);
402c4394386SDimitry Andric 
4032cab237bSDimitry Andric   for (SCC &NewC : llvm::reverse(make_range(std::next(NewSCCRange.begin()),
4042cab237bSDimitry Andric                                             NewSCCRange.end()))) {
405d88c1a5aSDimitry Andric     assert(C != &NewC && "No need to re-visit the current SCC!");
406d88c1a5aSDimitry Andric     assert(OldC != &NewC && "Already handled the original SCC!");
407d88c1a5aSDimitry Andric     UR.CWorklist.insert(&NewC);
4084ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
409c4394386SDimitry Andric 
410c4394386SDimitry Andric     // Ensure new SCCs' function analyses are updated.
411c4394386SDimitry Andric     if (NeedFAMProxy)
412c4394386SDimitry Andric       updateNewSCCFunctionAnalyses(NewC, G, AM);
413c4394386SDimitry Andric 
414c4394386SDimitry Andric     // Also propagate a normal invalidation to the new SCC as only the current
415c4394386SDimitry Andric     // will get one from the pass manager infrastructure.
416c4394386SDimitry Andric     AM.invalidate(NewC, PA);
417d88c1a5aSDimitry Andric   }
418d88c1a5aSDimitry Andric   return C;
419d88c1a5aSDimitry Andric }
420d88c1a5aSDimitry Andric 
updateCGAndAnalysisManagerForFunctionPass(LazyCallGraph & G,LazyCallGraph::SCC & InitialC,LazyCallGraph::Node & N,CGSCCAnalysisManager & AM,CGSCCUpdateResult & UR)421d88c1a5aSDimitry Andric LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
422d88c1a5aSDimitry Andric     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
4232cab237bSDimitry Andric     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
4242cab237bSDimitry Andric   using Node = LazyCallGraph::Node;
4252cab237bSDimitry Andric   using Edge = LazyCallGraph::Edge;
4262cab237bSDimitry Andric   using SCC = LazyCallGraph::SCC;
4272cab237bSDimitry Andric   using RefSCC = LazyCallGraph::RefSCC;
428d88c1a5aSDimitry Andric 
429d88c1a5aSDimitry Andric   RefSCC &InitialRC = InitialC.getOuterRefSCC();
430d88c1a5aSDimitry Andric   SCC *C = &InitialC;
431d88c1a5aSDimitry Andric   RefSCC *RC = &InitialRC;
432d88c1a5aSDimitry Andric   Function &F = N.getFunction();
433d88c1a5aSDimitry Andric 
434d88c1a5aSDimitry Andric   // Walk the function body and build up the set of retained, promoted, and
435d88c1a5aSDimitry Andric   // demoted edges.
436d88c1a5aSDimitry Andric   SmallVector<Constant *, 16> Worklist;
437d88c1a5aSDimitry Andric   SmallPtrSet<Constant *, 16> Visited;
4387a7e6055SDimitry Andric   SmallPtrSet<Node *, 16> RetainedEdges;
4397a7e6055SDimitry Andric   SmallSetVector<Node *, 4> PromotedRefTargets;
4407a7e6055SDimitry Andric   SmallSetVector<Node *, 4> DemotedCallTargets;
441d88c1a5aSDimitry Andric 
442d88c1a5aSDimitry Andric   // First walk the function and handle all called functions. We do this first
443d88c1a5aSDimitry Andric   // because if there is a single call edge, whether there are ref edges is
444d88c1a5aSDimitry Andric   // irrelevant.
445d88c1a5aSDimitry Andric   for (Instruction &I : instructions(F))
446d88c1a5aSDimitry Andric     if (auto CS = CallSite(&I))
447d88c1a5aSDimitry Andric       if (Function *Callee = CS.getCalledFunction())
448d88c1a5aSDimitry Andric         if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
4497a7e6055SDimitry Andric           Node &CalleeN = *G.lookup(*Callee);
4507a7e6055SDimitry Andric           Edge *E = N->lookup(CalleeN);
451d88c1a5aSDimitry Andric           // FIXME: We should really handle adding new calls. While it will
452d88c1a5aSDimitry Andric           // make downstream usage more complex, there is no fundamental
453d88c1a5aSDimitry Andric           // limitation and it will allow passes within the CGSCC to be a bit
454d88c1a5aSDimitry Andric           // more flexible in what transforms they can do. Until then, we
455d88c1a5aSDimitry Andric           // verify that new calls haven't been introduced.
456d88c1a5aSDimitry Andric           assert(E && "No function transformations should introduce *new* "
457d88c1a5aSDimitry Andric                       "call edges! Any new calls should be modeled as "
458d88c1a5aSDimitry Andric                       "promoted existing ref edges!");
4592cab237bSDimitry Andric           bool Inserted = RetainedEdges.insert(&CalleeN).second;
4602cab237bSDimitry Andric           (void)Inserted;
4612cab237bSDimitry Andric           assert(Inserted && "We should never visit a function twice.");
462d88c1a5aSDimitry Andric           if (!E->isCall())
4637a7e6055SDimitry Andric             PromotedRefTargets.insert(&CalleeN);
464d88c1a5aSDimitry Andric         }
465d88c1a5aSDimitry Andric 
466d88c1a5aSDimitry Andric   // Now walk all references.
467d88c1a5aSDimitry Andric   for (Instruction &I : instructions(F))
468d88c1a5aSDimitry Andric     for (Value *Op : I.operand_values())
4692cab237bSDimitry Andric       if (auto *C = dyn_cast<Constant>(Op))
470d88c1a5aSDimitry Andric         if (Visited.insert(C).second)
471d88c1a5aSDimitry Andric           Worklist.push_back(C);
472d88c1a5aSDimitry Andric 
473b40b48b8SDimitry Andric   auto VisitRef = [&](Function &Referee) {
4747a7e6055SDimitry Andric     Node &RefereeN = *G.lookup(Referee);
4757a7e6055SDimitry Andric     Edge *E = N->lookup(RefereeN);
476d88c1a5aSDimitry Andric     // FIXME: Similarly to new calls, we also currently preclude
477d88c1a5aSDimitry Andric     // introducing new references. See above for details.
478d88c1a5aSDimitry Andric     assert(E && "No function transformations should introduce *new* ref "
479d88c1a5aSDimitry Andric                 "edges! Any new ref edges would require IPO which "
480d88c1a5aSDimitry Andric                 "function passes aren't allowed to do!");
4812cab237bSDimitry Andric     bool Inserted = RetainedEdges.insert(&RefereeN).second;
4822cab237bSDimitry Andric     (void)Inserted;
4832cab237bSDimitry Andric     assert(Inserted && "We should never visit a function twice.");
484d88c1a5aSDimitry Andric     if (E->isCall())
4857a7e6055SDimitry Andric       DemotedCallTargets.insert(&RefereeN);
486b40b48b8SDimitry Andric   };
487b40b48b8SDimitry Andric   LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
488b40b48b8SDimitry Andric 
489b40b48b8SDimitry Andric   // Include synthetic reference edges to known, defined lib functions.
490b40b48b8SDimitry Andric   for (auto *F : G.getLibFunctions())
4912cab237bSDimitry Andric     // While the list of lib functions doesn't have repeats, don't re-visit
4922cab237bSDimitry Andric     // anything handled above.
4932cab237bSDimitry Andric     if (!Visited.count(F))
494b40b48b8SDimitry Andric       VisitRef(*F);
495d88c1a5aSDimitry Andric 
496d88c1a5aSDimitry Andric   // First remove all of the edges that are no longer present in this function.
4972cab237bSDimitry Andric   // The first step makes these edges uniformly ref edges and accumulates them
4982cab237bSDimitry Andric   // into a separate data structure so removal doesn't invalidate anything.
4992cab237bSDimitry Andric   SmallVector<Node *, 4> DeadTargets;
5002cab237bSDimitry Andric   for (Edge &E : *N) {
5012cab237bSDimitry Andric     if (RetainedEdges.count(&E.getNode()))
502d88c1a5aSDimitry Andric       continue;
503d88c1a5aSDimitry Andric 
5042cab237bSDimitry Andric     SCC &TargetC = *G.lookupSCC(E.getNode());
5052cab237bSDimitry Andric     RefSCC &TargetRC = TargetC.getOuterRefSCC();
5062cab237bSDimitry Andric     if (&TargetRC == RC && E.isCall()) {
507d88c1a5aSDimitry Andric       if (C != &TargetC) {
508d88c1a5aSDimitry Andric         // For separate SCCs this is trivial.
5092cab237bSDimitry Andric         RC->switchTrivialInternalEdgeToRef(N, E.getNode());
510d88c1a5aSDimitry Andric       } else {
511d88c1a5aSDimitry Andric         // Now update the call graph.
5122cab237bSDimitry Andric         C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
5132cab237bSDimitry Andric                                    G, N, C, AM, UR);
514d88c1a5aSDimitry Andric       }
515d88c1a5aSDimitry Andric     }
516d88c1a5aSDimitry Andric 
5172cab237bSDimitry Andric     // Now that this is ready for actual removal, put it into our list.
5182cab237bSDimitry Andric     DeadTargets.push_back(&E.getNode());
5192cab237bSDimitry Andric   }
5202cab237bSDimitry Andric   // Remove the easy cases quickly and actually pull them out of our list.
5212cab237bSDimitry Andric   DeadTargets.erase(
5222cab237bSDimitry Andric       llvm::remove_if(DeadTargets,
5232cab237bSDimitry Andric                       [&](Node *TargetN) {
5242cab237bSDimitry Andric                         SCC &TargetC = *G.lookupSCC(*TargetN);
5252cab237bSDimitry Andric                         RefSCC &TargetRC = TargetC.getOuterRefSCC();
5262cab237bSDimitry Andric 
5272cab237bSDimitry Andric                         // We can't trivially remove internal targets, so skip
5282cab237bSDimitry Andric                         // those.
5292cab237bSDimitry Andric                         if (&TargetRC == RC)
5302cab237bSDimitry Andric                           return false;
5312cab237bSDimitry Andric 
5322cab237bSDimitry Andric                         RC->removeOutgoingEdge(N, *TargetN);
5334ba319b5SDimitry Andric                         LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '"
5344ba319b5SDimitry Andric                                           << N << "' to '" << TargetN << "'\n");
5352cab237bSDimitry Andric                         return true;
5362cab237bSDimitry Andric                       }),
5372cab237bSDimitry Andric       DeadTargets.end());
5382cab237bSDimitry Andric 
5392cab237bSDimitry Andric   // Now do a batch removal of the internal ref edges left.
5402cab237bSDimitry Andric   auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets);
541d88c1a5aSDimitry Andric   if (!NewRefSCCs.empty()) {
5422cab237bSDimitry Andric     // The old RefSCC is dead, mark it as such.
5432cab237bSDimitry Andric     UR.InvalidatedRefSCCs.insert(RC);
5442cab237bSDimitry Andric 
545d88c1a5aSDimitry Andric     // Note that we don't bother to invalidate analyses as ref-edge
546d88c1a5aSDimitry Andric     // connectivity is not really observable in any way and is intended
547d88c1a5aSDimitry Andric     // exclusively to be used for ordering of transforms rather than for
548d88c1a5aSDimitry Andric     // analysis conclusions.
549d88c1a5aSDimitry Andric 
5502cab237bSDimitry Andric     // Update RC to the "bottom".
551d88c1a5aSDimitry Andric     assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
552d88c1a5aSDimitry Andric     RC = &C->getOuterRefSCC();
553d88c1a5aSDimitry Andric     assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
5542cab237bSDimitry Andric 
5552cab237bSDimitry Andric     // The RC worklist is in reverse postorder, so we enqueue the new ones in
5562cab237bSDimitry Andric     // RPO except for the one which contains the source node as that is the
5572cab237bSDimitry Andric     // "bottom" we will continue processing in the bottom-up walk.
558d88c1a5aSDimitry Andric     assert(NewRefSCCs.front() == RC &&
559d88c1a5aSDimitry Andric            "New current RefSCC not first in the returned list!");
5602cab237bSDimitry Andric     for (RefSCC *NewRC : llvm::reverse(make_range(std::next(NewRefSCCs.begin()),
5612cab237bSDimitry Andric                                                   NewRefSCCs.end()))) {
562d88c1a5aSDimitry Andric       assert(NewRC != RC && "Should not encounter the current RefSCC further "
563d88c1a5aSDimitry Andric                             "in the postorder list of new RefSCCs.");
564d88c1a5aSDimitry Andric       UR.RCWorklist.insert(NewRC);
5654ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "
5662cab237bSDimitry Andric                         << *NewRC << "\n");
567d88c1a5aSDimitry Andric     }
568d88c1a5aSDimitry Andric   }
569d88c1a5aSDimitry Andric 
570d88c1a5aSDimitry Andric   // Next demote all the call edges that are now ref edges. This helps make
571d88c1a5aSDimitry Andric   // the SCCs small which should minimize the work below as we don't want to
572d88c1a5aSDimitry Andric   // form cycles that this would break.
5737a7e6055SDimitry Andric   for (Node *RefTarget : DemotedCallTargets) {
5747a7e6055SDimitry Andric     SCC &TargetC = *G.lookupSCC(*RefTarget);
575d88c1a5aSDimitry Andric     RefSCC &TargetRC = TargetC.getOuterRefSCC();
576d88c1a5aSDimitry Andric 
577d88c1a5aSDimitry Andric     // The easy case is when the target RefSCC is not this RefSCC. This is
578d88c1a5aSDimitry Andric     // only supported when the target RefSCC is a child of this RefSCC.
579d88c1a5aSDimitry Andric     if (&TargetRC != RC) {
580d88c1a5aSDimitry Andric       assert(RC->isAncestorOf(TargetRC) &&
581d88c1a5aSDimitry Andric              "Cannot potentially form RefSCC cycles here!");
5827a7e6055SDimitry Andric       RC->switchOutgoingEdgeToRef(N, *RefTarget);
5834ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
5842cab237bSDimitry Andric                         << "' to '" << *RefTarget << "'\n");
585d88c1a5aSDimitry Andric       continue;
586d88c1a5aSDimitry Andric     }
587d88c1a5aSDimitry Andric 
588d88c1a5aSDimitry Andric     // We are switching an internal call edge to a ref edge. This may split up
589d88c1a5aSDimitry Andric     // some SCCs.
590d88c1a5aSDimitry Andric     if (C != &TargetC) {
591d88c1a5aSDimitry Andric       // For separate SCCs this is trivial.
5927a7e6055SDimitry Andric       RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
593d88c1a5aSDimitry Andric       continue;
594d88c1a5aSDimitry Andric     }
595d88c1a5aSDimitry Andric 
596d88c1a5aSDimitry Andric     // Now update the call graph.
5977a7e6055SDimitry Andric     C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
5982cab237bSDimitry Andric                                C, AM, UR);
599d88c1a5aSDimitry Andric   }
600d88c1a5aSDimitry Andric 
601d88c1a5aSDimitry Andric   // Now promote ref edges into call edges.
6027a7e6055SDimitry Andric   for (Node *CallTarget : PromotedRefTargets) {
6037a7e6055SDimitry Andric     SCC &TargetC = *G.lookupSCC(*CallTarget);
604d88c1a5aSDimitry Andric     RefSCC &TargetRC = TargetC.getOuterRefSCC();
605d88c1a5aSDimitry Andric 
606d88c1a5aSDimitry Andric     // The easy case is when the target RefSCC is not this RefSCC. This is
607d88c1a5aSDimitry Andric     // only supported when the target RefSCC is a child of this RefSCC.
608d88c1a5aSDimitry Andric     if (&TargetRC != RC) {
609d88c1a5aSDimitry Andric       assert(RC->isAncestorOf(TargetRC) &&
610d88c1a5aSDimitry Andric              "Cannot potentially form RefSCC cycles here!");
6117a7e6055SDimitry Andric       RC->switchOutgoingEdgeToCall(N, *CallTarget);
6124ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
6132cab237bSDimitry Andric                         << "' to '" << *CallTarget << "'\n");
614d88c1a5aSDimitry Andric       continue;
615d88c1a5aSDimitry Andric     }
6164ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
6174ba319b5SDimitry Andric                       << N << "' to '" << *CallTarget << "'\n");
618d88c1a5aSDimitry Andric 
619d88c1a5aSDimitry Andric     // Otherwise we are switching an internal ref edge to a call edge. This
620d88c1a5aSDimitry Andric     // may merge away some SCCs, and we add those to the UpdateResult. We also
621d88c1a5aSDimitry Andric     // need to make sure to update the worklist in the event SCCs have moved
622c4394386SDimitry Andric     // before the current one in the post-order sequence
623c4394386SDimitry Andric     bool HasFunctionAnalysisProxy = false;
624d88c1a5aSDimitry Andric     auto InitialSCCIndex = RC->find(*C) - RC->begin();
625c4394386SDimitry Andric     bool FormedCycle = RC->switchInternalEdgeToCall(
626c4394386SDimitry Andric         N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
627c4394386SDimitry Andric           for (SCC *MergedC : MergedSCCs) {
628c4394386SDimitry Andric             assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
629c4394386SDimitry Andric 
630c4394386SDimitry Andric             HasFunctionAnalysisProxy |=
631c4394386SDimitry Andric                 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
632c4394386SDimitry Andric                     *MergedC) != nullptr;
633c4394386SDimitry Andric 
634c4394386SDimitry Andric             // Mark that this SCC will no longer be valid.
635c4394386SDimitry Andric             UR.InvalidatedSCCs.insert(MergedC);
636c4394386SDimitry Andric 
637c4394386SDimitry Andric             // FIXME: We should really do a 'clear' here to forcibly release
638c4394386SDimitry Andric             // memory, but we don't have a good way of doing that and
639c4394386SDimitry Andric             // preserving the function analyses.
640c4394386SDimitry Andric             auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
641c4394386SDimitry Andric             PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
642c4394386SDimitry Andric             AM.invalidate(*MergedC, PA);
643c4394386SDimitry Andric           }
644c4394386SDimitry Andric         });
645c4394386SDimitry Andric 
646c4394386SDimitry Andric     // If we formed a cycle by creating this call, we need to update more data
647c4394386SDimitry Andric     // structures.
648c4394386SDimitry Andric     if (FormedCycle) {
649d88c1a5aSDimitry Andric       C = &TargetC;
650d88c1a5aSDimitry Andric       assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
651d88c1a5aSDimitry Andric 
652c4394386SDimitry Andric       // If one of the invalidated SCCs had a cached proxy to a function
653c4394386SDimitry Andric       // analysis manager, we need to create a proxy in the new current SCC as
6544ba319b5SDimitry Andric       // the invalidated SCCs had their functions moved.
655c4394386SDimitry Andric       if (HasFunctionAnalysisProxy)
656c4394386SDimitry Andric         AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
657c4394386SDimitry Andric 
658d88c1a5aSDimitry Andric       // Any analyses cached for this SCC are no longer precise as the shape
659c4394386SDimitry Andric       // has changed by introducing this cycle. However, we have taken care to
660c4394386SDimitry Andric       // update the proxies so it remains valide.
661c4394386SDimitry Andric       auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
662c4394386SDimitry Andric       PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
663c4394386SDimitry Andric       AM.invalidate(*C, PA);
664d88c1a5aSDimitry Andric     }
665d88c1a5aSDimitry Andric     auto NewSCCIndex = RC->find(*C) - RC->begin();
6662cab237bSDimitry Andric     // If we have actually moved an SCC to be topologically "below" the current
6672cab237bSDimitry Andric     // one due to merging, we will need to revisit the current SCC after
6682cab237bSDimitry Andric     // visiting those moved SCCs.
6692cab237bSDimitry Andric     //
6702cab237bSDimitry Andric     // It is critical that we *do not* revisit the current SCC unless we
6712cab237bSDimitry Andric     // actually move SCCs in the process of merging because otherwise we may
6722cab237bSDimitry Andric     // form a cycle where an SCC is split apart, merged, split, merged and so
6732cab237bSDimitry Andric     // on infinitely.
674d88c1a5aSDimitry Andric     if (InitialSCCIndex < NewSCCIndex) {
675d88c1a5aSDimitry Andric       // Put our current SCC back onto the worklist as we'll visit other SCCs
676d88c1a5aSDimitry Andric       // that are now definitively ordered prior to the current one in the
677d88c1a5aSDimitry Andric       // post-order sequence, and may end up observing more precise context to
678d88c1a5aSDimitry Andric       // optimize the current SCC.
679d88c1a5aSDimitry Andric       UR.CWorklist.insert(C);
6804ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
6812cab237bSDimitry Andric                         << "\n");
682d88c1a5aSDimitry Andric       // Enqueue in reverse order as we pop off the back of the worklist.
6832cab237bSDimitry Andric       for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
684d88c1a5aSDimitry Andric                                                   RC->begin() + NewSCCIndex))) {
685d88c1a5aSDimitry Andric         UR.CWorklist.insert(&MovedC);
6864ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
6872cab237bSDimitry Andric                           << MovedC << "\n");
688d88c1a5aSDimitry Andric       }
689d88c1a5aSDimitry Andric     }
690d88c1a5aSDimitry Andric   }
691d88c1a5aSDimitry Andric 
692d88c1a5aSDimitry Andric   assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
693d88c1a5aSDimitry Andric   assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
694d88c1a5aSDimitry Andric   assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
695d88c1a5aSDimitry Andric 
696d88c1a5aSDimitry Andric   // Record the current RefSCC and SCC for higher layers of the CGSCC pass
697d88c1a5aSDimitry Andric   // manager now that all the updates have been applied.
698d88c1a5aSDimitry Andric   if (RC != &InitialRC)
699d88c1a5aSDimitry Andric     UR.UpdatedRC = RC;
700d88c1a5aSDimitry Andric   if (C != &InitialC)
701d88c1a5aSDimitry Andric     UR.UpdatedC = C;
702d88c1a5aSDimitry Andric 
703d88c1a5aSDimitry Andric   return *C;
70491bc56edSDimitry Andric }
705