xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Analysis/CGSCCPassManager.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- CGSCCPassManager.h - Call graph pass management ----------*- C++ -*-===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// This header provides classes for managing passes over SCCs of the call
11 /// graph. These passes form an important component of LLVM's interprocedural
12 /// optimizations. Because they operate on the SCCs of the call graph, and they
13 /// traverse the graph in post-order, they can effectively do pair-wise
14 /// interprocedural optimizations for all call edges in the program while
15 /// incrementally refining it and improving the context of these pair-wise
16 /// optimizations. At each call site edge, the callee has already been
17 /// optimized as much as is possible. This in turn allows very accurate
18 /// analysis of it for IPO.
19 ///
20 /// A secondary more general goal is to be able to isolate optimization on
21 /// unrelated parts of the IR module. This is useful to ensure our
22 /// optimizations are principled and don't miss oportunities where refinement
23 /// of one part of the module influences transformations in another part of the
24 /// module. But this is also useful if we want to parallelize the optimizations
25 /// across common large module graph shapes which tend to be very wide and have
26 /// large regions of unrelated cliques.
27 ///
28 /// To satisfy these goals, we use the LazyCallGraph which provides two graphs
29 /// nested inside each other (and built lazily from the bottom-up): the call
30 /// graph proper, and a reference graph. The reference graph is super set of
31 /// the call graph and is a conservative approximation of what could through
32 /// scalar or CGSCC transforms *become* the call graph. Using this allows us to
33 /// ensure we optimize functions prior to them being introduced into the call
34 /// graph by devirtualization or other technique, and thus ensures that
35 /// subsequent pair-wise interprocedural optimizations observe the optimized
36 /// form of these functions. The (potentially transitive) reference
37 /// reachability used by the reference graph is a conservative approximation
38 /// that still allows us to have independent regions of the graph.
39 ///
40 /// FIXME: There is one major drawback of the reference graph: in its naive
41 /// form it is quadratic because it contains a distinct edge for each
42 /// (potentially indirect) reference, even if are all through some common
43 /// global table of function pointers. This can be fixed in a number of ways
44 /// that essentially preserve enough of the normalization. While it isn't
45 /// expected to completely preclude the usability of this, it will need to be
46 /// addressed.
47 ///
48 ///
49 /// All of these issues are made substantially more complex in the face of
50 /// mutations to the call graph while optimization passes are being run. When
51 /// mutations to the call graph occur we want to achieve two different things:
52 ///
53 /// - We need to update the call graph in-flight and invalidate analyses
54 ///   cached on entities in the graph. Because of the cache-based analysis
55 ///   design of the pass manager, it is essential to have stable identities for
56 ///   the elements of the IR that passes traverse, and to invalidate any
57 ///   analyses cached on these elements as the mutations take place.
58 ///
59 /// - We want to preserve the incremental and post-order traversal of the
60 ///   graph even as it is refined and mutated. This means we want optimization
61 ///   to observe the most refined form of the call graph and to do so in
62 ///   post-order.
63 ///
64 /// To address this, the CGSCC manager uses both worklists that can be expanded
65 /// by passes which transform the IR, and provides invalidation tests to skip
66 /// entries that become dead. This extra data is provided to every SCC pass so
67 /// that it can carefully update the manager's traversal as the call graph
68 /// mutates.
69 ///
70 /// We also provide support for running function passes within the CGSCC walk,
71 /// and there we provide automatic update of the call graph including of the
72 /// pass manager to reflect call graph changes that fall out naturally as part
73 /// of scalar transformations.
74 ///
75 /// The patterns used to ensure the goals of post-order visitation of the fully
76 /// refined graph:
77 ///
78 /// 1) Sink toward the "bottom" as the graph is refined. This means that any
79 ///    iteration continues in some valid post-order sequence after the mutation
80 ///    has altered the structure.
81 ///
82 /// 2) Enqueue in post-order, including the current entity. If the current
83 ///    entity's shape changes, it and everything after it in post-order needs
84 ///    to be visited to observe that shape.
85 ///
86 //===----------------------------------------------------------------------===//
87 
88 #ifndef LLVM_ANALYSIS_CGSCCPASSMANAGER_H
89 #define LLVM_ANALYSIS_CGSCCPASSMANAGER_H
90 
91 #include "llvm/ADT/MapVector.h"
92 #include "llvm/Analysis/LazyCallGraph.h"
93 #include "llvm/IR/PassManager.h"
94 #include "llvm/IR/ValueHandle.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include <cassert>
97 #include <utility>
98 
99 namespace llvm {
100 
101 class Function;
102 class Value;
103 template <typename T, unsigned int N> class SmallPriorityWorklist;
104 struct CGSCCUpdateResult;
105 
106 class Module;
107 
108 // Allow debug logging in this inline function.
109 #define DEBUG_TYPE "cgscc"
110 
111 /// Extern template declaration for the analysis set for this IR unit.
112 extern template class AllAnalysesOn<LazyCallGraph::SCC>;
113 
114 extern template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
115 
116 /// The CGSCC analysis manager.
117 ///
118 /// See the documentation for the AnalysisManager template for detail
119 /// documentation. This type serves as a convenient way to refer to this
120 /// construct in the adaptors and proxies used to integrate this into the larger
121 /// pass manager infrastructure.
122 using CGSCCAnalysisManager =
123     AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
124 
125 // Explicit specialization and instantiation declarations for the pass manager.
126 // See the comments on the definition of the specialization for details on how
127 // it differs from the primary template.
128 template <>
129 PreservedAnalyses
130 PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
131             CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
132                                       CGSCCAnalysisManager &AM,
133                                       LazyCallGraph &G, CGSCCUpdateResult &UR);
134 extern template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
135                                   LazyCallGraph &, CGSCCUpdateResult &>;
136 
137 /// The CGSCC pass manager.
138 ///
139 /// See the documentation for the PassManager template for details. It runs
140 /// a sequence of SCC passes over each SCC that the manager is run over. This
141 /// type serves as a convenient way to refer to this construct.
142 using CGSCCPassManager =
143     PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
144                 CGSCCUpdateResult &>;
145 
146 /// An explicit specialization of the require analysis template pass.
147 template <typename AnalysisT>
148 struct RequireAnalysisPass<AnalysisT, LazyCallGraph::SCC, CGSCCAnalysisManager,
149                            LazyCallGraph &, CGSCCUpdateResult &>
150     : PassInfoMixin<RequireAnalysisPass<AnalysisT, LazyCallGraph::SCC,
151                                         CGSCCAnalysisManager, LazyCallGraph &,
152                                         CGSCCUpdateResult &>> {
153   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM,
154                         LazyCallGraph &CG, CGSCCUpdateResult &) {
155     (void)AM.template getResult<AnalysisT>(C, CG);
156     return PreservedAnalyses::all();
157   }
158   void printPipeline(raw_ostream &OS,
159                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
160     auto ClassName = AnalysisT::name();
161     auto PassName = MapClassName2PassName(ClassName);
162     OS << "require<" << PassName << '>';
163   }
164 };
165 
166 /// A proxy from a \c CGSCCAnalysisManager to a \c Module.
167 using CGSCCAnalysisManagerModuleProxy =
168     InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
169 
170 /// We need a specialized result for the \c CGSCCAnalysisManagerModuleProxy so
171 /// it can have access to the call graph in order to walk all the SCCs when
172 /// invalidating things.
173 template <> class CGSCCAnalysisManagerModuleProxy::Result {
174 public:
175   explicit Result(CGSCCAnalysisManager &InnerAM, LazyCallGraph &G)
176       : InnerAM(&InnerAM), G(&G) {}
177 
178   /// Accessor for the analysis manager.
179   CGSCCAnalysisManager &getManager() { return *InnerAM; }
180 
181   /// Handler for invalidation of the Module.
182   ///
183   /// If the proxy analysis itself is preserved, then we assume that the set of
184   /// SCCs in the Module hasn't changed. Thus any pointers to SCCs in the
185   /// CGSCCAnalysisManager are still valid, and we don't need to call \c clear
186   /// on the CGSCCAnalysisManager.
187   ///
188   /// Regardless of whether this analysis is marked as preserved, all of the
189   /// analyses in the \c CGSCCAnalysisManager are potentially invalidated based
190   /// on the set of preserved analyses.
191   bool invalidate(Module &M, const PreservedAnalyses &PA,
192                   ModuleAnalysisManager::Invalidator &Inv);
193 
194 private:
195   CGSCCAnalysisManager *InnerAM;
196   LazyCallGraph *G;
197 };
198 
199 /// Provide a specialized run method for the \c CGSCCAnalysisManagerModuleProxy
200 /// so it can pass the lazy call graph to the result.
201 template <>
202 CGSCCAnalysisManagerModuleProxy::Result
203 CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM);
204 
205 // Ensure the \c CGSCCAnalysisManagerModuleProxy is provided as an extern
206 // template.
207 extern template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
208 
209 extern template class OuterAnalysisManagerProxy<
210     ModuleAnalysisManager, LazyCallGraph::SCC, LazyCallGraph &>;
211 
212 /// A proxy from a \c ModuleAnalysisManager to an \c SCC.
213 using ModuleAnalysisManagerCGSCCProxy =
214     OuterAnalysisManagerProxy<ModuleAnalysisManager, LazyCallGraph::SCC,
215                               LazyCallGraph &>;
216 
217 /// Support structure for SCC passes to communicate updates the call graph back
218 /// to the CGSCC pass manager infrastructure.
219 ///
220 /// The CGSCC pass manager runs SCC passes which are allowed to update the call
221 /// graph and SCC structures. This means the structure the pass manager works
222 /// on is mutating underneath it. In order to support that, there needs to be
223 /// careful communication about the precise nature and ramifications of these
224 /// updates to the pass management infrastructure.
225 ///
226 /// All SCC passes will have to accept a reference to the management layer's
227 /// update result struct and use it to reflect the results of any CG updates
228 /// performed.
229 ///
230 /// Passes which do not change the call graph structure in any way can just
231 /// ignore this argument to their run method.
232 struct CGSCCUpdateResult {
233   /// Worklist of the SCCs queued for processing.
234   ///
235   /// When a pass refines the graph and creates new SCCs or causes them to have
236   /// a different shape or set of component functions it should add the SCCs to
237   /// this worklist so that we visit them in the refined form.
238   ///
239   /// Note that if the SCCs are part of a RefSCC that is added to the \c
240   /// RCWorklist, they don't need to be added here as visiting the RefSCC will
241   /// be sufficient to re-visit the SCCs within it.
242   ///
243   /// This worklist is in reverse post-order, as we pop off the back in order
244   /// to observe SCCs in post-order. When adding SCCs, clients should add them
245   /// in reverse post-order.
246   SmallPriorityWorklist<LazyCallGraph::SCC *, 1> &CWorklist;
247 
248   /// The set of invalidated SCCs which should be skipped if they are found
249   /// in \c CWorklist.
250   ///
251   /// This is used to quickly prune out SCCs when they get deleted and happen
252   /// to already be on the worklist. We use this primarily to avoid scanning
253   /// the list and removing entries from it.
254   SmallPtrSetImpl<LazyCallGraph::SCC *> &InvalidatedSCCs;
255 
256   /// If non-null, the updated current \c SCC being processed.
257   ///
258   /// This is set when a graph refinement takes place and the "current" point
259   /// in the graph moves "down" or earlier in the post-order walk. This will
260   /// often cause the "current" SCC to be a newly created SCC object and the
261   /// old one to be added to the above worklist. When that happens, this
262   /// pointer is non-null and can be used to continue processing the "top" of
263   /// the post-order walk.
264   LazyCallGraph::SCC *UpdatedC;
265 
266   /// Preserved analyses across SCCs.
267   ///
268   /// We specifically want to allow CGSCC passes to mutate ancestor IR
269   /// (changing both the CG structure and the function IR itself). However,
270   /// this means we need to take special care to correctly mark what analyses
271   /// are preserved *across* SCCs. We have to track this out-of-band here
272   /// because within the main `PassManager` infrastructure we need to mark
273   /// everything within an SCC as preserved in order to avoid repeatedly
274   /// invalidating the same analyses as we unnest pass managers and adaptors.
275   /// So we track the cross-SCC version of the preserved analyses here from any
276   /// code that does direct invalidation of SCC analyses, and then use it
277   /// whenever we move forward in the post-order walk of SCCs before running
278   /// passes over the new SCC.
279   PreservedAnalyses CrossSCCPA;
280 
281   /// A hacky area where the inliner can retain history about inlining
282   /// decisions that mutated the call graph's SCC structure in order to avoid
283   /// infinite inlining. See the comments in the inliner's CG update logic.
284   ///
285   /// FIXME: Keeping this here seems like a big layering issue, we should look
286   /// for a better technique.
287   SmallDenseSet<std::pair<LazyCallGraph::Node *, LazyCallGraph::SCC *>, 4>
288       &InlinedInternalEdges;
289 
290   /// Functions that a pass has considered to be dead to be removed at the end
291   /// of the call graph walk in batch.
292   SmallVector<Function *, 4> &DeadFunctions;
293 
294   /// Weak VHs to keep track of indirect calls for the purposes of detecting
295   /// devirtualization.
296   ///
297   /// This is a map to avoid having duplicate entries. If a Value is
298   /// deallocated, its corresponding WeakTrackingVH will be nulled out. When
299   /// checking if a Value is in the map or not, also check if the corresponding
300   /// WeakTrackingVH is null to avoid issues with a new Value sharing the same
301   /// address as a deallocated one.
302   SmallMapVector<Value *, WeakTrackingVH, 16> IndirectVHs;
303 };
304 
305 /// The core module pass which does a post-order walk of the SCCs and
306 /// runs a CGSCC pass over each one.
307 ///
308 /// Designed to allow composition of a CGSCCPass(Manager) and
309 /// a ModulePassManager. Note that this pass must be run with a module analysis
310 /// manager as it uses the LazyCallGraph analysis. It will also run the
311 /// \c CGSCCAnalysisManagerModuleProxy analysis prior to running the CGSCC
312 /// pass over the module to enable a \c FunctionAnalysisManager to be used
313 /// within this run safely.
314 class ModuleToPostOrderCGSCCPassAdaptor
315     : public PassInfoMixin<ModuleToPostOrderCGSCCPassAdaptor> {
316 public:
317   using PassConceptT =
318       detail::PassConcept<LazyCallGraph::SCC, CGSCCAnalysisManager,
319                           LazyCallGraph &, CGSCCUpdateResult &>;
320 
321   explicit ModuleToPostOrderCGSCCPassAdaptor(std::unique_ptr<PassConceptT> Pass)
322       : Pass(std::move(Pass)) {}
323 
324   ModuleToPostOrderCGSCCPassAdaptor(ModuleToPostOrderCGSCCPassAdaptor &&Arg)
325       : Pass(std::move(Arg.Pass)) {}
326 
327   friend void swap(ModuleToPostOrderCGSCCPassAdaptor &LHS,
328                    ModuleToPostOrderCGSCCPassAdaptor &RHS) {
329     std::swap(LHS.Pass, RHS.Pass);
330   }
331 
332   ModuleToPostOrderCGSCCPassAdaptor &
333   operator=(ModuleToPostOrderCGSCCPassAdaptor RHS) {
334     swap(*this, RHS);
335     return *this;
336   }
337 
338   /// Runs the CGSCC pass across every SCC in the module.
339   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
340 
341   void printPipeline(raw_ostream &OS,
342                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
343     OS << "cgscc(";
344     Pass->printPipeline(OS, MapClassName2PassName);
345     OS << ')';
346   }
347 
348   static bool isRequired() { return true; }
349 
350 private:
351   std::unique_ptr<PassConceptT> Pass;
352 };
353 
354 /// A function to deduce a function pass type and wrap it in the
355 /// templated adaptor.
356 template <typename CGSCCPassT>
357 ModuleToPostOrderCGSCCPassAdaptor
358 createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass) {
359   using PassModelT =
360       detail::PassModel<LazyCallGraph::SCC, CGSCCPassT, CGSCCAnalysisManager,
361                         LazyCallGraph &, CGSCCUpdateResult &>;
362   // Do not use make_unique, it causes too many template instantiations,
363   // causing terrible compile times.
364   return ModuleToPostOrderCGSCCPassAdaptor(
365       std::unique_ptr<ModuleToPostOrderCGSCCPassAdaptor::PassConceptT>(
366           new PassModelT(std::forward<CGSCCPassT>(Pass))));
367 }
368 
369 /// A proxy from a \c FunctionAnalysisManager to an \c SCC.
370 ///
371 /// When a module pass runs and triggers invalidation, both the CGSCC and
372 /// Function analysis manager proxies on the module get an invalidation event.
373 /// We don't want to fully duplicate responsibility for most of the
374 /// invalidation logic. Instead, this layer is only responsible for SCC-local
375 /// invalidation events. We work with the module's FunctionAnalysisManager to
376 /// invalidate function analyses.
377 class FunctionAnalysisManagerCGSCCProxy
378     : public AnalysisInfoMixin<FunctionAnalysisManagerCGSCCProxy> {
379 public:
380   class Result {
381   public:
382     explicit Result() : FAM(nullptr) {}
383     explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
384 
385     void updateFAM(FunctionAnalysisManager &FAM) { this->FAM = &FAM; }
386     /// Accessor for the analysis manager.
387     FunctionAnalysisManager &getManager() {
388       assert(FAM);
389       return *FAM;
390     }
391 
392     bool invalidate(LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
393                     CGSCCAnalysisManager::Invalidator &Inv);
394 
395   private:
396     FunctionAnalysisManager *FAM;
397   };
398 
399   /// Computes the \c FunctionAnalysisManager and stores it in the result proxy.
400   Result run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &);
401 
402 private:
403   friend AnalysisInfoMixin<FunctionAnalysisManagerCGSCCProxy>;
404 
405   static AnalysisKey Key;
406 };
407 
408 extern template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
409 
410 /// A proxy from a \c CGSCCAnalysisManager to a \c Function.
411 using CGSCCAnalysisManagerFunctionProxy =
412     OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
413 
414 /// Helper to update the call graph after running a function pass.
415 ///
416 /// Function passes can only mutate the call graph in specific ways. This
417 /// routine provides a helper that updates the call graph in those ways
418 /// including returning whether any changes were made and populating a CG
419 /// update result struct for the overall CGSCC walk.
420 LazyCallGraph::SCC &updateCGAndAnalysisManagerForFunctionPass(
421     LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N,
422     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
423     FunctionAnalysisManager &FAM);
424 
425 /// Helper to update the call graph after running a CGSCC pass.
426 ///
427 /// CGSCC passes can only mutate the call graph in specific ways. This
428 /// routine provides a helper that updates the call graph in those ways
429 /// including returning whether any changes were made and populating a CG
430 /// update result struct for the overall CGSCC walk.
431 LazyCallGraph::SCC &updateCGAndAnalysisManagerForCGSCCPass(
432     LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N,
433     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
434     FunctionAnalysisManager &FAM);
435 
436 /// Adaptor that maps from a SCC to its functions.
437 ///
438 /// Designed to allow composition of a FunctionPass(Manager) and
439 /// a CGSCCPassManager. Note that if this pass is constructed with a pointer
440 /// to a \c CGSCCAnalysisManager it will run the
441 /// \c FunctionAnalysisManagerCGSCCProxy analysis prior to running the function
442 /// pass over the SCC to enable a \c FunctionAnalysisManager to be used
443 /// within this run safely.
444 class CGSCCToFunctionPassAdaptor
445     : public PassInfoMixin<CGSCCToFunctionPassAdaptor> {
446 public:
447   using PassConceptT = detail::PassConcept<Function, FunctionAnalysisManager>;
448 
449   explicit CGSCCToFunctionPassAdaptor(std::unique_ptr<PassConceptT> Pass,
450                                       bool EagerlyInvalidate, bool NoRerun)
451       : Pass(std::move(Pass)), EagerlyInvalidate(EagerlyInvalidate),
452         NoRerun(NoRerun) {}
453 
454   CGSCCToFunctionPassAdaptor(CGSCCToFunctionPassAdaptor &&Arg)
455       : Pass(std::move(Arg.Pass)), EagerlyInvalidate(Arg.EagerlyInvalidate),
456         NoRerun(Arg.NoRerun) {}
457 
458   friend void swap(CGSCCToFunctionPassAdaptor &LHS,
459                    CGSCCToFunctionPassAdaptor &RHS) {
460     std::swap(LHS.Pass, RHS.Pass);
461   }
462 
463   CGSCCToFunctionPassAdaptor &operator=(CGSCCToFunctionPassAdaptor RHS) {
464     swap(*this, RHS);
465     return *this;
466   }
467 
468   /// Runs the function pass across every function in the module.
469   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM,
470                         LazyCallGraph &CG, CGSCCUpdateResult &UR);
471 
472   void printPipeline(raw_ostream &OS,
473                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
474     OS << "function";
475     if (EagerlyInvalidate || NoRerun) {
476       OS << "<";
477       if (EagerlyInvalidate)
478         OS << "eager-inv";
479       if (EagerlyInvalidate && NoRerun)
480         OS << ";";
481       if (NoRerun)
482         OS << "no-rerun";
483       OS << ">";
484     }
485     OS << '(';
486     Pass->printPipeline(OS, MapClassName2PassName);
487     OS << ')';
488   }
489 
490   static bool isRequired() { return true; }
491 
492 private:
493   std::unique_ptr<PassConceptT> Pass;
494   bool EagerlyInvalidate;
495   bool NoRerun;
496 };
497 
498 /// A function to deduce a function pass type and wrap it in the
499 /// templated adaptor.
500 template <typename FunctionPassT>
501 CGSCCToFunctionPassAdaptor
502 createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass,
503                                  bool EagerlyInvalidate = false,
504                                  bool NoRerun = false) {
505   using PassModelT =
506       detail::PassModel<Function, FunctionPassT, FunctionAnalysisManager>;
507   // Do not use make_unique, it causes too many template instantiations,
508   // causing terrible compile times.
509   return CGSCCToFunctionPassAdaptor(
510       std::unique_ptr<CGSCCToFunctionPassAdaptor::PassConceptT>(
511           new PassModelT(std::forward<FunctionPassT>(Pass))),
512       EagerlyInvalidate, NoRerun);
513 }
514 
515 // A marker to determine if function passes should be run on a function within a
516 // CGSCCToFunctionPassAdaptor. This is used to prevent running an expensive
517 // function pass (manager) on a function multiple times if SCC mutations cause a
518 // function to be visited multiple times and the function is not modified by
519 // other SCC passes.
520 class ShouldNotRunFunctionPassesAnalysis
521     : public AnalysisInfoMixin<ShouldNotRunFunctionPassesAnalysis> {
522 public:
523   static AnalysisKey Key;
524   struct Result {};
525 
526   Result run(Function &F, FunctionAnalysisManager &FAM) { return Result(); }
527 };
528 
529 /// A helper that repeats an SCC pass each time an indirect call is refined to
530 /// a direct call by that pass.
531 ///
532 /// While the CGSCC pass manager works to re-visit SCCs and RefSCCs as they
533 /// change shape, we may also want to repeat an SCC pass if it simply refines
534 /// an indirect call to a direct call, even if doing so does not alter the
535 /// shape of the graph. Note that this only pertains to direct calls to
536 /// functions where IPO across the SCC may be able to compute more precise
537 /// results. For intrinsics, we assume scalar optimizations already can fully
538 /// reason about them.
539 ///
540 /// This repetition has the potential to be very large however, as each one
541 /// might refine a single call site. As a consequence, in practice we use an
542 /// upper bound on the number of repetitions to limit things.
543 class DevirtSCCRepeatedPass : public PassInfoMixin<DevirtSCCRepeatedPass> {
544 public:
545   using PassConceptT =
546       detail::PassConcept<LazyCallGraph::SCC, CGSCCAnalysisManager,
547                           LazyCallGraph &, CGSCCUpdateResult &>;
548 
549   explicit DevirtSCCRepeatedPass(std::unique_ptr<PassConceptT> Pass,
550                                  int MaxIterations)
551       : Pass(std::move(Pass)), MaxIterations(MaxIterations) {}
552 
553   /// Runs the wrapped pass up to \c MaxIterations on the SCC, iterating
554   /// whenever an indirect call is refined.
555   PreservedAnalyses run(LazyCallGraph::SCC &InitialC, CGSCCAnalysisManager &AM,
556                         LazyCallGraph &CG, CGSCCUpdateResult &UR);
557 
558   void printPipeline(raw_ostream &OS,
559                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
560     OS << "devirt<" << MaxIterations << ">(";
561     Pass->printPipeline(OS, MapClassName2PassName);
562     OS << ')';
563   }
564 
565 private:
566   std::unique_ptr<PassConceptT> Pass;
567   int MaxIterations;
568 };
569 
570 /// A function to deduce a function pass type and wrap it in the
571 /// templated adaptor.
572 template <typename CGSCCPassT>
573 DevirtSCCRepeatedPass createDevirtSCCRepeatedPass(CGSCCPassT &&Pass,
574                                                   int MaxIterations) {
575   using PassModelT =
576       detail::PassModel<LazyCallGraph::SCC, CGSCCPassT, CGSCCAnalysisManager,
577                         LazyCallGraph &, CGSCCUpdateResult &>;
578   // Do not use make_unique, it causes too many template instantiations,
579   // causing terrible compile times.
580   return DevirtSCCRepeatedPass(
581       std::unique_ptr<DevirtSCCRepeatedPass::PassConceptT>(
582           new PassModelT(std::forward<CGSCCPassT>(Pass))),
583       MaxIterations);
584 }
585 
586 // Clear out the debug logging macro.
587 #undef DEBUG_TYPE
588 
589 } // end namespace llvm
590 
591 #endif // LLVM_ANALYSIS_CGSCCPASSMANAGER_H
592