blob: fd2292ced017d4415ef7746fc094e75974d87763 [file] [log] [blame]
Chandler Carruth57418d82014-04-21 11:12:00 +00001//===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Analysis/CGSCCPassManager.h"
Eugene Zelenko046ca042017-08-31 21:56:16 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/Optional.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/SetVector.h"
15#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/iterator_range.h"
18#include "llvm/Analysis/LazyCallGraph.h"
Chandler Carruth377af8d2016-08-24 09:37:14 +000019#include "llvm/IR/CallSite.h"
Eugene Zelenko046ca042017-08-31 21:56:16 +000020#include "llvm/IR/Constant.h"
Chandler Carruthff117bc2016-12-06 10:06:06 +000021#include "llvm/IR/InstIterator.h"
Eugene Zelenko046ca042017-08-31 21:56:16 +000022#include "llvm/IR/Instruction.h"
23#include "llvm/IR/PassManager.h"
24#include "llvm/Support/Casting.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/raw_ostream.h"
27#include <algorithm>
28#include <cassert>
29#include <iterator>
Chandler Carruth57418d82014-04-21 11:12:00 +000030
Chandler Carruth83bfb552017-08-11 05:47:13 +000031#define DEBUG_TYPE "cgscc"
32
Chandler Carruth57418d82014-04-21 11:12:00 +000033using namespace llvm;
34
Vedant Kumar06a26732018-02-28 19:08:52 +000035// Explicit template instantiations and specialization definitions for core
Chandler Carruth8bf27802016-12-10 06:34:44 +000036// template typedefs.
Chandler Carruth500af852016-02-27 10:38:10 +000037namespace llvm {
Chandler Carruth377af8d2016-08-24 09:37:14 +000038
39// Explicit instantiations for the core proxy templates.
Chandler Carruth78a68062016-11-28 22:04:31 +000040template class AllAnalysesOn<LazyCallGraph::SCC>;
Chandler Carruth377af8d2016-08-24 09:37:14 +000041template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
42template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
43 LazyCallGraph &, CGSCCUpdateResult &>;
Chandler Carruth500af852016-02-27 10:38:10 +000044template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
45template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
Chandler Carruthd53dbed2017-02-07 01:50:48 +000046 LazyCallGraph::SCC, LazyCallGraph &>;
Chandler Carruth500af852016-02-27 10:38:10 +000047template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
Chandler Carruth377af8d2016-08-24 09:37:14 +000048
49/// Explicitly specialize the pass manager run method to handle call graph
50/// updates.
51template <>
52PreservedAnalyses
53PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
54 CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
55 CGSCCAnalysisManager &AM,
56 LazyCallGraph &G, CGSCCUpdateResult &UR) {
Fedor Sergeeve6959a62018-09-20 17:08:45 +000057 // 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
Chandler Carruth377af8d2016-08-24 09:37:14 +000062 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 for (auto &Pass : Passes) {
72 if (DebugLogging)
73 dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";
74
Fedor Sergeeve6959a62018-09-20 17:08:45 +000075 // Check the PassInstrumentation's BeforePass callbacks before running the
76 // pass, skip its execution completely if asked to (callback returns false).
77 if (!PI.runBeforePass(*Pass, *C))
78 continue;
79
Chandler Carruth377af8d2016-08-24 09:37:14 +000080 PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
81
Fedor Sergeev601226c2018-12-11 19:05:35 +000082 if (UR.InvalidatedSCCs.count(C))
83 PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass);
84 else
85 PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C);
Fedor Sergeeve6959a62018-09-20 17:08:45 +000086
Chandler Carruth377af8d2016-08-24 09:37:14 +000087 // Update the SCC if necessary.
88 C = UR.UpdatedC ? UR.UpdatedC : C;
89
Chandler Carruthdbaaccc2017-09-14 08:33:57 +000090 // If the CGSCC pass wasn't able to provide a valid updated SCC, the
91 // current SCC may simply need to be skipped if invalid.
92 if (UR.InvalidatedSCCs.count(C)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +000093 LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
Chandler Carruthdbaaccc2017-09-14 08:33:57 +000094 break;
95 }
Chandler Carruth377af8d2016-08-24 09:37:14 +000096 // Check that we didn't miss any update scenario.
Chandler Carruth377af8d2016-08-24 09:37:14 +000097 assert(C->begin() != C->end() && "Cannot have an empty SCC!");
98
99 // Update the analysis manager as each pass runs and potentially
Chandler Carruth0afff632016-11-28 10:42:21 +0000100 // invalidates analyses.
101 AM.invalidate(*C, PassPA);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000102
103 // Finally, we intersect the final preserved analyses to compute the
104 // aggregate preserved set for this pass manager.
105 PA.intersect(std::move(PassPA));
106
107 // FIXME: Historically, the pass managers all called the LLVM context's
108 // yield function here. We don't have a generic way to acquire the
109 // context and it isn't yet clear what the right pattern is for yielding
110 // in the new pass manager so it is currently omitted.
111 // ...getContext().yield();
112 }
113
Vedant Kumar06a26732018-02-28 19:08:52 +0000114 // Invalidation was handled after each pass in the above loop for the current
Chandler Carruth0afff632016-11-28 10:42:21 +0000115 // SCC. Therefore, the remaining analysis results in the AnalysisManager are
116 // preserved. We mark this with a set so that we don't need to inspect each
117 // one individually.
Chandler Carruth0fc44672016-12-27 08:40:39 +0000118 PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
Chandler Carruth0afff632016-11-28 10:42:21 +0000119
Chandler Carruth377af8d2016-08-24 09:37:14 +0000120 if (DebugLogging)
121 dbgs() << "Finished CGSCC pass manager run.\n";
122
123 return PA;
124}
125
Chandler Carruth8bf27802016-12-10 06:34:44 +0000126bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
127 Module &M, const PreservedAnalyses &PA,
128 ModuleAnalysisManager::Invalidator &Inv) {
Chandler Carruth0fc44672016-12-27 08:40:39 +0000129 // If literally everything is preserved, we're done.
130 if (PA.areAllPreserved())
131 return false; // This is still a valid proxy.
132
Chandler Carruth8bf27802016-12-10 06:34:44 +0000133 // If this proxy or the call graph is going to be invalidated, we also need
134 // to clear all the keys coming from that analysis.
135 //
136 // We also directly invalidate the FAM's module proxy if necessary, and if
137 // that proxy isn't preserved we can't preserve this proxy either. We rely on
138 // it to handle module -> function analysis invalidation in the face of
139 // structural changes and so if it's unavailable we conservatively clear the
Chandler Carruth0fc44672016-12-27 08:40:39 +0000140 // entire SCC layer as well rather than trying to do invalidation ourselves.
141 auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
142 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
Chandler Carruth8bf27802016-12-10 06:34:44 +0000143 Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
144 Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
145 InnerAM->clear();
146
147 // And the proxy itself should be marked as invalid so that we can observe
148 // the new call graph. This isn't strictly necessary because we cheat
149 // above, but is still useful.
150 return true;
151 }
152
Chandler Carruth0fc44672016-12-27 08:40:39 +0000153 // Directly check if the relevant set is preserved so we can short circuit
154 // invalidating SCCs below.
155 bool AreSCCAnalysesPreserved =
156 PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
157
Chandler Carruth8bf27802016-12-10 06:34:44 +0000158 // Ok, we have a graph, so we can propagate the invalidation down into it.
Chandler Carruth3a190c32017-02-06 19:38:06 +0000159 G->buildRefSCCs();
Chandler Carruth8bf27802016-12-10 06:34:44 +0000160 for (auto &RC : G->postorder_ref_sccs())
Chandler Carruth0fc44672016-12-27 08:40:39 +0000161 for (auto &C : RC) {
162 Optional<PreservedAnalyses> InnerPA;
163
164 // Check to see whether the preserved set needs to be adjusted based on
165 // module-level analysis invalidation triggering deferred invalidation
166 // for this SCC.
167 if (auto *OuterProxy =
168 InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
169 for (const auto &OuterInvalidationPair :
170 OuterProxy->getOuterInvalidations()) {
171 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
172 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
173 if (Inv.invalidate(OuterAnalysisID, M, PA)) {
174 if (!InnerPA)
175 InnerPA = PA;
176 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
177 InnerPA->abandon(InnerAnalysisID);
178 }
179 }
180
181 // Check if we needed a custom PA set. If so we'll need to run the inner
182 // invalidation.
183 if (InnerPA) {
184 InnerAM->invalidate(C, *InnerPA);
185 continue;
186 }
187
188 // Otherwise we only need to do invalidation if the original PA set didn't
189 // preserve all SCC analyses.
190 if (!AreSCCAnalysesPreserved)
191 InnerAM->invalidate(C, PA);
192 }
Chandler Carruth8bf27802016-12-10 06:34:44 +0000193
194 // Return false to indicate that this result is still a valid proxy.
195 return false;
196}
197
198template <>
199CGSCCAnalysisManagerModuleProxy::Result
200CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
201 // Force the Function analysis manager to also be available so that it can
202 // be accessed in an SCC analysis and proxied onward to function passes.
203 // FIXME: It is pretty awkward to just drop the result here and assert that
204 // we can find it again later.
205 (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
206
207 return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
208}
209
210AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
211
212FunctionAnalysisManagerCGSCCProxy::Result
213FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
214 CGSCCAnalysisManager &AM,
215 LazyCallGraph &CG) {
216 // Collect the FunctionAnalysisManager from the Module layer and use that to
217 // build the proxy result.
218 //
219 // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to
220 // invalidate the function analyses.
221 auto &MAM = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG).getManager();
222 Module &M = *C.begin()->getFunction().getParent();
223 auto *FAMProxy = MAM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M);
224 assert(FAMProxy && "The CGSCC pass manager requires that the FAM module "
225 "proxy is run on the module prior to entering the CGSCC "
226 "walk.");
227
228 // Note that we special-case invalidation handling of this proxy in the CGSCC
229 // analysis manager's Module proxy. This avoids the need to do anything
230 // special here to recompute all of this if ever the FAM's module proxy goes
231 // away.
232 return Result(FAMProxy->getManager());
233}
234
235bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
236 LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
237 CGSCCAnalysisManager::Invalidator &Inv) {
Chandler Carruth143ef322017-07-09 03:59:31 +0000238 // If literally everything is preserved, we're done.
239 if (PA.areAllPreserved())
240 return false; // This is still a valid proxy.
Chandler Carruth8bf27802016-12-10 06:34:44 +0000241
Chandler Carruth143ef322017-07-09 03:59:31 +0000242 // If this proxy isn't marked as preserved, then even if the result remains
243 // valid, the key itself may no longer be valid, so we clear everything.
244 //
245 // Note that in order to preserve this proxy, a module pass must ensure that
246 // the FAM has been completely updated to handle the deletion of functions.
247 // Specifically, any FAM-cached results for those functions need to have been
248 // forcibly cleared. When preserved, this proxy will only invalidate results
249 // cached on functions *still in the module* at the end of the module pass.
250 auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
251 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
252 for (LazyCallGraph::Node &N : C)
Sanjoy Dase87cf872017-09-28 02:45:42 +0000253 FAM->clear(N.getFunction(), N.getFunction().getName());
Chandler Carruth143ef322017-07-09 03:59:31 +0000254
255 return true;
256 }
257
258 // Directly check if the relevant set is preserved.
259 bool AreFunctionAnalysesPreserved =
260 PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
261
262 // Now walk all the functions to see if any inner analysis invalidation is
263 // necessary.
264 for (LazyCallGraph::Node &N : C) {
265 Function &F = N.getFunction();
266 Optional<PreservedAnalyses> FunctionPA;
267
268 // Check to see whether the preserved set needs to be pruned based on
269 // SCC-level analysis invalidation that triggers deferred invalidation
270 // registered with the outer analysis manager proxy for this function.
271 if (auto *OuterProxy =
272 FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
273 for (const auto &OuterInvalidationPair :
274 OuterProxy->getOuterInvalidations()) {
275 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
276 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
277 if (Inv.invalidate(OuterAnalysisID, C, PA)) {
278 if (!FunctionPA)
279 FunctionPA = PA;
280 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
281 FunctionPA->abandon(InnerAnalysisID);
282 }
283 }
284
285 // Check if we needed a custom PA set, and if so we'll need to run the
286 // inner invalidation.
287 if (FunctionPA) {
288 FAM->invalidate(F, *FunctionPA);
289 continue;
290 }
291
292 // Otherwise we only need to do invalidation if the original PA set didn't
293 // preserve all function analyses.
294 if (!AreFunctionAnalysesPreserved)
295 FAM->invalidate(F, PA);
296 }
297
298 // Return false to indicate that this result is still a valid proxy.
Chandler Carruth8bf27802016-12-10 06:34:44 +0000299 return false;
300}
301
Eugene Zelenko046ca042017-08-31 21:56:16 +0000302} // end namespace llvm
Chandler Carruth377af8d2016-08-24 09:37:14 +0000303
Chandler Carruthb86a95f2017-07-09 13:16:55 +0000304/// When a new SCC is created for the graph and there might be function
305/// analysis results cached for the functions now in that SCC two forms of
306/// updates are required.
307///
308/// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
309/// created so that any subsequent invalidation events to the SCC are
310/// propagated to the function analysis results cached for functions within it.
311///
312/// Second, if any of the functions within the SCC have analysis results with
313/// outer analysis dependencies, then those dependencies would point to the
314/// *wrong* SCC's analysis result. We forcibly invalidate the necessary
315/// function analyses so that they don't retain stale handles.
316static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
317 LazyCallGraph &G,
318 CGSCCAnalysisManager &AM) {
319 // Get the relevant function analysis manager.
320 auto &FAM =
321 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).getManager();
322
323 // Now walk the functions in this SCC and invalidate any function analysis
324 // results that might have outer dependencies on an SCC analysis.
325 for (LazyCallGraph::Node &N : C) {
326 Function &F = N.getFunction();
327
328 auto *OuterProxy =
329 FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
330 if (!OuterProxy)
331 // No outer analyses were queried, nothing to do.
332 continue;
333
334 // Forcibly abandon all the inner analyses with dependencies, but
335 // invalidate nothing else.
336 auto PA = PreservedAnalyses::all();
337 for (const auto &OuterInvalidationPair :
338 OuterProxy->getOuterInvalidations()) {
339 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
340 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
341 PA.abandon(InnerAnalysisID);
342 }
343
344 // Now invalidate anything we found.
345 FAM.invalidate(F, PA);
346 }
347}
348
Chandler Carruth377af8d2016-08-24 09:37:14 +0000349/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
350/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
351/// added SCCs.
352///
353/// The range of new SCCs must be in postorder already. The SCC they were split
354/// out of must be provided as \p C. The current node being mutated and
355/// triggering updates must be passed as \p N.
356///
357/// This function returns the SCC containing \p N. This will be either \p C if
358/// no new SCCs have been split out, or it will be the new SCC containing \p N.
359template <typename SCCRangeT>
Eugene Zelenko046ca042017-08-31 21:56:16 +0000360static LazyCallGraph::SCC *
Chandler Carruth377af8d2016-08-24 09:37:14 +0000361incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
362 LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
Chandler Carruth83bfb552017-08-11 05:47:13 +0000363 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
Eugene Zelenko046ca042017-08-31 21:56:16 +0000364 using SCC = LazyCallGraph::SCC;
Chandler Carruth377af8d2016-08-24 09:37:14 +0000365
366 if (NewSCCRange.begin() == NewSCCRange.end())
367 return C;
368
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000369 // Add the current SCC to the worklist as its shape has changed.
Chandler Carruth377af8d2016-08-24 09:37:14 +0000370 UR.CWorklist.insert(C);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000371 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
372 << "\n");
Chandler Carruth377af8d2016-08-24 09:37:14 +0000373
374 SCC *OldC = C;
Chandler Carruth377af8d2016-08-24 09:37:14 +0000375
376 // Update the current SCC. Note that if we have new SCCs, this must actually
377 // change the SCC.
378 assert(C != &*NewSCCRange.begin() &&
379 "Cannot insert new SCCs without changing current SCC!");
380 C = &*NewSCCRange.begin();
381 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
382
Chandler Carruth143ef322017-07-09 03:59:31 +0000383 // If we had a cached FAM proxy originally, we will want to create more of
384 // them for each SCC that was split off.
385 bool NeedFAMProxy =
386 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC) != nullptr;
387
388 // We need to propagate an invalidation call to all but the newly current SCC
389 // because the outer pass manager won't do that for us after splitting them.
390 // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
Vedant Kumar06a26732018-02-28 19:08:52 +0000391 // there are preserved analysis we can avoid invalidating them here for
Chandler Carruth143ef322017-07-09 03:59:31 +0000392 // split-off SCCs.
393 // We know however that this will preserve any FAM proxy so go ahead and mark
394 // that.
395 PreservedAnalyses PA;
396 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
397 AM.invalidate(*OldC, PA);
398
Chandler Carruthb86a95f2017-07-09 13:16:55 +0000399 // Ensure the now-current SCC's function analyses are updated.
Chandler Carruth143ef322017-07-09 03:59:31 +0000400 if (NeedFAMProxy)
Chandler Carruthb86a95f2017-07-09 13:16:55 +0000401 updateNewSCCFunctionAnalyses(*C, G, AM);
Chandler Carruth143ef322017-07-09 03:59:31 +0000402
Eugene Zelenko046ca042017-08-31 21:56:16 +0000403 for (SCC &NewC : llvm::reverse(make_range(std::next(NewSCCRange.begin()),
404 NewSCCRange.end()))) {
Chandler Carruth377af8d2016-08-24 09:37:14 +0000405 assert(C != &NewC && "No need to re-visit the current SCC!");
406 assert(OldC != &NewC && "Already handled the original SCC!");
407 UR.CWorklist.insert(&NewC);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000408 LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
Chandler Carruth143ef322017-07-09 03:59:31 +0000409
Chandler Carruthb86a95f2017-07-09 13:16:55 +0000410 // Ensure new SCCs' function analyses are updated.
Chandler Carruth143ef322017-07-09 03:59:31 +0000411 if (NeedFAMProxy)
Chandler Carruth3870ce22017-07-12 09:08:11 +0000412 updateNewSCCFunctionAnalyses(NewC, G, AM);
Chandler Carruth143ef322017-07-09 03:59:31 +0000413
Chandler Carruthb86a95f2017-07-09 13:16:55 +0000414 // Also propagate a normal invalidation to the new SCC as only the current
415 // will get one from the pass manager infrastructure.
Chandler Carruth143ef322017-07-09 03:59:31 +0000416 AM.invalidate(NewC, PA);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000417 }
418 return C;
419}
Chandler Carruth377af8d2016-08-24 09:37:14 +0000420
421LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
422 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
Chandler Carruth83bfb552017-08-11 05:47:13 +0000423 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
Eugene Zelenko046ca042017-08-31 21:56:16 +0000424 using Node = LazyCallGraph::Node;
425 using Edge = LazyCallGraph::Edge;
426 using SCC = LazyCallGraph::SCC;
427 using RefSCC = LazyCallGraph::RefSCC;
Chandler Carruth377af8d2016-08-24 09:37:14 +0000428
429 RefSCC &InitialRC = InitialC.getOuterRefSCC();
430 SCC *C = &InitialC;
431 RefSCC *RC = &InitialRC;
432 Function &F = N.getFunction();
433
434 // Walk the function body and build up the set of retained, promoted, and
435 // demoted edges.
436 SmallVector<Constant *, 16> Worklist;
437 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruth396f7202017-02-09 23:24:13 +0000438 SmallPtrSet<Node *, 16> RetainedEdges;
439 SmallSetVector<Node *, 4> PromotedRefTargets;
440 SmallSetVector<Node *, 4> DemotedCallTargets;
Chandler Carruthff117bc2016-12-06 10:06:06 +0000441
Chandler Carruth377af8d2016-08-24 09:37:14 +0000442 // First walk the function and handle all called functions. We do this first
443 // because if there is a single call edge, whether there are ref edges is
444 // irrelevant.
Chandler Carruthff117bc2016-12-06 10:06:06 +0000445 for (Instruction &I : instructions(F))
446 if (auto CS = CallSite(&I))
447 if (Function *Callee = CS.getCalledFunction())
448 if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
Chandler Carruth396f7202017-02-09 23:24:13 +0000449 Node &CalleeN = *G.lookup(*Callee);
450 Edge *E = N->lookup(CalleeN);
Chandler Carruthff117bc2016-12-06 10:06:06 +0000451 // FIXME: We should really handle adding new calls. While it will
452 // make downstream usage more complex, there is no fundamental
453 // limitation and it will allow passes within the CGSCC to be a bit
454 // more flexible in what transforms they can do. Until then, we
455 // verify that new calls haven't been introduced.
456 assert(E && "No function transformations should introduce *new* "
457 "call edges! Any new calls should be modeled as "
458 "promoted existing ref edges!");
Chandler Carruth55e10a52017-08-08 10:13:23 +0000459 bool Inserted = RetainedEdges.insert(&CalleeN).second;
460 (void)Inserted;
461 assert(Inserted && "We should never visit a function twice.");
Chandler Carruthff117bc2016-12-06 10:06:06 +0000462 if (!E->isCall())
Chandler Carruth396f7202017-02-09 23:24:13 +0000463 PromotedRefTargets.insert(&CalleeN);
Chandler Carruthff117bc2016-12-06 10:06:06 +0000464 }
Chandler Carruth377af8d2016-08-24 09:37:14 +0000465
466 // Now walk all references.
Chandler Carruthff117bc2016-12-06 10:06:06 +0000467 for (Instruction &I : instructions(F))
468 for (Value *Op : I.operand_values())
Eugene Zelenko046ca042017-08-31 21:56:16 +0000469 if (auto *C = dyn_cast<Constant>(Op))
Chandler Carruthff117bc2016-12-06 10:06:06 +0000470 if (Visited.insert(C).second)
471 Worklist.push_back(C);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000472
Chandler Carruthed504112017-07-15 08:08:19 +0000473 auto VisitRef = [&](Function &Referee) {
Chandler Carruth396f7202017-02-09 23:24:13 +0000474 Node &RefereeN = *G.lookup(Referee);
475 Edge *E = N->lookup(RefereeN);
Chandler Carruthff117bc2016-12-06 10:06:06 +0000476 // FIXME: Similarly to new calls, we also currently preclude
477 // introducing new references. See above for details.
478 assert(E && "No function transformations should introduce *new* ref "
479 "edges! Any new ref edges would require IPO which "
480 "function passes aren't allowed to do!");
Chandler Carruth55e10a52017-08-08 10:13:23 +0000481 bool Inserted = RetainedEdges.insert(&RefereeN).second;
482 (void)Inserted;
483 assert(Inserted && "We should never visit a function twice.");
Chandler Carruthff117bc2016-12-06 10:06:06 +0000484 if (E->isCall())
Chandler Carruth396f7202017-02-09 23:24:13 +0000485 DemotedCallTargets.insert(&RefereeN);
Chandler Carruthed504112017-07-15 08:08:19 +0000486 };
487 LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
488
489 // Include synthetic reference edges to known, defined lib functions.
490 for (auto *F : G.getLibFunctions())
Chandler Carruth55e10a52017-08-08 10:13:23 +0000491 // While the list of lib functions doesn't have repeats, don't re-visit
492 // anything handled above.
493 if (!Visited.count(F))
494 VisitRef(*F);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000495
496 // First remove all of the edges that are no longer present in this function.
Chandler Carruthaffd1282017-08-09 09:05:27 +0000497 // The first step makes these edges uniformly ref edges and accumulates them
498 // into a separate data structure so removal doesn't invalidate anything.
499 SmallVector<Node *, 4> DeadTargets;
500 for (Edge &E : *N) {
501 if (RetainedEdges.count(&E.getNode()))
Chandler Carruth377af8d2016-08-24 09:37:14 +0000502 continue;
Chandler Carruth377af8d2016-08-24 09:37:14 +0000503
Chandler Carruthaffd1282017-08-09 09:05:27 +0000504 SCC &TargetC = *G.lookupSCC(E.getNode());
505 RefSCC &TargetRC = TargetC.getOuterRefSCC();
506 if (&TargetRC == RC && E.isCall()) {
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000507 if (C != &TargetC) {
508 // For separate SCCs this is trivial.
Chandler Carruthaffd1282017-08-09 09:05:27 +0000509 RC->switchTrivialInternalEdgeToRef(N, E.getNode());
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000510 } else {
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000511 // Now update the call graph.
Chandler Carruthaffd1282017-08-09 09:05:27 +0000512 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
Chandler Carruth83bfb552017-08-11 05:47:13 +0000513 G, N, C, AM, UR);
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000514 }
515 }
Chandler Carruth377af8d2016-08-24 09:37:14 +0000516
Chandler Carruthaffd1282017-08-09 09:05:27 +0000517 // Now that this is ready for actual removal, put it into our list.
518 DeadTargets.push_back(&E.getNode());
519 }
520 // Remove the easy cases quickly and actually pull them out of our list.
521 DeadTargets.erase(
522 llvm::remove_if(DeadTargets,
523 [&](Node *TargetN) {
524 SCC &TargetC = *G.lookupSCC(*TargetN);
525 RefSCC &TargetRC = TargetC.getOuterRefSCC();
Chandler Carruth377af8d2016-08-24 09:37:14 +0000526
Chandler Carruthaffd1282017-08-09 09:05:27 +0000527 // We can't trivially remove internal targets, so skip
528 // those.
529 if (&TargetRC == RC)
530 return false;
531
532 RC->removeOutgoingEdge(N, *TargetN);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000533 LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '"
534 << N << "' to '" << TargetN << "'\n");
Chandler Carruthaffd1282017-08-09 09:05:27 +0000535 return true;
536 }),
537 DeadTargets.end());
538
539 // Now do a batch removal of the internal ref edges left.
540 auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets);
541 if (!NewRefSCCs.empty()) {
542 // The old RefSCC is dead, mark it as such.
543 UR.InvalidatedRefSCCs.insert(RC);
544
545 // Note that we don't bother to invalidate analyses as ref-edge
546 // connectivity is not really observable in any way and is intended
547 // exclusively to be used for ordering of transforms rather than for
548 // analysis conclusions.
549
550 // Update RC to the "bottom".
551 assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
552 RC = &C->getOuterRefSCC();
553 assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
554
555 // The RC worklist is in reverse postorder, so we enqueue the new ones in
556 // RPO except for the one which contains the source node as that is the
557 // "bottom" we will continue processing in the bottom-up walk.
558 assert(NewRefSCCs.front() == RC &&
559 "New current RefSCC not first in the returned list!");
Eugene Zelenko046ca042017-08-31 21:56:16 +0000560 for (RefSCC *NewRC : llvm::reverse(make_range(std::next(NewRefSCCs.begin()),
561 NewRefSCCs.end()))) {
Chandler Carruthaffd1282017-08-09 09:05:27 +0000562 assert(NewRC != RC && "Should not encounter the current RefSCC further "
563 "in the postorder list of new RefSCCs.");
564 UR.RCWorklist.insert(NewRC);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000565 LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "
566 << *NewRC << "\n");
Chandler Carruth377af8d2016-08-24 09:37:14 +0000567 }
568 }
569
570 // Next demote all the call edges that are now ref edges. This helps make
571 // the SCCs small which should minimize the work below as we don't want to
572 // form cycles that this would break.
Chandler Carruth396f7202017-02-09 23:24:13 +0000573 for (Node *RefTarget : DemotedCallTargets) {
574 SCC &TargetC = *G.lookupSCC(*RefTarget);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000575 RefSCC &TargetRC = TargetC.getOuterRefSCC();
576
577 // The easy case is when the target RefSCC is not this RefSCC. This is
578 // only supported when the target RefSCC is a child of this RefSCC.
579 if (&TargetRC != RC) {
580 assert(RC->isAncestorOf(TargetRC) &&
581 "Cannot potentially form RefSCC cycles here!");
Chandler Carruth396f7202017-02-09 23:24:13 +0000582 RC->switchOutgoingEdgeToRef(N, *RefTarget);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000583 LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
584 << "' to '" << *RefTarget << "'\n");
Chandler Carruth377af8d2016-08-24 09:37:14 +0000585 continue;
586 }
587
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000588 // We are switching an internal call edge to a ref edge. This may split up
589 // some SCCs.
590 if (C != &TargetC) {
591 // For separate SCCs this is trivial.
Chandler Carruth396f7202017-02-09 23:24:13 +0000592 RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000593 continue;
594 }
595
Chandler Carruth6fbb41e2016-12-28 10:34:50 +0000596 // Now update the call graph.
Chandler Carruth396f7202017-02-09 23:24:13 +0000597 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
Chandler Carruth83bfb552017-08-11 05:47:13 +0000598 C, AM, UR);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000599 }
600
601 // Now promote ref edges into call edges.
Chandler Carruth396f7202017-02-09 23:24:13 +0000602 for (Node *CallTarget : PromotedRefTargets) {
603 SCC &TargetC = *G.lookupSCC(*CallTarget);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000604 RefSCC &TargetRC = TargetC.getOuterRefSCC();
605
606 // The easy case is when the target RefSCC is not this RefSCC. This is
607 // only supported when the target RefSCC is a child of this RefSCC.
608 if (&TargetRC != RC) {
609 assert(RC->isAncestorOf(TargetRC) &&
610 "Cannot potentially form RefSCC cycles here!");
Chandler Carruth396f7202017-02-09 23:24:13 +0000611 RC->switchOutgoingEdgeToCall(N, *CallTarget);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000612 LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
613 << "' to '" << *CallTarget << "'\n");
Chandler Carruth377af8d2016-08-24 09:37:14 +0000614 continue;
615 }
Nicola Zaghen0818e782018-05-14 12:53:11 +0000616 LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
617 << N << "' to '" << *CallTarget << "'\n");
Chandler Carruth377af8d2016-08-24 09:37:14 +0000618
619 // Otherwise we are switching an internal ref edge to a call edge. This
620 // may merge away some SCCs, and we add those to the UpdateResult. We also
621 // need to make sure to update the worklist in the event SCCs have moved
Chandler Carruthfe40a5a2017-07-09 13:45:11 +0000622 // before the current one in the post-order sequence
623 bool HasFunctionAnalysisProxy = false;
Chandler Carruth377af8d2016-08-24 09:37:14 +0000624 auto InitialSCCIndex = RC->find(*C) - RC->begin();
Chandler Carruthfe40a5a2017-07-09 13:45:11 +0000625 bool FormedCycle = RC->switchInternalEdgeToCall(
626 N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
627 for (SCC *MergedC : MergedSCCs) {
628 assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
629
630 HasFunctionAnalysisProxy |=
631 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
632 *MergedC) != nullptr;
633
634 // Mark that this SCC will no longer be valid.
635 UR.InvalidatedSCCs.insert(MergedC);
636
637 // FIXME: We should really do a 'clear' here to forcibly release
638 // memory, but we don't have a good way of doing that and
639 // preserving the function analyses.
640 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
641 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
642 AM.invalidate(*MergedC, PA);
643 }
644 });
645
646 // If we formed a cycle by creating this call, we need to update more data
647 // structures.
648 if (FormedCycle) {
Chandler Carruth377af8d2016-08-24 09:37:14 +0000649 C = &TargetC;
650 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
651
Chandler Carruthfe40a5a2017-07-09 13:45:11 +0000652 // If one of the invalidated SCCs had a cached proxy to a function
653 // analysis manager, we need to create a proxy in the new current SCC as
Vedant Kumar06a26732018-02-28 19:08:52 +0000654 // the invalidated SCCs had their functions moved.
Chandler Carruthfe40a5a2017-07-09 13:45:11 +0000655 if (HasFunctionAnalysisProxy)
656 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
657
Chandler Carruth377af8d2016-08-24 09:37:14 +0000658 // Any analyses cached for this SCC are no longer precise as the shape
Chandler Carruthfe40a5a2017-07-09 13:45:11 +0000659 // has changed by introducing this cycle. However, we have taken care to
660 // update the proxies so it remains valide.
661 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
662 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
663 AM.invalidate(*C, PA);
Chandler Carruth377af8d2016-08-24 09:37:14 +0000664 }
665 auto NewSCCIndex = RC->find(*C) - RC->begin();
Chandler Carruth07e7c752017-08-01 06:40:11 +0000666 // If we have actually moved an SCC to be topologically "below" the current
667 // one due to merging, we will need to revisit the current SCC after
668 // visiting those moved SCCs.
669 //
670 // It is critical that we *do not* revisit the current SCC unless we
671 // actually move SCCs in the process of merging because otherwise we may
672 // form a cycle where an SCC is split apart, merged, split, merged and so
673 // on infinitely.
Chandler Carruth377af8d2016-08-24 09:37:14 +0000674 if (InitialSCCIndex < NewSCCIndex) {
675 // Put our current SCC back onto the worklist as we'll visit other SCCs
676 // that are now definitively ordered prior to the current one in the
677 // post-order sequence, and may end up observing more precise context to
678 // optimize the current SCC.
679 UR.CWorklist.insert(C);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000680 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
681 << "\n");
Chandler Carruth377af8d2016-08-24 09:37:14 +0000682 // Enqueue in reverse order as we pop off the back of the worklist.
Eugene Zelenko046ca042017-08-31 21:56:16 +0000683 for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
684 RC->begin() + NewSCCIndex))) {
Chandler Carruth377af8d2016-08-24 09:37:14 +0000685 UR.CWorklist.insert(&MovedC);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000686 LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
687 << MovedC << "\n");
Chandler Carruth377af8d2016-08-24 09:37:14 +0000688 }
689 }
690 }
691
692 assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
693 assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
694 assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
695
696 // Record the current RefSCC and SCC for higher layers of the CGSCC pass
697 // manager now that all the updates have been applied.
698 if (RC != &InitialRC)
699 UR.UpdatedRC = RC;
700 if (C != &InitialC)
701 UR.UpdatedC = C;
702
703 return *C;
Chandler Carruth57418d82014-04-21 11:12:00 +0000704}