1 //===- 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"
11 #include "llvm/IR/CallSite.h"
12 #include "llvm/IR/InstIterator.h"
13 
14 using namespace llvm;
15 
16 // Explicit template instantiations and specialization defininitions for core
17 // template typedefs.
18 namespace llvm {
19 
20 // Explicit instantiations for the core proxy templates.
21 template class AllAnalysesOn<LazyCallGraph::SCC>;
22 template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
23 template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
24                            LazyCallGraph &, CGSCCUpdateResult &>;
25 template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
26 template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
27                                          LazyCallGraph::SCC, LazyCallGraph &>;
28 template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
29 
30 /// Explicitly specialize the pass manager run method to handle call graph
31 /// updates.
32 template <>
33 PreservedAnalyses
34 PassManager<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
61     // invalidates analyses.
62     AM.invalidate(*C, PassPA);
63 
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 
75   // 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.
79   PA.preserve<AllAnalysesOn<LazyCallGraph::SCC>>();
80 
81   if (DebugLogging)
82     dbgs() << "Finished CGSCC pass manager run.\n";
83 
84   return PA;
85 }
86 
87 bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
88     Module &M, const PreservedAnalyses &PA,
89     ModuleAnalysisManager::Invalidator &Inv) {
90   // If this proxy or the call graph is going to be invalidated, we also need
91   // to clear all the keys coming from that analysis.
92   //
93   // We also directly invalidate the FAM's module proxy if necessary, and if
94   // that proxy isn't preserved we can't preserve this proxy either. We rely on
95   // it to handle module -> function analysis invalidation in the face of
96   // structural changes and so if it's unavailable we conservatively clear the
97   // entire SCC layer as well rather than trying to do invaliadtion ourselves.
98   if (!PA.preserved<CGSCCAnalysisManagerModuleProxy>() ||
99       Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
100       Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
101     InnerAM->clear();
102 
103     // And the proxy itself should be marked as invalid so that we can observe
104     // the new call graph. This isn't strictly necessary because we cheat
105     // above, but is still useful.
106     return true;
107   }
108 
109   // Ok, we have a graph, so we can propagate the invalidation down into it.
110   for (auto &RC : G->postorder_ref_sccs())
111     for (auto &C : RC)
112       InnerAM->invalidate(C, PA);
113 
114   // Return false to indicate that this result is still a valid proxy.
115   return false;
116 }
117 
118 template <>
119 CGSCCAnalysisManagerModuleProxy::Result
120 CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
121   // Force the Function analysis manager to also be available so that it can
122   // be accessed in an SCC analysis and proxied onward to function passes.
123   // FIXME: It is pretty awkward to just drop the result here and assert that
124   // we can find it again later.
125   (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
126 
127   return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
128 }
129 
130 AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
131 
132 FunctionAnalysisManagerCGSCCProxy::Result
133 FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
134                                        CGSCCAnalysisManager &AM,
135                                        LazyCallGraph &CG) {
136   // Collect the FunctionAnalysisManager from the Module layer and use that to
137   // build the proxy result.
138   //
139   // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to
140   // invalidate the function analyses.
141   auto &MAM = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG).getManager();
142   Module &M = *C.begin()->getFunction().getParent();
143   auto *FAMProxy = MAM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M);
144   assert(FAMProxy && "The CGSCC pass manager requires that the FAM module "
145                      "proxy is run on the module prior to entering the CGSCC "
146                      "walk.");
147 
148   // Note that we special-case invalidation handling of this proxy in the CGSCC
149   // analysis manager's Module proxy. This avoids the need to do anything
150   // special here to recompute all of this if ever the FAM's module proxy goes
151   // away.
152   return Result(FAMProxy->getManager());
153 }
154 
155 bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
156     LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
157     CGSCCAnalysisManager::Invalidator &Inv) {
158   for (LazyCallGraph::Node &N : C)
159     FAM->invalidate(N.getFunction(), PA);
160 
161   // This proxy doesn't need to handle invalidation itself. Instead, the
162   // module-level CGSCC proxy handles it above by ensuring that if the
163   // module-level FAM proxy becomes invalid the entire SCC layer, which
164   // includes this proxy, is cleared.
165   return false;
166 }
167 
168 } // End llvm namespace
169 
170 namespace {
171 /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
172 /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
173 /// added SCCs.
174 ///
175 /// The range of new SCCs must be in postorder already. The SCC they were split
176 /// out of must be provided as \p C. The current node being mutated and
177 /// triggering updates must be passed as \p N.
178 ///
179 /// This function returns the SCC containing \p N. This will be either \p C if
180 /// no new SCCs have been split out, or it will be the new SCC containing \p N.
181 template <typename SCCRangeT>
182 LazyCallGraph::SCC *
183 incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
184                        LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
185                        CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
186                        bool DebugLogging = false) {
187   typedef LazyCallGraph::SCC SCC;
188 
189   if (NewSCCRange.begin() == NewSCCRange.end())
190     return C;
191 
192   // Invalidate the analyses of the current SCC and add it to the worklist since
193   // it has changed its shape.
194   AM.invalidate(*C, PreservedAnalyses::none());
195   UR.CWorklist.insert(C);
196   if (DebugLogging)
197     dbgs() << "Enqueuing the existing SCC in the worklist:" << *C << "\n";
198 
199   SCC *OldC = C;
200   (void)OldC;
201 
202   // Update the current SCC. Note that if we have new SCCs, this must actually
203   // change the SCC.
204   assert(C != &*NewSCCRange.begin() &&
205          "Cannot insert new SCCs without changing current SCC!");
206   C = &*NewSCCRange.begin();
207   assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
208 
209   for (SCC &NewC :
210        reverse(make_range(std::next(NewSCCRange.begin()), NewSCCRange.end()))) {
211     assert(C != &NewC && "No need to re-visit the current SCC!");
212     assert(OldC != &NewC && "Already handled the original SCC!");
213     UR.CWorklist.insert(&NewC);
214     if (DebugLogging)
215       dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n";
216   }
217   return C;
218 }
219 }
220 
221 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
222     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
223     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging) {
224   typedef LazyCallGraph::Node Node;
225   typedef LazyCallGraph::Edge Edge;
226   typedef LazyCallGraph::SCC SCC;
227   typedef LazyCallGraph::RefSCC RefSCC;
228 
229   RefSCC &InitialRC = InitialC.getOuterRefSCC();
230   SCC *C = &InitialC;
231   RefSCC *RC = &InitialRC;
232   Function &F = N.getFunction();
233 
234   // Walk the function body and build up the set of retained, promoted, and
235   // demoted edges.
236   SmallVector<Constant *, 16> Worklist;
237   SmallPtrSet<Constant *, 16> Visited;
238   SmallPtrSet<Function *, 16> RetainedEdges;
239   SmallSetVector<Function *, 4> PromotedRefTargets;
240   SmallSetVector<Function *, 4> DemotedCallTargets;
241 
242   // First walk the function and handle all called functions. We do this first
243   // because if there is a single call edge, whether there are ref edges is
244   // irrelevant.
245   for (Instruction &I : instructions(F))
246     if (auto CS = CallSite(&I))
247       if (Function *Callee = CS.getCalledFunction())
248         if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
249           const Edge *E = N.lookup(*Callee);
250           // FIXME: We should really handle adding new calls. While it will
251           // make downstream usage more complex, there is no fundamental
252           // limitation and it will allow passes within the CGSCC to be a bit
253           // more flexible in what transforms they can do. Until then, we
254           // verify that new calls haven't been introduced.
255           assert(E && "No function transformations should introduce *new* "
256                       "call edges! Any new calls should be modeled as "
257                       "promoted existing ref edges!");
258           RetainedEdges.insert(Callee);
259           if (!E->isCall())
260             PromotedRefTargets.insert(Callee);
261         }
262 
263   // Now walk all references.
264   for (Instruction &I : instructions(F))
265     for (Value *Op : I.operand_values())
266       if (Constant *C = dyn_cast<Constant>(Op))
267         if (Visited.insert(C).second)
268           Worklist.push_back(C);
269 
270   LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &Referee) {
271     const Edge *E = N.lookup(Referee);
272     // FIXME: Similarly to new calls, we also currently preclude
273     // introducing new references. See above for details.
274     assert(E && "No function transformations should introduce *new* ref "
275                 "edges! Any new ref edges would require IPO which "
276                 "function passes aren't allowed to do!");
277     RetainedEdges.insert(&Referee);
278     if (E->isCall())
279       DemotedCallTargets.insert(&Referee);
280   });
281 
282   // First remove all of the edges that are no longer present in this function.
283   // We have to build a list of dead targets first and then remove them as the
284   // data structures will all be invalidated by removing them.
285   SmallVector<PointerIntPair<Node *, 1, Edge::Kind>, 4> DeadTargets;
286   for (Edge &E : N)
287     if (!RetainedEdges.count(&E.getFunction()))
288       DeadTargets.push_back({E.getNode(), E.getKind()});
289   for (auto DeadTarget : DeadTargets) {
290     Node &TargetN = *DeadTarget.getPointer();
291     bool IsCall = DeadTarget.getInt() == Edge::Call;
292     SCC &TargetC = *G.lookupSCC(TargetN);
293     RefSCC &TargetRC = TargetC.getOuterRefSCC();
294 
295     if (&TargetRC != RC) {
296       RC->removeOutgoingEdge(N, TargetN);
297       if (DebugLogging)
298         dbgs() << "Deleting outgoing edge from '" << N << "' to '" << TargetN
299                << "'\n";
300       continue;
301     }
302     if (DebugLogging)
303       dbgs() << "Deleting internal " << (IsCall ? "call" : "ref")
304              << " edge from '" << N << "' to '" << TargetN << "'\n";
305 
306     if (IsCall)
307       C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N,
308                                  C, AM, UR, DebugLogging);
309 
310     auto NewRefSCCs = RC->removeInternalRefEdge(N, TargetN);
311     if (!NewRefSCCs.empty()) {
312       // Note that we don't bother to invalidate analyses as ref-edge
313       // connectivity is not really observable in any way and is intended
314       // exclusively to be used for ordering of transforms rather than for
315       // analysis conclusions.
316 
317       // The RC worklist is in reverse postorder, so we first enqueue the
318       // current RefSCC as it will remain the parent of all split RefSCCs, then
319       // we enqueue the new ones in RPO except for the one which contains the
320       // source node as that is the "bottom" we will continue processing in the
321       // bottom-up walk.
322       UR.RCWorklist.insert(RC);
323       if (DebugLogging)
324         dbgs() << "Enqueuing the existing RefSCC in the update worklist: "
325                << *RC << "\n";
326       // Update the RC to the "bottom".
327       assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
328       RC = &C->getOuterRefSCC();
329       assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
330       assert(NewRefSCCs.front() == RC &&
331              "New current RefSCC not first in the returned list!");
332       for (RefSCC *NewRC : reverse(
333                make_range(std::next(NewRefSCCs.begin()), NewRefSCCs.end()))) {
334         assert(NewRC != RC && "Should not encounter the current RefSCC further "
335                               "in the postorder list of new RefSCCs.");
336         UR.RCWorklist.insert(NewRC);
337         if (DebugLogging)
338           dbgs() << "Enqueuing a new RefSCC in the update worklist: " << *NewRC
339                  << "\n";
340       }
341     }
342   }
343 
344   // Next demote all the call edges that are now ref edges. This helps make
345   // the SCCs small which should minimize the work below as we don't want to
346   // form cycles that this would break.
347   for (Function *RefTarget : DemotedCallTargets) {
348     Node &TargetN = *G.lookup(*RefTarget);
349     SCC &TargetC = *G.lookupSCC(TargetN);
350     RefSCC &TargetRC = TargetC.getOuterRefSCC();
351 
352     // The easy case is when the target RefSCC is not this RefSCC. This is
353     // only supported when the target RefSCC is a child of this RefSCC.
354     if (&TargetRC != RC) {
355       assert(RC->isAncestorOf(TargetRC) &&
356              "Cannot potentially form RefSCC cycles here!");
357       RC->switchOutgoingEdgeToRef(N, TargetN);
358       if (DebugLogging)
359         dbgs() << "Switch outgoing call edge to a ref edge from '" << N
360                << "' to '" << TargetN << "'\n";
361       continue;
362     }
363 
364     // Otherwise we are switching an internal call edge to a ref edge. This
365     // may split up some SCCs.
366     C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N, C,
367                                AM, UR, DebugLogging);
368   }
369 
370   // Now promote ref edges into call edges.
371   for (Function *CallTarget : PromotedRefTargets) {
372     Node &TargetN = *G.lookup(*CallTarget);
373     SCC &TargetC = *G.lookupSCC(TargetN);
374     RefSCC &TargetRC = TargetC.getOuterRefSCC();
375 
376     // The easy case is when the target RefSCC is not this RefSCC. This is
377     // only supported when the target RefSCC is a child of this RefSCC.
378     if (&TargetRC != RC) {
379       assert(RC->isAncestorOf(TargetRC) &&
380              "Cannot potentially form RefSCC cycles here!");
381       RC->switchOutgoingEdgeToCall(N, TargetN);
382       if (DebugLogging)
383         dbgs() << "Switch outgoing ref edge to a call edge from '" << N
384                << "' to '" << TargetN << "'\n";
385       continue;
386     }
387     if (DebugLogging)
388       dbgs() << "Switch an internal ref edge to a call edge from '" << N
389              << "' to '" << TargetN << "'\n";
390 
391     // Otherwise we are switching an internal ref edge to a call edge. This
392     // may merge away some SCCs, and we add those to the UpdateResult. We also
393     // need to make sure to update the worklist in the event SCCs have moved
394     // before the current one in the post-order sequence.
395     auto InitialSCCIndex = RC->find(*C) - RC->begin();
396     auto InvalidatedSCCs = RC->switchInternalEdgeToCall(N, TargetN);
397     if (!InvalidatedSCCs.empty()) {
398       C = &TargetC;
399       assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
400 
401       // Any analyses cached for this SCC are no longer precise as the shape
402       // has changed by introducing this cycle.
403       AM.invalidate(*C, PreservedAnalyses::none());
404 
405       for (SCC *InvalidatedC : InvalidatedSCCs) {
406         assert(InvalidatedC != C && "Cannot invalidate the current SCC!");
407         UR.InvalidatedSCCs.insert(InvalidatedC);
408 
409         // Also clear any cached analyses for the SCCs that are dead. This
410         // isn't really necessary for correctness but can release memory.
411         AM.clear(*InvalidatedC);
412       }
413     }
414     auto NewSCCIndex = RC->find(*C) - RC->begin();
415     if (InitialSCCIndex < NewSCCIndex) {
416       // Put our current SCC back onto the worklist as we'll visit other SCCs
417       // that are now definitively ordered prior to the current one in the
418       // post-order sequence, and may end up observing more precise context to
419       // optimize the current SCC.
420       UR.CWorklist.insert(C);
421       if (DebugLogging)
422         dbgs() << "Enqueuing the existing SCC in the worklist: " << *C << "\n";
423       // Enqueue in reverse order as we pop off the back of the worklist.
424       for (SCC &MovedC : reverse(make_range(RC->begin() + InitialSCCIndex,
425                                             RC->begin() + NewSCCIndex))) {
426         UR.CWorklist.insert(&MovedC);
427         if (DebugLogging)
428           dbgs() << "Enqueuing a newly earlier in post-order SCC: " << MovedC
429                  << "\n";
430       }
431     }
432   }
433 
434   assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
435   assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
436   assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
437 
438   // Record the current RefSCC and SCC for higher layers of the CGSCC pass
439   // manager now that all the updates have been applied.
440   if (RC != &InitialRC)
441     UR.UpdatedRC = RC;
442   if (C != &InitialC)
443     UR.UpdatedC = C;
444 
445   return *C;
446 }
447