blob: e811dc3a802739a5c82a7e3552f9745d52fe2c2c [file] [log] [blame]
Chandler Carruth572e3402014-04-21 11:12:00 +00001//===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chandler Carruth572e3402014-04-21 11:12:00 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Analysis/CGSCCPassManager.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000010#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"
Chandler Carruth88823462016-08-24 09:37:14 +000018#include "llvm/IR/CallSite.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000019#include "llvm/IR/Constant.h"
Chandler Carruth89772232016-12-06 10:06:06 +000020#include "llvm/IR/InstIterator.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000021#include "llvm/IR/Instruction.h"
22#include "llvm/IR/PassManager.h"
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
26#include <algorithm>
27#include <cassert>
28#include <iterator>
Chandler Carruth572e3402014-04-21 11:12:00 +000029
Chandler Carruth19913b22017-08-11 05:47:13 +000030#define DEBUG_TYPE "cgscc"
31
Chandler Carruth572e3402014-04-21 11:12:00 +000032using namespace llvm;
33
Vedant Kumard3196742018-02-28 19:08:52 +000034// Explicit template instantiations and specialization definitions for core
Chandler Carruth6b981642016-12-10 06:34:44 +000035// template typedefs.
Chandler Carruth2a540942016-02-27 10:38:10 +000036namespace llvm {
Chandler Carruth88823462016-08-24 09:37:14 +000037
38// Explicit instantiations for the core proxy templates.
Chandler Carruth3ab2a5a2016-11-28 22:04:31 +000039template class AllAnalysesOn<LazyCallGraph::SCC>;
Chandler Carruth88823462016-08-24 09:37:14 +000040template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
41template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
42 LazyCallGraph &, CGSCCUpdateResult &>;
Chandler Carruth2a540942016-02-27 10:38:10 +000043template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
44template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
Chandler Carruth346542b2017-02-07 01:50:48 +000045 LazyCallGraph::SCC, LazyCallGraph &>;
Chandler Carruth2a540942016-02-27 10:38:10 +000046template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
Chandler Carruth88823462016-08-24 09:37:14 +000047
48/// Explicitly specialize the pass manager run method to handle call graph
49/// updates.
50template <>
51PreservedAnalyses
52PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
53 CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
54 CGSCCAnalysisManager &AM,
55 LazyCallGraph &G, CGSCCUpdateResult &UR) {
Fedor Sergeevee8d31c2018-09-20 17:08:45 +000056 // Request PassInstrumentation from analysis manager, will use it to run
57 // instrumenting callbacks for the passes later.
58 PassInstrumentation PI =
59 AM.getResult<PassInstrumentationAnalysis>(InitialC, G);
60
Chandler Carruth88823462016-08-24 09:37:14 +000061 PreservedAnalyses PA = PreservedAnalyses::all();
62
63 if (DebugLogging)
64 dbgs() << "Starting CGSCC pass manager run.\n";
65
66 // The SCC may be refined while we are running passes over it, so set up
67 // a pointer that we can update.
68 LazyCallGraph::SCC *C = &InitialC;
69
70 for (auto &Pass : Passes) {
71 if (DebugLogging)
72 dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";
73
Fedor Sergeevee8d31c2018-09-20 17:08:45 +000074 // Check the PassInstrumentation's BeforePass callbacks before running the
75 // pass, skip its execution completely if asked to (callback returns false).
76 if (!PI.runBeforePass(*Pass, *C))
77 continue;
78
Chandler Carruth88823462016-08-24 09:37:14 +000079 PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
80
Fedor Sergeeva1d95c32018-12-11 19:05:35 +000081 if (UR.InvalidatedSCCs.count(C))
82 PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass);
83 else
84 PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C);
Fedor Sergeevee8d31c2018-09-20 17:08:45 +000085
Chandler Carruth88823462016-08-24 09:37:14 +000086 // Update the SCC if necessary.
87 C = UR.UpdatedC ? UR.UpdatedC : C;
88
Chandler Carruth7376ae82017-09-14 08:33:57 +000089 // If the CGSCC pass wasn't able to provide a valid updated SCC, the
90 // current SCC may simply need to be skipped if invalid.
91 if (UR.InvalidatedSCCs.count(C)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +000092 LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
Chandler Carruth7376ae82017-09-14 08:33:57 +000093 break;
94 }
Chandler Carruth88823462016-08-24 09:37:14 +000095 // Check that we didn't miss any update scenario.
Chandler Carruth88823462016-08-24 09:37:14 +000096 assert(C->begin() != C->end() && "Cannot have an empty SCC!");
97
98 // Update the analysis manager as each pass runs and potentially
Chandler Carruth0c6efff12016-11-28 10:42:21 +000099 // invalidates analyses.
100 AM.invalidate(*C, PassPA);
Chandler Carruth88823462016-08-24 09:37:14 +0000101
102 // Finally, we intersect the final preserved analyses to compute the
103 // aggregate preserved set for this pass manager.
104 PA.intersect(std::move(PassPA));
105
106 // FIXME: Historically, the pass managers all called the LLVM context's
107 // yield function here. We don't have a generic way to acquire the
108 // context and it isn't yet clear what the right pattern is for yielding
109 // in the new pass manager so it is currently omitted.
110 // ...getContext().yield();
111 }
112
Vedant Kumard3196742018-02-28 19:08:52 +0000113 // Invalidation was handled after each pass in the above loop for the current
Chandler Carruth0c6efff12016-11-28 10:42:21 +0000114 // SCC. Therefore, the remaining analysis results in the AnalysisManager are
115 // preserved. We mark this with a set so that we don't need to inspect each
116 // one individually.
Chandler Carruthba90ae92016-12-27 08:40:39 +0000117 PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
Chandler Carruth0c6efff12016-11-28 10:42:21 +0000118
Chandler Carruth88823462016-08-24 09:37:14 +0000119 if (DebugLogging)
120 dbgs() << "Finished CGSCC pass manager run.\n";
121
122 return PA;
123}
124
Chandler Carruth6b981642016-12-10 06:34:44 +0000125bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
126 Module &M, const PreservedAnalyses &PA,
127 ModuleAnalysisManager::Invalidator &Inv) {
Chandler Carruthba90ae92016-12-27 08:40:39 +0000128 // If literally everything is preserved, we're done.
129 if (PA.areAllPreserved())
130 return false; // This is still a valid proxy.
131
Chandler Carruth6b981642016-12-10 06:34:44 +0000132 // If this proxy or the call graph is going to be invalidated, we also need
133 // to clear all the keys coming from that analysis.
134 //
135 // We also directly invalidate the FAM's module proxy if necessary, and if
136 // that proxy isn't preserved we can't preserve this proxy either. We rely on
137 // it to handle module -> function analysis invalidation in the face of
138 // structural changes and so if it's unavailable we conservatively clear the
Chandler Carruthba90ae92016-12-27 08:40:39 +0000139 // entire SCC layer as well rather than trying to do invalidation ourselves.
140 auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
141 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
Chandler Carruth6b981642016-12-10 06:34:44 +0000142 Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
143 Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
144 InnerAM->clear();
145
146 // And the proxy itself should be marked as invalid so that we can observe
147 // the new call graph. This isn't strictly necessary because we cheat
148 // above, but is still useful.
149 return true;
150 }
151
Chandler Carruthba90ae92016-12-27 08:40:39 +0000152 // Directly check if the relevant set is preserved so we can short circuit
153 // invalidating SCCs below.
154 bool AreSCCAnalysesPreserved =
155 PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
156
Chandler Carruth6b981642016-12-10 06:34:44 +0000157 // Ok, we have a graph, so we can propagate the invalidation down into it.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000158 G->buildRefSCCs();
Chandler Carruth6b981642016-12-10 06:34:44 +0000159 for (auto &RC : G->postorder_ref_sccs())
Chandler Carruthba90ae92016-12-27 08:40:39 +0000160 for (auto &C : RC) {
161 Optional<PreservedAnalyses> InnerPA;
162
163 // Check to see whether the preserved set needs to be adjusted based on
164 // module-level analysis invalidation triggering deferred invalidation
165 // for this SCC.
166 if (auto *OuterProxy =
167 InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
168 for (const auto &OuterInvalidationPair :
169 OuterProxy->getOuterInvalidations()) {
170 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
171 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
172 if (Inv.invalidate(OuterAnalysisID, M, PA)) {
173 if (!InnerPA)
174 InnerPA = PA;
175 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
176 InnerPA->abandon(InnerAnalysisID);
177 }
178 }
179
180 // Check if we needed a custom PA set. If so we'll need to run the inner
181 // invalidation.
182 if (InnerPA) {
183 InnerAM->invalidate(C, *InnerPA);
184 continue;
185 }
186
187 // Otherwise we only need to do invalidation if the original PA set didn't
188 // preserve all SCC analyses.
189 if (!AreSCCAnalysesPreserved)
190 InnerAM->invalidate(C, PA);
191 }
Chandler Carruth6b981642016-12-10 06:34:44 +0000192
193 // Return false to indicate that this result is still a valid proxy.
194 return false;
195}
196
197template <>
198CGSCCAnalysisManagerModuleProxy::Result
199CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
200 // Force the Function analysis manager to also be available so that it can
201 // be accessed in an SCC analysis and proxied onward to function passes.
202 // FIXME: It is pretty awkward to just drop the result here and assert that
203 // we can find it again later.
204 (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
205
206 return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
207}
208
209AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
210
211FunctionAnalysisManagerCGSCCProxy::Result
212FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
213 CGSCCAnalysisManager &AM,
214 LazyCallGraph &CG) {
215 // Collect the FunctionAnalysisManager from the Module layer and use that to
216 // build the proxy result.
217 //
218 // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to
219 // invalidate the function analyses.
220 auto &MAM = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG).getManager();
221 Module &M = *C.begin()->getFunction().getParent();
222 auto *FAMProxy = MAM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M);
223 assert(FAMProxy && "The CGSCC pass manager requires that the FAM module "
224 "proxy is run on the module prior to entering the CGSCC "
225 "walk.");
226
227 // Note that we special-case invalidation handling of this proxy in the CGSCC
228 // analysis manager's Module proxy. This avoids the need to do anything
229 // special here to recompute all of this if ever the FAM's module proxy goes
230 // away.
231 return Result(FAMProxy->getManager());
232}
233
234bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
235 LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
236 CGSCCAnalysisManager::Invalidator &Inv) {
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000237 // If literally everything is preserved, we're done.
238 if (PA.areAllPreserved())
239 return false; // This is still a valid proxy.
Chandler Carruth6b981642016-12-10 06:34:44 +0000240
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000241 // If this proxy isn't marked as preserved, then even if the result remains
242 // valid, the key itself may no longer be valid, so we clear everything.
243 //
244 // Note that in order to preserve this proxy, a module pass must ensure that
245 // the FAM has been completely updated to handle the deletion of functions.
246 // Specifically, any FAM-cached results for those functions need to have been
247 // forcibly cleared. When preserved, this proxy will only invalidate results
248 // cached on functions *still in the module* at the end of the module pass.
249 auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
250 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
251 for (LazyCallGraph::Node &N : C)
Sanjoy Dasdef17292017-09-28 02:45:42 +0000252 FAM->clear(N.getFunction(), N.getFunction().getName());
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000253
254 return true;
255 }
256
257 // Directly check if the relevant set is preserved.
258 bool AreFunctionAnalysesPreserved =
259 PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
260
261 // Now walk all the functions to see if any inner analysis invalidation is
262 // necessary.
263 for (LazyCallGraph::Node &N : C) {
264 Function &F = N.getFunction();
265 Optional<PreservedAnalyses> FunctionPA;
266
267 // Check to see whether the preserved set needs to be pruned based on
268 // SCC-level analysis invalidation that triggers deferred invalidation
269 // registered with the outer analysis manager proxy for this function.
270 if (auto *OuterProxy =
271 FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
272 for (const auto &OuterInvalidationPair :
273 OuterProxy->getOuterInvalidations()) {
274 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
275 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
276 if (Inv.invalidate(OuterAnalysisID, C, PA)) {
277 if (!FunctionPA)
278 FunctionPA = PA;
279 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
280 FunctionPA->abandon(InnerAnalysisID);
281 }
282 }
283
284 // Check if we needed a custom PA set, and if so we'll need to run the
285 // inner invalidation.
286 if (FunctionPA) {
287 FAM->invalidate(F, *FunctionPA);
288 continue;
289 }
290
291 // Otherwise we only need to do invalidation if the original PA set didn't
292 // preserve all function analyses.
293 if (!AreFunctionAnalysesPreserved)
294 FAM->invalidate(F, PA);
295 }
296
297 // Return false to indicate that this result is still a valid proxy.
Chandler Carruth6b981642016-12-10 06:34:44 +0000298 return false;
299}
300
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000301} // end namespace llvm
Chandler Carruth88823462016-08-24 09:37:14 +0000302
Chandler Carruth7c8964d2017-07-09 13:16:55 +0000303/// When a new SCC is created for the graph and there might be function
304/// analysis results cached for the functions now in that SCC two forms of
305/// updates are required.
306///
307/// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
308/// created so that any subsequent invalidation events to the SCC are
309/// propagated to the function analysis results cached for functions within it.
310///
311/// Second, if any of the functions within the SCC have analysis results with
312/// outer analysis dependencies, then those dependencies would point to the
313/// *wrong* SCC's analysis result. We forcibly invalidate the necessary
314/// function analyses so that they don't retain stale handles.
315static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
316 LazyCallGraph &G,
317 CGSCCAnalysisManager &AM) {
318 // Get the relevant function analysis manager.
319 auto &FAM =
320 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).getManager();
321
322 // Now walk the functions in this SCC and invalidate any function analysis
323 // results that might have outer dependencies on an SCC analysis.
324 for (LazyCallGraph::Node &N : C) {
325 Function &F = N.getFunction();
326
327 auto *OuterProxy =
328 FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
329 if (!OuterProxy)
330 // No outer analyses were queried, nothing to do.
331 continue;
332
333 // Forcibly abandon all the inner analyses with dependencies, but
334 // invalidate nothing else.
335 auto PA = PreservedAnalyses::all();
336 for (const auto &OuterInvalidationPair :
337 OuterProxy->getOuterInvalidations()) {
338 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
339 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
340 PA.abandon(InnerAnalysisID);
341 }
342
343 // Now invalidate anything we found.
344 FAM.invalidate(F, PA);
345 }
346}
347
Chandler Carruth88823462016-08-24 09:37:14 +0000348/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
349/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
350/// added SCCs.
351///
352/// The range of new SCCs must be in postorder already. The SCC they were split
353/// out of must be provided as \p C. The current node being mutated and
354/// triggering updates must be passed as \p N.
355///
356/// This function returns the SCC containing \p N. This will be either \p C if
357/// no new SCCs have been split out, or it will be the new SCC containing \p N.
358template <typename SCCRangeT>
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000359static LazyCallGraph::SCC *
Chandler Carruth88823462016-08-24 09:37:14 +0000360incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
361 LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
Chandler Carruth19913b22017-08-11 05:47:13 +0000362 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000363 using SCC = LazyCallGraph::SCC;
Chandler Carruth88823462016-08-24 09:37:14 +0000364
365 if (NewSCCRange.begin() == NewSCCRange.end())
366 return C;
367
Chandler Carruth443e57e2016-12-28 10:34:50 +0000368 // Add the current SCC to the worklist as its shape has changed.
Chandler Carruth88823462016-08-24 09:37:14 +0000369 UR.CWorklist.insert(C);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000370 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
371 << "\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000372
373 SCC *OldC = C;
Chandler Carruth88823462016-08-24 09:37:14 +0000374
375 // Update the current SCC. Note that if we have new SCCs, this must actually
376 // change the SCC.
377 assert(C != &*NewSCCRange.begin() &&
378 "Cannot insert new SCCs without changing current SCC!");
379 C = &*NewSCCRange.begin();
380 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
381
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000382 // If we had a cached FAM proxy originally, we will want to create more of
383 // them for each SCC that was split off.
384 bool NeedFAMProxy =
385 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC) != nullptr;
386
387 // We need to propagate an invalidation call to all but the newly current SCC
388 // because the outer pass manager won't do that for us after splitting them.
389 // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
Vedant Kumard3196742018-02-28 19:08:52 +0000390 // there are preserved analysis we can avoid invalidating them here for
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000391 // split-off SCCs.
392 // We know however that this will preserve any FAM proxy so go ahead and mark
393 // that.
394 PreservedAnalyses PA;
395 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
396 AM.invalidate(*OldC, PA);
397
Chandler Carruth7c8964d2017-07-09 13:16:55 +0000398 // Ensure the now-current SCC's function analyses are updated.
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000399 if (NeedFAMProxy)
Chandler Carruth7c8964d2017-07-09 13:16:55 +0000400 updateNewSCCFunctionAnalyses(*C, G, AM);
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000401
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000402 for (SCC &NewC : llvm::reverse(make_range(std::next(NewSCCRange.begin()),
403 NewSCCRange.end()))) {
Chandler Carruth88823462016-08-24 09:37:14 +0000404 assert(C != &NewC && "No need to re-visit the current SCC!");
405 assert(OldC != &NewC && "Already handled the original SCC!");
406 UR.CWorklist.insert(&NewC);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000407 LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000408
Chandler Carruth7c8964d2017-07-09 13:16:55 +0000409 // Ensure new SCCs' function analyses are updated.
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000410 if (NeedFAMProxy)
Chandler Carruth051bdb02017-07-12 09:08:11 +0000411 updateNewSCCFunctionAnalyses(NewC, G, AM);
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000412
Chandler Carruth7c8964d2017-07-09 13:16:55 +0000413 // Also propagate a normal invalidation to the new SCC as only the current
414 // will get one from the pass manager infrastructure.
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000415 AM.invalidate(NewC, PA);
Chandler Carruth88823462016-08-24 09:37:14 +0000416 }
417 return C;
418}
Chandler Carruth88823462016-08-24 09:37:14 +0000419
420LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
421 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
Chandler Carruth19913b22017-08-11 05:47:13 +0000422 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000423 using Node = LazyCallGraph::Node;
424 using Edge = LazyCallGraph::Edge;
425 using SCC = LazyCallGraph::SCC;
426 using RefSCC = LazyCallGraph::RefSCC;
Chandler Carruth88823462016-08-24 09:37:14 +0000427
428 RefSCC &InitialRC = InitialC.getOuterRefSCC();
429 SCC *C = &InitialC;
430 RefSCC *RC = &InitialRC;
431 Function &F = N.getFunction();
432
433 // Walk the function body and build up the set of retained, promoted, and
434 // demoted edges.
435 SmallVector<Constant *, 16> Worklist;
436 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000437 SmallPtrSet<Node *, 16> RetainedEdges;
438 SmallSetVector<Node *, 4> PromotedRefTargets;
439 SmallSetVector<Node *, 4> DemotedCallTargets;
Chandler Carruth89772232016-12-06 10:06:06 +0000440
Chandler Carruth88823462016-08-24 09:37:14 +0000441 // First walk the function and handle all called functions. We do this first
442 // because if there is a single call edge, whether there are ref edges is
443 // irrelevant.
Chandler Carruth89772232016-12-06 10:06:06 +0000444 for (Instruction &I : instructions(F))
445 if (auto CS = CallSite(&I))
446 if (Function *Callee = CS.getCalledFunction())
447 if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000448 Node &CalleeN = *G.lookup(*Callee);
449 Edge *E = N->lookup(CalleeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000450 // FIXME: We should really handle adding new calls. While it will
451 // make downstream usage more complex, there is no fundamental
452 // limitation and it will allow passes within the CGSCC to be a bit
453 // more flexible in what transforms they can do. Until then, we
454 // verify that new calls haven't been introduced.
455 assert(E && "No function transformations should introduce *new* "
456 "call edges! Any new calls should be modeled as "
457 "promoted existing ref edges!");
Chandler Carruth6e35c312017-08-08 10:13:23 +0000458 bool Inserted = RetainedEdges.insert(&CalleeN).second;
459 (void)Inserted;
460 assert(Inserted && "We should never visit a function twice.");
Chandler Carruth89772232016-12-06 10:06:06 +0000461 if (!E->isCall())
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000462 PromotedRefTargets.insert(&CalleeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000463 }
Chandler Carruth88823462016-08-24 09:37:14 +0000464
465 // Now walk all references.
Chandler Carruth89772232016-12-06 10:06:06 +0000466 for (Instruction &I : instructions(F))
467 for (Value *Op : I.operand_values())
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000468 if (auto *C = dyn_cast<Constant>(Op))
Chandler Carruth89772232016-12-06 10:06:06 +0000469 if (Visited.insert(C).second)
470 Worklist.push_back(C);
Chandler Carruth88823462016-08-24 09:37:14 +0000471
Chandler Carruthf59a8382017-07-15 08:08:19 +0000472 auto VisitRef = [&](Function &Referee) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000473 Node &RefereeN = *G.lookup(Referee);
474 Edge *E = N->lookup(RefereeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000475 // FIXME: Similarly to new calls, we also currently preclude
476 // introducing new references. See above for details.
477 assert(E && "No function transformations should introduce *new* ref "
478 "edges! Any new ref edges would require IPO which "
479 "function passes aren't allowed to do!");
Chandler Carruth6e35c312017-08-08 10:13:23 +0000480 bool Inserted = RetainedEdges.insert(&RefereeN).second;
481 (void)Inserted;
482 assert(Inserted && "We should never visit a function twice.");
Chandler Carruth89772232016-12-06 10:06:06 +0000483 if (E->isCall())
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000484 DemotedCallTargets.insert(&RefereeN);
Chandler Carruthf59a8382017-07-15 08:08:19 +0000485 };
486 LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
487
488 // Include synthetic reference edges to known, defined lib functions.
489 for (auto *F : G.getLibFunctions())
Chandler Carruth6e35c312017-08-08 10:13:23 +0000490 // While the list of lib functions doesn't have repeats, don't re-visit
491 // anything handled above.
492 if (!Visited.count(F))
493 VisitRef(*F);
Chandler Carruth88823462016-08-24 09:37:14 +0000494
495 // First remove all of the edges that are no longer present in this function.
Chandler Carruth23c2f442017-08-09 09:05:27 +0000496 // The first step makes these edges uniformly ref edges and accumulates them
497 // into a separate data structure so removal doesn't invalidate anything.
498 SmallVector<Node *, 4> DeadTargets;
499 for (Edge &E : *N) {
500 if (RetainedEdges.count(&E.getNode()))
Chandler Carruth88823462016-08-24 09:37:14 +0000501 continue;
Chandler Carruth88823462016-08-24 09:37:14 +0000502
Chandler Carruth23c2f442017-08-09 09:05:27 +0000503 SCC &TargetC = *G.lookupSCC(E.getNode());
504 RefSCC &TargetRC = TargetC.getOuterRefSCC();
505 if (&TargetRC == RC && E.isCall()) {
Chandler Carruth443e57e2016-12-28 10:34:50 +0000506 if (C != &TargetC) {
507 // For separate SCCs this is trivial.
Chandler Carruth23c2f442017-08-09 09:05:27 +0000508 RC->switchTrivialInternalEdgeToRef(N, E.getNode());
Chandler Carruth443e57e2016-12-28 10:34:50 +0000509 } else {
Chandler Carruth443e57e2016-12-28 10:34:50 +0000510 // Now update the call graph.
Chandler Carruth23c2f442017-08-09 09:05:27 +0000511 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
Chandler Carruth19913b22017-08-11 05:47:13 +0000512 G, N, C, AM, UR);
Chandler Carruth443e57e2016-12-28 10:34:50 +0000513 }
514 }
Chandler Carruth88823462016-08-24 09:37:14 +0000515
Chandler Carruth23c2f442017-08-09 09:05:27 +0000516 // Now that this is ready for actual removal, put it into our list.
517 DeadTargets.push_back(&E.getNode());
518 }
519 // Remove the easy cases quickly and actually pull them out of our list.
520 DeadTargets.erase(
521 llvm::remove_if(DeadTargets,
522 [&](Node *TargetN) {
523 SCC &TargetC = *G.lookupSCC(*TargetN);
524 RefSCC &TargetRC = TargetC.getOuterRefSCC();
Chandler Carruth88823462016-08-24 09:37:14 +0000525
Chandler Carruth23c2f442017-08-09 09:05:27 +0000526 // We can't trivially remove internal targets, so skip
527 // those.
528 if (&TargetRC == RC)
529 return false;
530
531 RC->removeOutgoingEdge(N, *TargetN);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000532 LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '"
533 << N << "' to '" << TargetN << "'\n");
Chandler Carruth23c2f442017-08-09 09:05:27 +0000534 return true;
535 }),
536 DeadTargets.end());
537
538 // Now do a batch removal of the internal ref edges left.
539 auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets);
540 if (!NewRefSCCs.empty()) {
541 // The old RefSCC is dead, mark it as such.
542 UR.InvalidatedRefSCCs.insert(RC);
543
544 // Note that we don't bother to invalidate analyses as ref-edge
545 // connectivity is not really observable in any way and is intended
546 // exclusively to be used for ordering of transforms rather than for
547 // analysis conclusions.
548
549 // Update RC to the "bottom".
550 assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
551 RC = &C->getOuterRefSCC();
552 assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
553
554 // The RC worklist is in reverse postorder, so we enqueue the new ones in
555 // RPO except for the one which contains the source node as that is the
556 // "bottom" we will continue processing in the bottom-up walk.
557 assert(NewRefSCCs.front() == RC &&
558 "New current RefSCC not first in the returned list!");
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000559 for (RefSCC *NewRC : llvm::reverse(make_range(std::next(NewRefSCCs.begin()),
560 NewRefSCCs.end()))) {
Chandler Carruth23c2f442017-08-09 09:05:27 +0000561 assert(NewRC != RC && "Should not encounter the current RefSCC further "
562 "in the postorder list of new RefSCCs.");
563 UR.RCWorklist.insert(NewRC);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000564 LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "
565 << *NewRC << "\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000566 }
567 }
568
569 // Next demote all the call edges that are now ref edges. This helps make
570 // the SCCs small which should minimize the work below as we don't want to
571 // form cycles that this would break.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000572 for (Node *RefTarget : DemotedCallTargets) {
573 SCC &TargetC = *G.lookupSCC(*RefTarget);
Chandler Carruth88823462016-08-24 09:37:14 +0000574 RefSCC &TargetRC = TargetC.getOuterRefSCC();
575
576 // The easy case is when the target RefSCC is not this RefSCC. This is
577 // only supported when the target RefSCC is a child of this RefSCC.
578 if (&TargetRC != RC) {
579 assert(RC->isAncestorOf(TargetRC) &&
580 "Cannot potentially form RefSCC cycles here!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000581 RC->switchOutgoingEdgeToRef(N, *RefTarget);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000582 LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
583 << "' to '" << *RefTarget << "'\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000584 continue;
585 }
586
Chandler Carruth443e57e2016-12-28 10:34:50 +0000587 // We are switching an internal call edge to a ref edge. This may split up
588 // some SCCs.
589 if (C != &TargetC) {
590 // For separate SCCs this is trivial.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000591 RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
Chandler Carruth443e57e2016-12-28 10:34:50 +0000592 continue;
593 }
594
Chandler Carruth443e57e2016-12-28 10:34:50 +0000595 // Now update the call graph.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000596 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
Chandler Carruth19913b22017-08-11 05:47:13 +0000597 C, AM, UR);
Chandler Carruth88823462016-08-24 09:37:14 +0000598 }
599
600 // Now promote ref edges into call edges.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000601 for (Node *CallTarget : PromotedRefTargets) {
602 SCC &TargetC = *G.lookupSCC(*CallTarget);
Chandler Carruth88823462016-08-24 09:37:14 +0000603 RefSCC &TargetRC = TargetC.getOuterRefSCC();
604
605 // The easy case is when the target RefSCC is not this RefSCC. This is
606 // only supported when the target RefSCC is a child of this RefSCC.
607 if (&TargetRC != RC) {
608 assert(RC->isAncestorOf(TargetRC) &&
609 "Cannot potentially form RefSCC cycles here!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000610 RC->switchOutgoingEdgeToCall(N, *CallTarget);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000611 LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
612 << "' to '" << *CallTarget << "'\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000613 continue;
614 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000615 LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
616 << N << "' to '" << *CallTarget << "'\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000617
618 // Otherwise we are switching an internal ref edge to a call edge. This
619 // may merge away some SCCs, and we add those to the UpdateResult. We also
620 // need to make sure to update the worklist in the event SCCs have moved
Chandler Carruthc213c672017-07-09 13:45:11 +0000621 // before the current one in the post-order sequence
622 bool HasFunctionAnalysisProxy = false;
Chandler Carruth88823462016-08-24 09:37:14 +0000623 auto InitialSCCIndex = RC->find(*C) - RC->begin();
Chandler Carruthc213c672017-07-09 13:45:11 +0000624 bool FormedCycle = RC->switchInternalEdgeToCall(
625 N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
626 for (SCC *MergedC : MergedSCCs) {
627 assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
628
629 HasFunctionAnalysisProxy |=
630 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
631 *MergedC) != nullptr;
632
633 // Mark that this SCC will no longer be valid.
634 UR.InvalidatedSCCs.insert(MergedC);
635
636 // FIXME: We should really do a 'clear' here to forcibly release
637 // memory, but we don't have a good way of doing that and
638 // preserving the function analyses.
639 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
640 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
641 AM.invalidate(*MergedC, PA);
642 }
643 });
644
645 // If we formed a cycle by creating this call, we need to update more data
646 // structures.
647 if (FormedCycle) {
Chandler Carruth88823462016-08-24 09:37:14 +0000648 C = &TargetC;
649 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
650
Chandler Carruthc213c672017-07-09 13:45:11 +0000651 // If one of the invalidated SCCs had a cached proxy to a function
652 // analysis manager, we need to create a proxy in the new current SCC as
Vedant Kumard3196742018-02-28 19:08:52 +0000653 // the invalidated SCCs had their functions moved.
Chandler Carruthc213c672017-07-09 13:45:11 +0000654 if (HasFunctionAnalysisProxy)
655 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
656
Chandler Carruth88823462016-08-24 09:37:14 +0000657 // Any analyses cached for this SCC are no longer precise as the shape
Chandler Carruthc213c672017-07-09 13:45:11 +0000658 // has changed by introducing this cycle. However, we have taken care to
659 // update the proxies so it remains valide.
660 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
661 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
662 AM.invalidate(*C, PA);
Chandler Carruth88823462016-08-24 09:37:14 +0000663 }
664 auto NewSCCIndex = RC->find(*C) - RC->begin();
Chandler Carruth3c6a8202017-08-01 06:40:11 +0000665 // If we have actually moved an SCC to be topologically "below" the current
666 // one due to merging, we will need to revisit the current SCC after
667 // visiting those moved SCCs.
668 //
669 // It is critical that we *do not* revisit the current SCC unless we
670 // actually move SCCs in the process of merging because otherwise we may
671 // form a cycle where an SCC is split apart, merged, split, merged and so
672 // on infinitely.
Chandler Carruth88823462016-08-24 09:37:14 +0000673 if (InitialSCCIndex < NewSCCIndex) {
674 // Put our current SCC back onto the worklist as we'll visit other SCCs
675 // that are now definitively ordered prior to the current one in the
676 // post-order sequence, and may end up observing more precise context to
677 // optimize the current SCC.
678 UR.CWorklist.insert(C);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000679 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
680 << "\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000681 // Enqueue in reverse order as we pop off the back of the worklist.
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000682 for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
683 RC->begin() + NewSCCIndex))) {
Chandler Carruth88823462016-08-24 09:37:14 +0000684 UR.CWorklist.insert(&MovedC);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000685 LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
686 << MovedC << "\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000687 }
688 }
689 }
690
691 assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
692 assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
693 assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
694
695 // Record the current RefSCC and SCC for higher layers of the CGSCC pass
696 // manager now that all the updates have been applied.
697 if (RC != &InitialRC)
698 UR.UpdatedRC = RC;
699 if (C != &InitialC)
700 UR.UpdatedC = C;
701
702 return *C;
Chandler Carruth572e3402014-04-21 11:12:00 +0000703}