LLVM 19.0.0git
PassManager.h
Go to the documentation of this file.
1//===- PassManager.h - Pass management infrastructure -----------*- 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 defines various interfaces for pass management in LLVM. There
11/// is no "pass" interface in LLVM per se. Instead, an instance of any class
12/// which supports a method to 'run' it over a unit of IR can be used as
13/// a pass. A pass manager is generally a tool to collect a sequence of passes
14/// which run over a particular IR construct, and run each of them in sequence
15/// over each such construct in the containing IR construct. As there is no
16/// containing IR construct for a Module, a manager for passes over modules
17/// forms the base case which runs its managed passes in sequence over the
18/// single module provided.
19///
20/// The core IR library provides managers for running passes over
21/// modules and functions.
22///
23/// * FunctionPassManager can run over a Module, runs each pass over
24/// a Function.
25/// * ModulePassManager must be directly run, runs each pass over the Module.
26///
27/// Note that the implementations of the pass managers use concept-based
28/// polymorphism as outlined in the "Value Semantics and Concept-based
29/// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
30/// Class of Evil") by Sean Parent:
31/// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
32/// * http://www.youtube.com/watch?v=_BpMYeUFXv8
33/// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
34///
35//===----------------------------------------------------------------------===//
36
37#ifndef LLVM_IR_PASSMANAGER_H
38#define LLVM_IR_PASSMANAGER_H
39
40#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringRef.h"
44#include "llvm/IR/Analysis.h"
47#include <cassert>
48#include <cstring>
49#include <iterator>
50#include <list>
51#include <memory>
52#include <tuple>
53#include <type_traits>
54#include <utility>
55#include <vector>
56
57namespace llvm {
58
59class Function;
60class Module;
61
62// Forward declare the analysis manager template.
63template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
64
65/// A CRTP mix-in to automatically provide informational APIs needed for
66/// passes.
67///
68/// This provides some boilerplate for types that are passes.
69template <typename DerivedT> struct PassInfoMixin {
70 /// Gets the name of the pass we are mixed into.
71 static StringRef name() {
72 static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value,
73 "Must pass the derived type as the template argument!");
74 StringRef Name = getTypeName<DerivedT>();
75 Name.consume_front("llvm::");
76 return Name;
77 }
78
80 function_ref<StringRef(StringRef)> MapClassName2PassName) {
81 StringRef ClassName = DerivedT::name();
82 auto PassName = MapClassName2PassName(ClassName);
83 OS << PassName;
84 }
85};
86
87/// A CRTP mix-in that provides informational APIs needed for analysis passes.
88///
89/// This provides some boilerplate for types that are analysis passes. It
90/// automatically mixes in \c PassInfoMixin.
91template <typename DerivedT>
92struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
93 /// Returns an opaque, unique ID for this analysis type.
94 ///
95 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
96 /// suitable for use in sets, maps, and other data structures that use the low
97 /// bits of pointers.
98 ///
99 /// Note that this requires the derived type provide a static \c AnalysisKey
100 /// member called \c Key.
101 ///
102 /// FIXME: The only reason the mixin type itself can't declare the Key value
103 /// is that some compilers cannot correctly unique a templated static variable
104 /// so it has the same addresses in each instantiation. The only currently
105 /// known platform with this limitation is Windows DLL builds, specifically
106 /// building each part of LLVM as a DLL. If we ever remove that build
107 /// configuration, this mixin can provide the static key as well.
108 static AnalysisKey *ID() {
109 static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
110 "Must pass the derived type as the template argument!");
111 return &DerivedT::Key;
112 }
113};
114
115namespace detail {
116
117/// Actual unpacker of extra arguments in getAnalysisResult,
118/// passes only those tuple arguments that are mentioned in index_sequence.
119template <typename PassT, typename IRUnitT, typename AnalysisManagerT,
120 typename... ArgTs, size_t... Ns>
121typename PassT::Result
122getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR,
123 std::tuple<ArgTs...> Args,
124 std::index_sequence<Ns...>) {
125 (void)Args;
126 return AM.template getResult<PassT>(IR, std::get<Ns>(Args)...);
127}
128
129/// Helper for *partial* unpacking of extra arguments in getAnalysisResult.
130///
131/// Arguments passed in tuple come from PassManager, so they might have extra
132/// arguments after those AnalysisManager's ExtraArgTs ones that we need to
133/// pass to getResult.
134template <typename PassT, typename IRUnitT, typename... AnalysisArgTs,
135 typename... MainArgTs>
136typename PassT::Result
138 std::tuple<MainArgTs...> Args) {
140 PassT, IRUnitT>)(AM, IR, Args,
141 std::index_sequence_for<AnalysisArgTs...>{});
142}
143
144} // namespace detail
145
146/// Manages a sequence of passes over a particular unit of IR.
147///
148/// A pass manager contains a sequence of passes to run over a particular unit
149/// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
150/// IR, and when run over some given IR will run each of its contained passes in
151/// sequence. Pass managers are the primary and most basic building block of a
152/// pass pipeline.
153///
154/// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
155/// argument. The pass manager will propagate that analysis manager to each
156/// pass it runs, and will call the analysis manager's invalidation routine with
157/// the PreservedAnalyses of each pass it runs.
158template <typename IRUnitT,
159 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
160 typename... ExtraArgTs>
162 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
163public:
164 /// Construct a pass manager.
165 explicit PassManager() = default;
166
167 // FIXME: These are equivalent to the default move constructor/move
168 // assignment. However, using = default triggers linker errors due to the
169 // explicit instantiations below. Find away to use the default and remove the
170 // duplicated code here.
172
174 Passes = std::move(RHS.Passes);
175 return *this;
176 }
177
179 function_ref<StringRef(StringRef)> MapClassName2PassName) {
180 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
181 auto *P = Passes[Idx].get();
182 P->printPipeline(OS, MapClassName2PassName);
183 if (Idx + 1 < Size)
184 OS << ',';
185 }
186 }
187
188 /// Run all of the passes in this manager over the given unit of IR.
189 /// ExtraArgs are passed to each pass.
190 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
191 ExtraArgTs... ExtraArgs);
192
193 template <typename PassT>
194 LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v<PassT, PassManager>>
195 addPass(PassT &&Pass) {
196 using PassModelT =
197 detail::PassModel<IRUnitT, PassT, AnalysisManagerT, ExtraArgTs...>;
198 // Do not use make_unique or emplace_back, they cause too many template
199 // instantiations, causing terrible compile times.
200 Passes.push_back(std::unique_ptr<PassConceptT>(
201 new PassModelT(std::forward<PassT>(Pass))));
202 }
203
204 /// When adding a pass manager pass that has the same type as this pass
205 /// manager, simply move the passes over. This is because we don't have
206 /// use cases rely on executing nested pass managers. Doing this could
207 /// reduce implementation complexity and avoid potential invalidation
208 /// issues that may happen with nested pass managers of the same type.
209 template <typename PassT>
210 LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<std::is_same_v<PassT, PassManager>>
211 addPass(PassT &&Pass) {
212 for (auto &P : Pass.Passes)
213 Passes.push_back(std::move(P));
214 }
215
216 /// Returns if the pass manager contains any passes.
217 bool isEmpty() const { return Passes.empty(); }
218
219 static bool isRequired() { return true; }
220
221protected:
223 detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>;
224
225 std::vector<std::unique_ptr<PassConceptT>> Passes;
226};
227
228template <typename IRUnitT>
230
231template <>
233
234extern template class PassManager<Module>;
235
236/// Convenience typedef for a pass manager over modules.
238
239template <>
241 const Function &IR);
242
243extern template class PassManager<Function>;
244
245/// Convenience typedef for a pass manager over functions.
247
248/// A container for analyses that lazily runs them and caches their
249/// results.
250///
251/// This class can manage analyses for any IR unit where the address of the IR
252/// unit sufficies as its identity.
253template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
254public:
255 class Invalidator;
256
257private:
258 // Now that we've defined our invalidator, we can define the concept types.
260 using PassConceptT =
261 detail::AnalysisPassConcept<IRUnitT, Invalidator, ExtraArgTs...>;
262
263 /// List of analysis pass IDs and associated concept pointers.
264 ///
265 /// Requires iterators to be valid across appending new entries and arbitrary
266 /// erases. Provides the analysis ID to enable finding iterators to a given
267 /// entry in maps below, and provides the storage for the actual result
268 /// concept.
269 using AnalysisResultListT =
270 std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>;
271
272 /// Map type from IRUnitT pointer to our custom list type.
274
275 /// Map type from a pair of analysis ID and IRUnitT pointer to an
276 /// iterator into a particular result list (which is where the actual analysis
277 /// result is stored).
278 using AnalysisResultMapT =
280 typename AnalysisResultListT::iterator>;
281
282public:
283 /// API to communicate dependencies between analyses during invalidation.
284 ///
285 /// When an analysis result embeds handles to other analysis results, it
286 /// needs to be invalidated both when its own information isn't preserved and
287 /// when any of its embedded analysis results end up invalidated. We pass an
288 /// \c Invalidator object as an argument to \c invalidate() in order to let
289 /// the analysis results themselves define the dependency graph on the fly.
290 /// This lets us avoid building an explicit representation of the
291 /// dependencies between analysis results.
293 public:
294 /// Trigger the invalidation of some other analysis pass if not already
295 /// handled and return whether it was in fact invalidated.
296 ///
297 /// This is expected to be called from within a given analysis result's \c
298 /// invalidate method to trigger a depth-first walk of all inter-analysis
299 /// dependencies. The same \p IR unit and \p PA passed to that result's \c
300 /// invalidate method should in turn be provided to this routine.
301 ///
302 /// The first time this is called for a given analysis pass, it will call
303 /// the corresponding result's \c invalidate method. Subsequent calls will
304 /// use a cache of the results of that initial call. It is an error to form
305 /// cyclic dependencies between analysis results.
306 ///
307 /// This returns true if the given analysis's result is invalid. Any
308 /// dependecies on it will become invalid as a result.
309 template <typename PassT>
310 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
311 using ResultModelT =
312 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
314
315 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
316 }
317
318 /// A type-erased variant of the above invalidate method with the same core
319 /// API other than passing an analysis ID rather than an analysis type
320 /// parameter.
321 ///
322 /// This is sadly less efficient than the above routine, which leverages
323 /// the type parameter to avoid the type erasure overhead.
324 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
325 return invalidateImpl<>(ID, IR, PA);
326 }
327
328 private:
329 friend class AnalysisManager;
330
331 template <typename ResultT = ResultConceptT>
332 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
333 const PreservedAnalyses &PA) {
334 // If we've already visited this pass, return true if it was invalidated
335 // and false otherwise.
336 auto IMapI = IsResultInvalidated.find(ID);
337 if (IMapI != IsResultInvalidated.end())
338 return IMapI->second;
339
340 // Otherwise look up the result object.
341 auto RI = Results.find({ID, &IR});
342 assert(RI != Results.end() &&
343 "Trying to invalidate a dependent result that isn't in the "
344 "manager's cache is always an error, likely due to a stale result "
345 "handle!");
346
347 auto &Result = static_cast<ResultT &>(*RI->second->second);
348
349 // Insert into the map whether the result should be invalidated and return
350 // that. Note that we cannot reuse IMapI and must do a fresh insert here,
351 // as calling invalidate could (recursively) insert things into the map,
352 // making any iterator or reference invalid.
353 bool Inserted;
354 std::tie(IMapI, Inserted) =
355 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
356 (void)Inserted;
357 assert(Inserted && "Should not have already inserted this ID, likely "
358 "indicates a dependency cycle!");
359 return IMapI->second;
360 }
361
362 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
363 const AnalysisResultMapT &Results)
364 : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
365
366 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
367 const AnalysisResultMapT &Results;
368 };
369
370 /// Construct an empty analysis manager.
374
375 /// Returns true if the analysis manager has an empty results cache.
376 bool empty() const {
377 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
378 "The storage and index of analysis results disagree on how many "
379 "there are!");
380 return AnalysisResults.empty();
381 }
382
383 /// Clear any cached analysis results for a single unit of IR.
384 ///
385 /// This doesn't invalidate, but instead simply deletes, the relevant results.
386 /// It is useful when the IR is being removed and we want to clear out all the
387 /// memory pinned for it.
388 void clear(IRUnitT &IR, llvm::StringRef Name);
389
390 /// Clear all analysis results cached by this AnalysisManager.
391 ///
392 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
393 /// deletes them. This lets you clean up the AnalysisManager when the set of
394 /// IR units itself has potentially changed, and thus we can't even look up a
395 /// a result and invalidate/clear it directly.
396 void clear() {
397 AnalysisResults.clear();
398 AnalysisResultLists.clear();
399 }
400
401 /// Get the result of an analysis pass for a given IR unit.
402 ///
403 /// Runs the analysis if a cached result is not available.
404 template <typename PassT>
405 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
406 assert(AnalysisPasses.count(PassT::ID()) &&
407 "This analysis pass was not registered prior to being queried");
408 ResultConceptT &ResultConcept =
409 getResultImpl(PassT::ID(), IR, ExtraArgs...);
410
411 using ResultModelT =
412 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
414
415 return static_cast<ResultModelT &>(ResultConcept).Result;
416 }
417
418 /// Get the cached result of an analysis pass for a given IR unit.
419 ///
420 /// This method never runs the analysis.
421 ///
422 /// \returns null if there is no cached result.
423 template <typename PassT>
424 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
425 assert(AnalysisPasses.count(PassT::ID()) &&
426 "This analysis pass was not registered prior to being queried");
427
428 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
429 if (!ResultConcept)
430 return nullptr;
431
432 using ResultModelT =
433 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
435
436 return &static_cast<ResultModelT *>(ResultConcept)->Result;
437 }
438
439 /// Verify that the given Result cannot be invalidated, assert otherwise.
440 template <typename PassT>
441 void verifyNotInvalidated(IRUnitT &IR, typename PassT::Result *Result) const {
443 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
444 Invalidator Inv(IsResultInvalidated, AnalysisResults);
445 assert(!Result->invalidate(IR, PA, Inv) &&
446 "Cached result cannot be invalidated");
447 }
448
449 /// Register an analysis pass with the manager.
450 ///
451 /// The parameter is a callable whose result is an analysis pass. This allows
452 /// passing in a lambda to construct the analysis.
453 ///
454 /// The analysis type to register is the type returned by calling the \c
455 /// PassBuilder argument. If that type has already been registered, then the
456 /// argument will not be called and this function will return false.
457 /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
458 /// and this function returns true.
459 ///
460 /// (Note: Although the return value of this function indicates whether or not
461 /// an analysis was previously registered, there intentionally isn't a way to
462 /// query this directly. Instead, you should just register all the analyses
463 /// you might want and let this class run them lazily. This idiom lets us
464 /// minimize the number of times we have to look up analyses in our
465 /// hashtable.)
466 template <typename PassBuilderT>
467 bool registerPass(PassBuilderT &&PassBuilder) {
468 using PassT = decltype(PassBuilder());
469 using PassModelT =
470 detail::AnalysisPassModel<IRUnitT, PassT, Invalidator, ExtraArgTs...>;
471
472 auto &PassPtr = AnalysisPasses[PassT::ID()];
473 if (PassPtr)
474 // Already registered this pass type!
475 return false;
476
477 // Construct a new model around the instance returned by the builder.
478 PassPtr.reset(new PassModelT(PassBuilder()));
479 return true;
480 }
481
482 /// Invalidate cached analyses for an IR unit.
483 ///
484 /// Walk through all of the analyses pertaining to this unit of IR and
485 /// invalidate them, unless they are preserved by the PreservedAnalyses set.
486 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA);
487
488private:
489 /// Look up a registered analysis pass.
490 PassConceptT &lookUpPass(AnalysisKey *ID) {
491 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
492 assert(PI != AnalysisPasses.end() &&
493 "Analysis passes must be registered prior to being queried!");
494 return *PI->second;
495 }
496
497 /// Look up a registered analysis pass.
498 const PassConceptT &lookUpPass(AnalysisKey *ID) const {
499 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
500 assert(PI != AnalysisPasses.end() &&
501 "Analysis passes must be registered prior to being queried!");
502 return *PI->second;
503 }
504
505 /// Get an analysis result, running the pass if necessary.
506 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
507 ExtraArgTs... ExtraArgs);
508
509 /// Get a cached analysis result or return null.
510 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
512 AnalysisResults.find({ID, &IR});
513 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
514 }
515
516 /// Map type from analysis pass ID to pass concept pointer.
517 using AnalysisPassMapT =
518 DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>;
519
520 /// Collection of analysis passes, indexed by ID.
521 AnalysisPassMapT AnalysisPasses;
522
523 /// Map from IR unit to a list of analysis results.
524 ///
525 /// Provides linear time removal of all analysis results for a IR unit and
526 /// the ultimate storage for a particular cached analysis result.
527 AnalysisResultListMapT AnalysisResultLists;
528
529 /// Map from an analysis ID and IR unit to a particular cached
530 /// analysis result.
531 AnalysisResultMapT AnalysisResults;
532};
533
534extern template class AnalysisManager<Module>;
535
536/// Convenience typedef for the Module analysis manager.
537using ModuleAnalysisManager = AnalysisManager<Module>;
538
539extern template class AnalysisManager<Function>;
540
541/// Convenience typedef for the Function analysis manager.
543
544/// An analysis over an "outer" IR unit that provides access to an
545/// analysis manager over an "inner" IR unit. The inner unit must be contained
546/// in the outer unit.
547///
548/// For example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
549/// an analysis over Modules (the "outer" unit) that provides access to a
550/// Function analysis manager. The FunctionAnalysisManager is the "inner"
551/// manager being proxied, and Functions are the "inner" unit. The inner/outer
552/// relationship is valid because each Function is contained in one Module.
553///
554/// If you're (transitively) within a pass manager for an IR unit U that
555/// contains IR unit V, you should never use an analysis manager over V, except
556/// via one of these proxies.
557///
558/// Note that the proxy's result is a move-only RAII object. The validity of
559/// the analyses in the inner analysis manager is tied to its lifetime.
560template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
562 : public AnalysisInfoMixin<
563 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
564public:
565 class Result {
566 public:
567 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
568
569 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
570 // We have to null out the analysis manager in the moved-from state
571 // because we are taking ownership of the responsibilty to clear the
572 // analysis state.
573 Arg.InnerAM = nullptr;
574 }
575
577 // InnerAM is cleared in a moved from state where there is nothing to do.
578 if (!InnerAM)
579 return;
580
581 // Clear out the analysis manager if we're being destroyed -- it means we
582 // didn't even see an invalidate call when we got invalidated.
583 InnerAM->clear();
584 }
585
587 InnerAM = RHS.InnerAM;
588 // We have to null out the analysis manager in the moved-from state
589 // because we are taking ownership of the responsibilty to clear the
590 // analysis state.
591 RHS.InnerAM = nullptr;
592 return *this;
593 }
594
595 /// Accessor for the analysis manager.
596 AnalysisManagerT &getManager() { return *InnerAM; }
597
598 /// Handler for invalidation of the outer IR unit, \c IRUnitT.
599 ///
600 /// If the proxy analysis itself is not preserved, we assume that the set of
601 /// inner IR objects contained in IRUnit may have changed. In this case,
602 /// we have to call \c clear() on the inner analysis manager, as it may now
603 /// have stale pointers to its inner IR objects.
604 ///
605 /// Regardless of whether the proxy analysis is marked as preserved, all of
606 /// the analyses in the inner analysis manager are potentially invalidated
607 /// based on the set of preserved analyses.
609 IRUnitT &IR, const PreservedAnalyses &PA,
611
612 private:
613 AnalysisManagerT *InnerAM;
614 };
615
616 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
617 : InnerAM(&InnerAM) {}
618
619 /// Run the analysis pass and create our proxy result object.
620 ///
621 /// This doesn't do any interesting work; it is primarily used to insert our
622 /// proxy result object into the outer analysis cache so that we can proxy
623 /// invalidation to the inner analysis manager.
625 ExtraArgTs...) {
626 return Result(*InnerAM);
627 }
628
629private:
630 friend AnalysisInfoMixin<
632
633 static AnalysisKey Key;
634
635 AnalysisManagerT *InnerAM;
636};
637
638template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
639AnalysisKey
640 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
641
642/// Provide the \c FunctionAnalysisManager to \c Module proxy.
645
646/// Specialization of the invalidate method for the \c
647/// FunctionAnalysisManagerModuleProxy's result.
648template <>
649bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
650 Module &M, const PreservedAnalyses &PA,
652
653// Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
654// template.
656 Module>;
657
658/// An analysis over an "inner" IR unit that provides access to an
659/// analysis manager over a "outer" IR unit. The inner unit must be contained
660/// in the outer unit.
661///
662/// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
663/// analysis over Functions (the "inner" unit) which provides access to a Module
664/// analysis manager. The ModuleAnalysisManager is the "outer" manager being
665/// proxied, and Modules are the "outer" IR unit. The inner/outer relationship
666/// is valid because each Function is contained in one Module.
667///
668/// This proxy only exposes the const interface of the outer analysis manager,
669/// to indicate that you cannot cause an outer analysis to run from within an
670/// inner pass. Instead, you must rely on the \c getCachedResult API. This is
671/// due to keeping potential future concurrency in mind. To give an example,
672/// running a module analysis before any function passes may give a different
673/// result than running it in a function pass. Both may be valid, but it would
674/// produce non-deterministic results. GlobalsAA is a good analysis example,
675/// because the cached information has the mod/ref info for all memory for each
676/// function at the time the analysis was computed. The information is still
677/// valid after a function transformation, but it may be *different* if
678/// recomputed after that transform. GlobalsAA is never invalidated.
679
680///
681/// This proxy doesn't manage invalidation in any way -- that is handled by the
682/// recursive return path of each layer of the pass manager. A consequence of
683/// this is the outer analyses may be stale. We invalidate the outer analyses
684/// only when we're done running passes over the inner IR units.
685template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
687 : public AnalysisInfoMixin<
688 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
689public:
690 /// Result proxy object for \c OuterAnalysisManagerProxy.
691 class Result {
692 public:
693 explicit Result(const AnalysisManagerT &OuterAM) : OuterAM(&OuterAM) {}
694
695 /// Get a cached analysis. If the analysis can be invalidated, this will
696 /// assert.
697 template <typename PassT, typename IRUnitTParam>
698 typename PassT::Result *getCachedResult(IRUnitTParam &IR) const {
699 typename PassT::Result *Res =
700 OuterAM->template getCachedResult<PassT>(IR);
701 if (Res)
702 OuterAM->template verifyNotInvalidated<PassT>(IR, Res);
703 return Res;
704 }
705
706 /// Method provided for unit testing, not intended for general use.
707 template <typename PassT, typename IRUnitTParam>
708 bool cachedResultExists(IRUnitTParam &IR) const {
709 typename PassT::Result *Res =
710 OuterAM->template getCachedResult<PassT>(IR);
711 return Res != nullptr;
712 }
713
714 /// When invalidation occurs, remove any registered invalidation events.
716 IRUnitT &IRUnit, const PreservedAnalyses &PA,
718 // Loop over the set of registered outer invalidation mappings and if any
719 // of them map to an analysis that is now invalid, clear it out.
721 for (auto &KeyValuePair : OuterAnalysisInvalidationMap) {
722 AnalysisKey *OuterID = KeyValuePair.first;
723 auto &InnerIDs = KeyValuePair.second;
724 llvm::erase_if(InnerIDs, [&](AnalysisKey *InnerID) {
725 return Inv.invalidate(InnerID, IRUnit, PA);
726 });
727 if (InnerIDs.empty())
728 DeadKeys.push_back(OuterID);
729 }
730
731 for (auto *OuterID : DeadKeys)
732 OuterAnalysisInvalidationMap.erase(OuterID);
733
734 // The proxy itself remains valid regardless of anything else.
735 return false;
736 }
737
738 /// Register a deferred invalidation event for when the outer analysis
739 /// manager processes its invalidations.
740 template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
742 AnalysisKey *OuterID = OuterAnalysisT::ID();
743 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
744
745 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
746 // Note, this is a linear scan. If we end up with large numbers of
747 // analyses that all trigger invalidation on the same outer analysis,
748 // this entire system should be changed to some other deterministic
749 // data structure such as a `SetVector` of a pair of pointers.
750 if (!llvm::is_contained(InvalidatedIDList, InvalidatedID))
751 InvalidatedIDList.push_back(InvalidatedID);
752 }
753
754 /// Access the map from outer analyses to deferred invalidation requiring
755 /// analyses.
758 return OuterAnalysisInvalidationMap;
759 }
760
761 private:
762 const AnalysisManagerT *OuterAM;
763
764 /// A map from an outer analysis ID to the set of this IR-unit's analyses
765 /// which need to be invalidated.
767 OuterAnalysisInvalidationMap;
768 };
769
770 OuterAnalysisManagerProxy(const AnalysisManagerT &OuterAM)
771 : OuterAM(&OuterAM) {}
772
773 /// Run the analysis pass and create our proxy result object.
774 /// Nothing to see here, it just forwards the \c OuterAM reference into the
775 /// result.
777 ExtraArgTs...) {
778 return Result(*OuterAM);
779 }
780
781private:
782 friend AnalysisInfoMixin<
783 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
784
785 static AnalysisKey Key;
786
787 const AnalysisManagerT *OuterAM;
788};
789
790template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
791AnalysisKey
792 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
793
794extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
795 Function>;
796/// Provide the \c ModuleAnalysisManager to \c Function proxy.
799
800/// Trivial adaptor that maps from a module to its functions.
801///
802/// Designed to allow composition of a FunctionPass(Manager) and
803/// a ModulePassManager, by running the FunctionPass(Manager) over every
804/// function in the module.
805///
806/// Function passes run within this adaptor can rely on having exclusive access
807/// to the function they are run over. They should not read or modify any other
808/// functions! Other threads or systems may be manipulating other functions in
809/// the module, and so their state should never be relied on.
810/// FIXME: Make the above true for all of LLVM's actual passes, some still
811/// violate this principle.
812///
813/// Function passes can also read the module containing the function, but they
814/// should not modify that module outside of the use lists of various globals.
815/// For example, a function pass is not permitted to add functions to the
816/// module.
817/// FIXME: Make the above true for all of LLVM's actual passes, some still
818/// violate this principle.
819///
820/// Note that although function passes can access module analyses, module
821/// analyses are not invalidated while the function passes are running, so they
822/// may be stale. Function analyses will not be stale.
824 : public PassInfoMixin<ModuleToFunctionPassAdaptor> {
825public:
827
828 explicit ModuleToFunctionPassAdaptor(std::unique_ptr<PassConceptT> Pass,
829 bool EagerlyInvalidate)
830 : Pass(std::move(Pass)), EagerlyInvalidate(EagerlyInvalidate) {}
831
832 /// Runs the function pass across every function in the module.
835 function_ref<StringRef(StringRef)> MapClassName2PassName);
836
837 static bool isRequired() { return true; }
838
839private:
840 std::unique_ptr<PassConceptT> Pass;
841 bool EagerlyInvalidate;
842};
843
844/// A function to deduce a function pass type and wrap it in the
845/// templated adaptor.
846template <typename FunctionPassT>
847ModuleToFunctionPassAdaptor
849 bool EagerlyInvalidate = false) {
850 using PassModelT =
852 // Do not use make_unique, it causes too many template instantiations,
853 // causing terrible compile times.
855 std::unique_ptr<ModuleToFunctionPassAdaptor::PassConceptT>(
856 new PassModelT(std::forward<FunctionPassT>(Pass))),
857 EagerlyInvalidate);
858}
859
860/// A utility pass template to force an analysis result to be available.
861///
862/// If there are extra arguments at the pass's run level there may also be
863/// extra arguments to the analysis manager's \c getResult routine. We can't
864/// guess how to effectively map the arguments from one to the other, and so
865/// this specialization just ignores them.
866///
867/// Specific patterns of run-method extra arguments and analysis manager extra
868/// arguments will have to be defined as appropriate specializations.
869template <typename AnalysisT, typename IRUnitT,
870 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
871 typename... ExtraArgTs>
873 : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
874 ExtraArgTs...>> {
875 /// Run this pass over some unit of IR.
876 ///
877 /// This pass can be run over any unit of IR and use any analysis manager
878 /// provided they satisfy the basic API requirements. When this pass is
879 /// created, these methods can be instantiated to satisfy whatever the
880 /// context requires.
881 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
882 ExtraArgTs &&... Args) {
883 (void)AM.template getResult<AnalysisT>(Arg,
884 std::forward<ExtraArgTs>(Args)...);
885
886 return PreservedAnalyses::all();
887 }
889 function_ref<StringRef(StringRef)> MapClassName2PassName) {
890 auto ClassName = AnalysisT::name();
891 auto PassName = MapClassName2PassName(ClassName);
892 OS << "require<" << PassName << '>';
893 }
894 static bool isRequired() { return true; }
895};
896
897/// A no-op pass template which simply forces a specific analysis result
898/// to be invalidated.
899template <typename AnalysisT>
901 : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
902 /// Run this pass over some unit of IR.
903 ///
904 /// This pass can be run over any unit of IR and use any analysis manager,
905 /// provided they satisfy the basic API requirements. When this pass is
906 /// created, these methods can be instantiated to satisfy whatever the
907 /// context requires.
908 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
909 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
910 auto PA = PreservedAnalyses::all();
911 PA.abandon<AnalysisT>();
912 return PA;
913 }
915 function_ref<StringRef(StringRef)> MapClassName2PassName) {
916 auto ClassName = AnalysisT::name();
917 auto PassName = MapClassName2PassName(ClassName);
918 OS << "invalidate<" << PassName << '>';
919 }
920};
921
922/// A utility pass that does nothing, but preserves no analyses.
923///
924/// Because this preserves no analyses, any analysis passes queried after this
925/// pass runs will recompute fresh results.
926struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
927 /// Run this pass over some unit of IR.
928 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
929 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
931 }
932};
933
934} // end namespace llvm
935
936#endif // LLVM_IR_PASSMANAGER_H
Function Alias Analysis Results
#define LLVM_ATTRIBUTE_MINSIZE
Definition: Compiler.h:233
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
std::string Name
uint64_t Size
Legalize the Machine IR a function s Machine IR
Definition: Legalizer.cpp:81
Machine Check Debug Module
#define P(N)
This header provides internal APIs and implementation details used by the pass management interfaces ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
static const char PassName[]
Value * RHS
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:292
bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA)
A type-erased variant of the above invalidate method with the same core API other than passing an ana...
Definition: PassManager.h:324
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
Definition: PassManager.h:310
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
AnalysisManager()
Construct an empty analysis manager.
void clear()
Clear all analysis results cached by this AnalysisManager.
Definition: PassManager.h:396
AnalysisManager(AnalysisManager &&)
void verifyNotInvalidated(IRUnitT &IR, typename PassT::Result *Result) const
Verify that the given Result cannot be invalidated, assert otherwise.
Definition: PassManager.h:441
AnalysisManager & operator=(AnalysisManager &&)
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:424
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:467
bool empty() const
Returns true if the analysis manager has an empty results cache.
Definition: PassManager.h:376
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition: DenseMap.h:71
bool empty() const
Definition: DenseMap.h:98
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
iterator end()
Definition: DenseMap.h:84
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition: DenseMap.h:73
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA, typename AnalysisManager< IRUnitT, ExtraArgTs... >::Invalidator &Inv)
Handler for invalidation of the outer IR unit, IRUnitT.
Result(AnalysisManagerT &InnerAM)
Definition: PassManager.h:567
AnalysisManagerT & getManager()
Accessor for the analysis manager.
Definition: PassManager.h:596
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
Result run(IRUnitT &IR, AnalysisManager< IRUnitT, ExtraArgTs... > &AM, ExtraArgTs...)
Run the analysis pass and create our proxy result object.
Definition: PassManager.h:624
InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
Definition: PassManager.h:616
Trivial adaptor that maps from a module to its functions.
Definition: PassManager.h:824
ModuleToFunctionPassAdaptor(std::unique_ptr< PassConceptT > Pass, bool EagerlyInvalidate)
Definition: PassManager.h:828
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Runs the function pass across every function in the module.
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition: PassManager.cpp:94
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Result proxy object for OuterAnalysisManagerProxy.
Definition: PassManager.h:691
Result(const AnalysisManagerT &OuterAM)
Definition: PassManager.h:693
PassT::Result * getCachedResult(IRUnitTParam &IR) const
Get a cached analysis.
Definition: PassManager.h:698
bool invalidate(IRUnitT &IRUnit, const PreservedAnalyses &PA, typename AnalysisManager< IRUnitT, ExtraArgTs... >::Invalidator &Inv)
When invalidation occurs, remove any registered invalidation events.
Definition: PassManager.h:715
bool cachedResultExists(IRUnitTParam &IR) const
Method provided for unit testing, not intended for general use.
Definition: PassManager.h:708
const SmallDenseMap< AnalysisKey *, TinyPtrVector< AnalysisKey * >, 2 > & getOuterInvalidations() const
Access the map from outer analyses to deferred invalidation requiring analyses.
Definition: PassManager.h:757
void registerOuterAnalysisInvalidation()
Register a deferred invalidation event for when the outer analysis manager processes its invalidation...
Definition: PassManager.h:741
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:688
Result run(IRUnitT &, AnalysisManager< IRUnitT, ExtraArgTs... > &, ExtraArgTs...)
Run the analysis pass and create our proxy result object.
Definition: PassManager.h:776
OuterAnalysisManagerProxy(const AnalysisManagerT &OuterAM)
Definition: PassManager.h:770
This class provides access to building LLVM's passes.
Definition: PassBuilder.h:106
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:162
PassManager(PassManager &&Arg)
Definition: PassManager.h:171
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition: PassManager.h:178
PassManager & operator=(PassManager &&RHS)
Definition: PassManager.h:173
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
Definition: PassManager.h:195
std::vector< std::unique_ptr< PassConceptT > > Passes
Definition: PassManager.h:225
PassManager()=default
Construct a pass manager.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t< std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
When adding a pass manager pass that has the same type as this pass manager, simply move the passes o...
Definition: PassManager.h:211
static bool isRequired()
Definition: PassManager.h:219
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
bool isEmpty() const
Returns if the pass manager contains any passes.
Definition: PassManager.h:217
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void abandon()
Mark an analysis as abandoned.
Definition: Analysis.h:164
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
Pass manager infrastructure for declaring and invalidating analyses.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
PassT::Result getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR, std::tuple< ArgTs... > Args, std::index_sequence< Ns... >)
Actual unpacker of extra arguments in getAnalysisResult, passes only those tuple arguments that are m...
Definition: PassManager.h:122
PassT::Result getAnalysisResult(AnalysisManager< IRUnitT, AnalysisArgTs... > &AM, IRUnitT &IR, std::tuple< MainArgTs... > Args)
Helper for partial unpacking of extra arguments in getAnalysisResult.
Definition: PassManager.h:137
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
Definition: PassManager.h:848
void printIRUnitNameForStackTrace< Function >(raw_ostream &OS, const Function &IR)
void printIRUnitNameForStackTrace(raw_ostream &OS, const IRUnitT &IR)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Definition: PassManager.h:542
void printIRUnitNameForStackTrace< Module >(raw_ostream &OS, const Module &IR)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2051
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition: MIRParser.h:38
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:92
static AnalysisKey * ID()
Returns an opaque, unique ID for this analysis type.
Definition: PassManager.h:108
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:28
A utility pass that does nothing, but preserves no analyses.
Definition: PassManager.h:926
PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...)
Run this pass over some unit of IR.
Definition: PassManager.h:929
A no-op pass template which simply forces a specific analysis result to be invalidated.
Definition: PassManager.h:901
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition: PassManager.h:914
PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...)
Run this pass over some unit of IR.
Definition: PassManager.h:909
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:69
static StringRef name()
Gets the name of the pass we are mixed into.
Definition: PassManager.h:71
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition: PassManager.h:79
A utility pass template to force an analysis result to be available.
Definition: PassManager.h:874
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition: PassManager.h:888
static bool isRequired()
Definition: PassManager.h:894
PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&... Args)
Run this pass over some unit of IR.
Definition: PassManager.h:881
Abstract concept of an analysis pass.
Wrapper to model the analysis pass concept.
Abstract concept of an analysis result.
Wrapper to model the analysis result concept.
A template wrapper used to implement the polymorphic API.