blob: b0a7d306b264091e405fbcfec51c12ce022e15c5 [file] [log] [blame]
Chandler Carruth572e3402014-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"
Chandler Carruth88823462016-08-24 09:37:14 +000011#include "llvm/IR/CallSite.h"
Chandler Carruth89772232016-12-06 10:06:06 +000012#include "llvm/IR/InstIterator.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000013
14using namespace llvm;
15
Chandler Carruth6b981642016-12-10 06:34:44 +000016// Explicit template instantiations and specialization defininitions for core
17// template typedefs.
Chandler Carruth2a540942016-02-27 10:38:10 +000018namespace llvm {
Chandler Carruth88823462016-08-24 09:37:14 +000019
20// Explicit instantiations for the core proxy templates.
Chandler Carruth3ab2a5a2016-11-28 22:04:31 +000021template class AllAnalysesOn<LazyCallGraph::SCC>;
Chandler Carruth88823462016-08-24 09:37:14 +000022template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
23template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
24 LazyCallGraph &, CGSCCUpdateResult &>;
Chandler Carruth2a540942016-02-27 10:38:10 +000025template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
26template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
Chandler Carruth346542b2017-02-07 01:50:48 +000027 LazyCallGraph::SCC, LazyCallGraph &>;
Chandler Carruth2a540942016-02-27 10:38:10 +000028template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
Chandler Carruth88823462016-08-24 09:37:14 +000029
30/// Explicitly specialize the pass manager run method to handle call graph
31/// updates.
32template <>
33PreservedAnalyses
34PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
35 CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
36 CGSCCAnalysisManager &AM,
37 LazyCallGraph &G, CGSCCUpdateResult &UR) {
38 PreservedAnalyses PA = PreservedAnalyses::all();
39
40 if (DebugLogging)
41 dbgs() << "Starting CGSCC pass manager run.\n";
42
43 // The SCC may be refined while we are running passes over it, so set up
44 // a pointer that we can update.
45 LazyCallGraph::SCC *C = &InitialC;
46
47 for (auto &Pass : Passes) {
48 if (DebugLogging)
49 dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";
50
51 PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
52
53 // Update the SCC if necessary.
54 C = UR.UpdatedC ? UR.UpdatedC : C;
55
56 // Check that we didn't miss any update scenario.
57 assert(!UR.InvalidatedSCCs.count(C) && "Processing an invalid SCC!");
58 assert(C->begin() != C->end() && "Cannot have an empty SCC!");
59
60 // Update the analysis manager as each pass runs and potentially
Chandler Carruth0c6efff12016-11-28 10:42:21 +000061 // invalidates analyses.
62 AM.invalidate(*C, PassPA);
Chandler Carruth88823462016-08-24 09:37:14 +000063
64 // Finally, we intersect the final preserved analyses to compute the
65 // aggregate preserved set for this pass manager.
66 PA.intersect(std::move(PassPA));
67
68 // FIXME: Historically, the pass managers all called the LLVM context's
69 // yield function here. We don't have a generic way to acquire the
70 // context and it isn't yet clear what the right pattern is for yielding
71 // in the new pass manager so it is currently omitted.
72 // ...getContext().yield();
73 }
74
Chandler Carruth0c6efff12016-11-28 10:42:21 +000075 // Invaliadtion was handled after each pass in the above loop for the current
76 // SCC. Therefore, the remaining analysis results in the AnalysisManager are
77 // preserved. We mark this with a set so that we don't need to inspect each
78 // one individually.
Chandler Carruthba90ae92016-12-27 08:40:39 +000079 PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
Chandler Carruth0c6efff12016-11-28 10:42:21 +000080
Chandler Carruth88823462016-08-24 09:37:14 +000081 if (DebugLogging)
82 dbgs() << "Finished CGSCC pass manager run.\n";
83
84 return PA;
85}
86
Chandler Carruth6b981642016-12-10 06:34:44 +000087bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
88 Module &M, const PreservedAnalyses &PA,
89 ModuleAnalysisManager::Invalidator &Inv) {
Chandler Carruthba90ae92016-12-27 08:40:39 +000090 // If literally everything is preserved, we're done.
91 if (PA.areAllPreserved())
92 return false; // This is still a valid proxy.
93
Chandler Carruth6b981642016-12-10 06:34:44 +000094 // If this proxy or the call graph is going to be invalidated, we also need
95 // to clear all the keys coming from that analysis.
96 //
97 // We also directly invalidate the FAM's module proxy if necessary, and if
98 // that proxy isn't preserved we can't preserve this proxy either. We rely on
99 // it to handle module -> function analysis invalidation in the face of
100 // structural changes and so if it's unavailable we conservatively clear the
Chandler Carruthba90ae92016-12-27 08:40:39 +0000101 // entire SCC layer as well rather than trying to do invalidation ourselves.
102 auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
103 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
Chandler Carruth6b981642016-12-10 06:34:44 +0000104 Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
105 Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
106 InnerAM->clear();
107
108 // And the proxy itself should be marked as invalid so that we can observe
109 // the new call graph. This isn't strictly necessary because we cheat
110 // above, but is still useful.
111 return true;
112 }
113
Chandler Carruthba90ae92016-12-27 08:40:39 +0000114 // Directly check if the relevant set is preserved so we can short circuit
115 // invalidating SCCs below.
116 bool AreSCCAnalysesPreserved =
117 PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
118
Chandler Carruth6b981642016-12-10 06:34:44 +0000119 // Ok, we have a graph, so we can propagate the invalidation down into it.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000120 G->buildRefSCCs();
Chandler Carruth6b981642016-12-10 06:34:44 +0000121 for (auto &RC : G->postorder_ref_sccs())
Chandler Carruthba90ae92016-12-27 08:40:39 +0000122 for (auto &C : RC) {
123 Optional<PreservedAnalyses> InnerPA;
124
125 // Check to see whether the preserved set needs to be adjusted based on
126 // module-level analysis invalidation triggering deferred invalidation
127 // for this SCC.
128 if (auto *OuterProxy =
129 InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
130 for (const auto &OuterInvalidationPair :
131 OuterProxy->getOuterInvalidations()) {
132 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
133 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
134 if (Inv.invalidate(OuterAnalysisID, M, PA)) {
135 if (!InnerPA)
136 InnerPA = PA;
137 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
138 InnerPA->abandon(InnerAnalysisID);
139 }
140 }
141
142 // Check if we needed a custom PA set. If so we'll need to run the inner
143 // invalidation.
144 if (InnerPA) {
145 InnerAM->invalidate(C, *InnerPA);
146 continue;
147 }
148
149 // Otherwise we only need to do invalidation if the original PA set didn't
150 // preserve all SCC analyses.
151 if (!AreSCCAnalysesPreserved)
152 InnerAM->invalidate(C, PA);
153 }
Chandler Carruth6b981642016-12-10 06:34:44 +0000154
155 // Return false to indicate that this result is still a valid proxy.
156 return false;
157}
158
159template <>
160CGSCCAnalysisManagerModuleProxy::Result
161CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
162 // Force the Function analysis manager to also be available so that it can
163 // be accessed in an SCC analysis and proxied onward to function passes.
164 // FIXME: It is pretty awkward to just drop the result here and assert that
165 // we can find it again later.
166 (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
167
168 return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
169}
170
171AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
172
173FunctionAnalysisManagerCGSCCProxy::Result
174FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
175 CGSCCAnalysisManager &AM,
176 LazyCallGraph &CG) {
177 // Collect the FunctionAnalysisManager from the Module layer and use that to
178 // build the proxy result.
179 //
180 // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to
181 // invalidate the function analyses.
182 auto &MAM = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG).getManager();
183 Module &M = *C.begin()->getFunction().getParent();
184 auto *FAMProxy = MAM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M);
185 assert(FAMProxy && "The CGSCC pass manager requires that the FAM module "
186 "proxy is run on the module prior to entering the CGSCC "
187 "walk.");
188
189 // Note that we special-case invalidation handling of this proxy in the CGSCC
190 // analysis manager's Module proxy. This avoids the need to do anything
191 // special here to recompute all of this if ever the FAM's module proxy goes
192 // away.
193 return Result(FAMProxy->getManager());
194}
195
196bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
197 LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
198 CGSCCAnalysisManager::Invalidator &Inv) {
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000199 // If literally everything is preserved, we're done.
200 if (PA.areAllPreserved())
201 return false; // This is still a valid proxy.
Chandler Carruth6b981642016-12-10 06:34:44 +0000202
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000203 // If this proxy isn't marked as preserved, then even if the result remains
204 // valid, the key itself may no longer be valid, so we clear everything.
205 //
206 // Note that in order to preserve this proxy, a module pass must ensure that
207 // the FAM has been completely updated to handle the deletion of functions.
208 // Specifically, any FAM-cached results for those functions need to have been
209 // forcibly cleared. When preserved, this proxy will only invalidate results
210 // cached on functions *still in the module* at the end of the module pass.
211 auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
212 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
213 for (LazyCallGraph::Node &N : C)
214 FAM->clear(N.getFunction());
215
216 return true;
217 }
218
219 // Directly check if the relevant set is preserved.
220 bool AreFunctionAnalysesPreserved =
221 PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
222
223 // Now walk all the functions to see if any inner analysis invalidation is
224 // necessary.
225 for (LazyCallGraph::Node &N : C) {
226 Function &F = N.getFunction();
227 Optional<PreservedAnalyses> FunctionPA;
228
229 // Check to see whether the preserved set needs to be pruned based on
230 // SCC-level analysis invalidation that triggers deferred invalidation
231 // registered with the outer analysis manager proxy for this function.
232 if (auto *OuterProxy =
233 FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
234 for (const auto &OuterInvalidationPair :
235 OuterProxy->getOuterInvalidations()) {
236 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
237 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
238 if (Inv.invalidate(OuterAnalysisID, C, PA)) {
239 if (!FunctionPA)
240 FunctionPA = PA;
241 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
242 FunctionPA->abandon(InnerAnalysisID);
243 }
244 }
245
246 // Check if we needed a custom PA set, and if so we'll need to run the
247 // inner invalidation.
248 if (FunctionPA) {
249 FAM->invalidate(F, *FunctionPA);
250 continue;
251 }
252
253 // Otherwise we only need to do invalidation if the original PA set didn't
254 // preserve all function analyses.
255 if (!AreFunctionAnalysesPreserved)
256 FAM->invalidate(F, PA);
257 }
258
259 // Return false to indicate that this result is still a valid proxy.
Chandler Carruth6b981642016-12-10 06:34:44 +0000260 return false;
261}
262
Chandler Carruth88823462016-08-24 09:37:14 +0000263} // End llvm namespace
264
265namespace {
266/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
267/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
268/// added SCCs.
269///
270/// The range of new SCCs must be in postorder already. The SCC they were split
271/// out of must be provided as \p C. The current node being mutated and
272/// triggering updates must be passed as \p N.
273///
274/// This function returns the SCC containing \p N. This will be either \p C if
275/// no new SCCs have been split out, or it will be the new SCC containing \p N.
276template <typename SCCRangeT>
277LazyCallGraph::SCC *
278incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
279 LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
280 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
281 bool DebugLogging = false) {
282 typedef LazyCallGraph::SCC SCC;
283
284 if (NewSCCRange.begin() == NewSCCRange.end())
285 return C;
286
Chandler Carruth443e57e2016-12-28 10:34:50 +0000287 // Add the current SCC to the worklist as its shape has changed.
Chandler Carruth88823462016-08-24 09:37:14 +0000288 UR.CWorklist.insert(C);
289 if (DebugLogging)
290 dbgs() << "Enqueuing the existing SCC in the worklist:" << *C << "\n";
291
292 SCC *OldC = C;
Chandler Carruth88823462016-08-24 09:37:14 +0000293
294 // Update the current SCC. Note that if we have new SCCs, this must actually
295 // change the SCC.
296 assert(C != &*NewSCCRange.begin() &&
297 "Cannot insert new SCCs without changing current SCC!");
298 C = &*NewSCCRange.begin();
299 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
300
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000301 // If we had a cached FAM proxy originally, we will want to create more of
302 // them for each SCC that was split off.
303 bool NeedFAMProxy =
304 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC) != nullptr;
305
306 // We need to propagate an invalidation call to all but the newly current SCC
307 // because the outer pass manager won't do that for us after splitting them.
308 // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
309 // there are preserved ananalyses we can avoid invalidating them here for
310 // split-off SCCs.
311 // We know however that this will preserve any FAM proxy so go ahead and mark
312 // that.
313 PreservedAnalyses PA;
314 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
315 AM.invalidate(*OldC, PA);
316
317 // Ensure we have a proxy for the now-current SCC if needed.
318 if (NeedFAMProxy)
319 (void)AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
320
Chandler Carruth88823462016-08-24 09:37:14 +0000321 for (SCC &NewC :
322 reverse(make_range(std::next(NewSCCRange.begin()), NewSCCRange.end()))) {
323 assert(C != &NewC && "No need to re-visit the current SCC!");
324 assert(OldC != &NewC && "Already handled the original SCC!");
325 UR.CWorklist.insert(&NewC);
326 if (DebugLogging)
327 dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n";
Chandler Carruthbd9c2902017-07-09 03:59:31 +0000328
329 // Ensure new SCCs have a FAM proxy if needed.
330 if (NeedFAMProxy)
331 (void)AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
332
333 // And propagate an invalidation to the new SCC as only the current will
334 // get one from the pass manager infrastructure.
335 AM.invalidate(NewC, PA);
Chandler Carruth88823462016-08-24 09:37:14 +0000336 }
337 return C;
338}
339}
340
341LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
342 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
343 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging) {
344 typedef LazyCallGraph::Node Node;
345 typedef LazyCallGraph::Edge Edge;
346 typedef LazyCallGraph::SCC SCC;
347 typedef LazyCallGraph::RefSCC RefSCC;
348
349 RefSCC &InitialRC = InitialC.getOuterRefSCC();
350 SCC *C = &InitialC;
351 RefSCC *RC = &InitialRC;
352 Function &F = N.getFunction();
353
354 // Walk the function body and build up the set of retained, promoted, and
355 // demoted edges.
356 SmallVector<Constant *, 16> Worklist;
357 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000358 SmallPtrSet<Node *, 16> RetainedEdges;
359 SmallSetVector<Node *, 4> PromotedRefTargets;
360 SmallSetVector<Node *, 4> DemotedCallTargets;
Chandler Carruth89772232016-12-06 10:06:06 +0000361
Chandler Carruth88823462016-08-24 09:37:14 +0000362 // First walk the function and handle all called functions. We do this first
363 // because if there is a single call edge, whether there are ref edges is
364 // irrelevant.
Chandler Carruth89772232016-12-06 10:06:06 +0000365 for (Instruction &I : instructions(F))
366 if (auto CS = CallSite(&I))
367 if (Function *Callee = CS.getCalledFunction())
368 if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000369 Node &CalleeN = *G.lookup(*Callee);
370 Edge *E = N->lookup(CalleeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000371 // FIXME: We should really handle adding new calls. While it will
372 // make downstream usage more complex, there is no fundamental
373 // limitation and it will allow passes within the CGSCC to be a bit
374 // more flexible in what transforms they can do. Until then, we
375 // verify that new calls haven't been introduced.
376 assert(E && "No function transformations should introduce *new* "
377 "call edges! Any new calls should be modeled as "
378 "promoted existing ref edges!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000379 RetainedEdges.insert(&CalleeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000380 if (!E->isCall())
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000381 PromotedRefTargets.insert(&CalleeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000382 }
Chandler Carruth88823462016-08-24 09:37:14 +0000383
384 // Now walk all references.
Chandler Carruth89772232016-12-06 10:06:06 +0000385 for (Instruction &I : instructions(F))
386 for (Value *Op : I.operand_values())
387 if (Constant *C = dyn_cast<Constant>(Op))
388 if (Visited.insert(C).second)
389 Worklist.push_back(C);
Chandler Carruth88823462016-08-24 09:37:14 +0000390
Chandler Carruth89772232016-12-06 10:06:06 +0000391 LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &Referee) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000392 Node &RefereeN = *G.lookup(Referee);
393 Edge *E = N->lookup(RefereeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000394 // FIXME: Similarly to new calls, we also currently preclude
395 // introducing new references. See above for details.
396 assert(E && "No function transformations should introduce *new* ref "
397 "edges! Any new ref edges would require IPO which "
398 "function passes aren't allowed to do!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000399 RetainedEdges.insert(&RefereeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000400 if (E->isCall())
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000401 DemotedCallTargets.insert(&RefereeN);
Chandler Carruth89772232016-12-06 10:06:06 +0000402 });
Chandler Carruth88823462016-08-24 09:37:14 +0000403
404 // First remove all of the edges that are no longer present in this function.
405 // We have to build a list of dead targets first and then remove them as the
406 // data structures will all be invalidated by removing them.
407 SmallVector<PointerIntPair<Node *, 1, Edge::Kind>, 4> DeadTargets;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000408 for (Edge &E : *N)
409 if (!RetainedEdges.count(&E.getNode()))
410 DeadTargets.push_back({&E.getNode(), E.getKind()});
Chandler Carruth88823462016-08-24 09:37:14 +0000411 for (auto DeadTarget : DeadTargets) {
412 Node &TargetN = *DeadTarget.getPointer();
413 bool IsCall = DeadTarget.getInt() == Edge::Call;
414 SCC &TargetC = *G.lookupSCC(TargetN);
415 RefSCC &TargetRC = TargetC.getOuterRefSCC();
416
417 if (&TargetRC != RC) {
418 RC->removeOutgoingEdge(N, TargetN);
419 if (DebugLogging)
420 dbgs() << "Deleting outgoing edge from '" << N << "' to '" << TargetN
421 << "'\n";
422 continue;
423 }
424 if (DebugLogging)
425 dbgs() << "Deleting internal " << (IsCall ? "call" : "ref")
426 << " edge from '" << N << "' to '" << TargetN << "'\n";
427
Chandler Carruth443e57e2016-12-28 10:34:50 +0000428 if (IsCall) {
429 if (C != &TargetC) {
430 // For separate SCCs this is trivial.
431 RC->switchTrivialInternalEdgeToRef(N, TargetN);
432 } else {
Chandler Carruth443e57e2016-12-28 10:34:50 +0000433 // Now update the call graph.
434 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G,
435 N, C, AM, UR, DebugLogging);
436 }
437 }
Chandler Carruth88823462016-08-24 09:37:14 +0000438
439 auto NewRefSCCs = RC->removeInternalRefEdge(N, TargetN);
440 if (!NewRefSCCs.empty()) {
441 // Note that we don't bother to invalidate analyses as ref-edge
442 // connectivity is not really observable in any way and is intended
443 // exclusively to be used for ordering of transforms rather than for
444 // analysis conclusions.
445
446 // The RC worklist is in reverse postorder, so we first enqueue the
447 // current RefSCC as it will remain the parent of all split RefSCCs, then
448 // we enqueue the new ones in RPO except for the one which contains the
449 // source node as that is the "bottom" we will continue processing in the
450 // bottom-up walk.
451 UR.RCWorklist.insert(RC);
452 if (DebugLogging)
453 dbgs() << "Enqueuing the existing RefSCC in the update worklist: "
454 << *RC << "\n";
455 // Update the RC to the "bottom".
456 assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
457 RC = &C->getOuterRefSCC();
458 assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
Chandler Carruth66a95682016-12-20 03:32:17 +0000459 assert(NewRefSCCs.front() == RC &&
460 "New current RefSCC not first in the returned list!");
461 for (RefSCC *NewRC : reverse(
462 make_range(std::next(NewRefSCCs.begin()), NewRefSCCs.end()))) {
463 assert(NewRC != RC && "Should not encounter the current RefSCC further "
464 "in the postorder list of new RefSCCs.");
465 UR.RCWorklist.insert(NewRC);
466 if (DebugLogging)
467 dbgs() << "Enqueuing a new RefSCC in the update worklist: " << *NewRC
468 << "\n";
469 }
Chandler Carruth88823462016-08-24 09:37:14 +0000470 }
471 }
472
473 // Next demote all the call edges that are now ref edges. This helps make
474 // the SCCs small which should minimize the work below as we don't want to
475 // form cycles that this would break.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000476 for (Node *RefTarget : DemotedCallTargets) {
477 SCC &TargetC = *G.lookupSCC(*RefTarget);
Chandler Carruth88823462016-08-24 09:37:14 +0000478 RefSCC &TargetRC = TargetC.getOuterRefSCC();
479
480 // The easy case is when the target RefSCC is not this RefSCC. This is
481 // only supported when the target RefSCC is a child of this RefSCC.
482 if (&TargetRC != RC) {
483 assert(RC->isAncestorOf(TargetRC) &&
484 "Cannot potentially form RefSCC cycles here!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000485 RC->switchOutgoingEdgeToRef(N, *RefTarget);
Chandler Carruth88823462016-08-24 09:37:14 +0000486 if (DebugLogging)
487 dbgs() << "Switch outgoing call edge to a ref edge from '" << N
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000488 << "' to '" << *RefTarget << "'\n";
Chandler Carruth88823462016-08-24 09:37:14 +0000489 continue;
490 }
491
Chandler Carruth443e57e2016-12-28 10:34:50 +0000492 // We are switching an internal call edge to a ref edge. This may split up
493 // some SCCs.
494 if (C != &TargetC) {
495 // For separate SCCs this is trivial.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000496 RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
Chandler Carruth443e57e2016-12-28 10:34:50 +0000497 continue;
498 }
499
Chandler Carruth443e57e2016-12-28 10:34:50 +0000500 // Now update the call graph.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000501 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
502 C, AM, UR, DebugLogging);
Chandler Carruth88823462016-08-24 09:37:14 +0000503 }
504
505 // Now promote ref edges into call edges.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000506 for (Node *CallTarget : PromotedRefTargets) {
507 SCC &TargetC = *G.lookupSCC(*CallTarget);
Chandler Carruth88823462016-08-24 09:37:14 +0000508 RefSCC &TargetRC = TargetC.getOuterRefSCC();
509
510 // The easy case is when the target RefSCC is not this RefSCC. This is
511 // only supported when the target RefSCC is a child of this RefSCC.
512 if (&TargetRC != RC) {
513 assert(RC->isAncestorOf(TargetRC) &&
514 "Cannot potentially form RefSCC cycles here!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000515 RC->switchOutgoingEdgeToCall(N, *CallTarget);
Chandler Carruth88823462016-08-24 09:37:14 +0000516 if (DebugLogging)
517 dbgs() << "Switch outgoing ref edge to a call edge from '" << N
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000518 << "' to '" << *CallTarget << "'\n";
Chandler Carruth88823462016-08-24 09:37:14 +0000519 continue;
520 }
521 if (DebugLogging)
522 dbgs() << "Switch an internal ref edge to a call edge from '" << N
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000523 << "' to '" << *CallTarget << "'\n";
Chandler Carruth88823462016-08-24 09:37:14 +0000524
525 // Otherwise we are switching an internal ref edge to a call edge. This
526 // may merge away some SCCs, and we add those to the UpdateResult. We also
527 // need to make sure to update the worklist in the event SCCs have moved
528 // before the current one in the post-order sequence.
529 auto InitialSCCIndex = RC->find(*C) - RC->begin();
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000530 auto InvalidatedSCCs = RC->switchInternalEdgeToCall(N, *CallTarget);
Chandler Carruth88823462016-08-24 09:37:14 +0000531 if (!InvalidatedSCCs.empty()) {
532 C = &TargetC;
533 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
534
535 // Any analyses cached for this SCC are no longer precise as the shape
536 // has changed by introducing this cycle.
537 AM.invalidate(*C, PreservedAnalyses::none());
538
539 for (SCC *InvalidatedC : InvalidatedSCCs) {
540 assert(InvalidatedC != C && "Cannot invalidate the current SCC!");
541 UR.InvalidatedSCCs.insert(InvalidatedC);
542
543 // Also clear any cached analyses for the SCCs that are dead. This
544 // isn't really necessary for correctness but can release memory.
545 AM.clear(*InvalidatedC);
546 }
547 }
548 auto NewSCCIndex = RC->find(*C) - RC->begin();
549 if (InitialSCCIndex < NewSCCIndex) {
550 // Put our current SCC back onto the worklist as we'll visit other SCCs
551 // that are now definitively ordered prior to the current one in the
552 // post-order sequence, and may end up observing more precise context to
553 // optimize the current SCC.
554 UR.CWorklist.insert(C);
555 if (DebugLogging)
556 dbgs() << "Enqueuing the existing SCC in the worklist: " << *C << "\n";
557 // Enqueue in reverse order as we pop off the back of the worklist.
558 for (SCC &MovedC : reverse(make_range(RC->begin() + InitialSCCIndex,
559 RC->begin() + NewSCCIndex))) {
560 UR.CWorklist.insert(&MovedC);
561 if (DebugLogging)
562 dbgs() << "Enqueuing a newly earlier in post-order SCC: " << MovedC
563 << "\n";
564 }
565 }
566 }
567
568 assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
569 assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
570 assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
571
572 // Record the current RefSCC and SCC for higher layers of the CGSCC pass
573 // manager now that all the updates have been applied.
574 if (RC != &InitialRC)
575 UR.UpdatedRC = RC;
576 if (C != &InitialC)
577 UR.UpdatedC = C;
578
579 return *C;
Chandler Carruth572e3402014-04-21 11:12:00 +0000580}