1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This header defines various interfaces for pass management in LLVM. There
12 /// is no "pass" interface in LLVM per se. Instead, an instance of any class
13 /// which supports a method to 'run' it over a unit of IR can be used as
14 /// a pass. A pass manager is generally a tool to collect a sequence of passes
15 /// which run over a particular IR construct, and run each of them in sequence
16 /// over each such construct in the containing IR construct. As there is no
17 /// containing IR construct for a Module, a manager for passes over modules
18 /// forms the base case which runs its managed passes in sequence over the
19 /// single module provided.
21 /// The core IR library provides managers for running passes over
22 /// modules and functions.
24 /// * FunctionPassManager can run over a Module, runs each pass over
26 /// * ModulePassManager must be directly run, runs each pass over the Module.
28 /// Note that the implementations of the pass managers use concept-based
29 /// polymorphism as outlined in the "Value Semantics and Concept-based
30 /// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
31 /// Class of Evil") by Sean Parent:
32 /// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
33 /// * http://www.youtube.com/watch?v=_BpMYeUFXv8
34 /// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
36 //===----------------------------------------------------------------------===//
38 #ifndef LLVM_IR_PASSMANAGER_H
39 #define LLVM_IR_PASSMANAGER_H
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/TinyPtrVector.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/PassManagerInternal.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/TypeName.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Support/type_traits.h"
58 /// A special type used by analysis passes to provide an address that
59 /// identifies that particular analysis pass type.
61 /// Analysis passes should have a static data member of this type and derive
62 /// from the \c AnalysisInfoMixin to get a static ID method used to identify
63 /// the analysis in the pass management infrastructure.
64 struct alignas(8) AnalysisKey {};
66 /// A special type used to provide an address that identifies a set of related
67 /// analyses. These sets are primarily used below to mark sets of analyses as
70 /// For example, a transformation can indicate that it preserves the CFG of a
71 /// function by preserving the appropriate AnalysisSetKey. An analysis that
72 /// depends only on the CFG can then check if that AnalysisSetKey is preserved;
73 /// if it is, the analysis knows that it itself is preserved.
74 struct alignas(8) AnalysisSetKey {};
76 /// A set of analyses that are preserved following a run of a transformation
79 /// Transformation passes build and return these objects to communicate which
80 /// analyses are still valid after the transformation. For most passes this is
81 /// fairly simple: if they don't change anything all analyses are preserved,
82 /// otherwise only a short list of analyses that have been explicitly updated
85 /// This class also lets transformation passes mark abstract *sets* of analyses
86 /// as preserved. A transformation that (say) does not alter the CFG can
87 /// indicate such by marking a particular AnalysisSetKey as preserved, and
88 /// then analyses can query whether that AnalysisSetKey is preserved.
90 /// Finally, this class can represent an "abandoned" analysis, which is
91 /// not preserved even if it would be covered by some abstract set of analyses.
93 /// Given a `PreservedAnalyses` object, an analysis will typically want to
94 /// figure out whether it is preserved. In the example below, MyAnalysisType is
95 /// preserved if it's not abandoned, and (a) it's explicitly marked as
96 /// preserved, (b), the set AllAnalysesOn<MyIRUnit> is preserved, or (c) both
97 /// AnalysisSetA and AnalysisSetB are preserved.
100 /// auto PAC = PA.getChecker<MyAnalysisType>();
101 /// if (PAC.preserved() || PAC.preservedSet<AllAnalysesOn<MyIRUnit>>() ||
102 /// (PAC.preservedSet<AnalysisSetA>() &&
103 /// PAC.preservedSet<AnalysisSetB>())) {
104 /// // The analysis has been successfully preserved ...
107 class PreservedAnalyses {
109 /// \brief Convenience factory function for the empty preserved set.
110 static PreservedAnalyses none() { return PreservedAnalyses(); }
112 /// \brief Construct a special preserved set that preserves all passes.
113 static PreservedAnalyses all() {
114 PreservedAnalyses PA;
115 PA.PreservedIDs.insert(&AllAnalysesKey);
119 /// Mark an analysis as preserved.
120 template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); }
122 /// \brief Given an analysis's ID, mark the analysis as preserved, adding it
124 void preserve(AnalysisKey *ID) {
125 // Clear this ID from the explicit not-preserved set if present.
126 NotPreservedAnalysisIDs.erase(ID);
128 // If we're not already preserving all analyses (other than those in
129 // NotPreservedAnalysisIDs).
130 if (!areAllPreserved())
131 PreservedIDs.insert(ID);
134 /// Mark an analysis set as preserved.
135 template <typename AnalysisSetT> void preserveSet() {
136 preserveSet(AnalysisSetT::ID());
139 /// Mark an analysis set as preserved using its ID.
140 void preserveSet(AnalysisSetKey *ID) {
141 // If we're not already in the saturated 'all' state, add this set.
142 if (!areAllPreserved())
143 PreservedIDs.insert(ID);
146 /// Mark an analysis as abandoned.
148 /// An abandoned analysis is not preserved, even if it is nominally covered
149 /// by some other set or was previously explicitly marked as preserved.
151 /// Note that you can only abandon a specific analysis, not a *set* of
153 template <typename AnalysisT> void abandon() { abandon(AnalysisT::ID()); }
155 /// Mark an analysis as abandoned using its ID.
157 /// An abandoned analysis is not preserved, even if it is nominally covered
158 /// by some other set or was previously explicitly marked as preserved.
160 /// Note that you can only abandon a specific analysis, not a *set* of
162 void abandon(AnalysisKey *ID) {
163 PreservedIDs.erase(ID);
164 NotPreservedAnalysisIDs.insert(ID);
167 /// \brief Intersect this set with another in place.
169 /// This is a mutating operation on this preserved set, removing all
170 /// preserved passes which are not also preserved in the argument.
171 void intersect(const PreservedAnalyses &Arg) {
172 if (Arg.areAllPreserved())
174 if (areAllPreserved()) {
178 // The intersection requires the *union* of the explicitly not-preserved
179 // IDs and the *intersection* of the preserved IDs.
180 for (auto ID : Arg.NotPreservedAnalysisIDs) {
181 PreservedIDs.erase(ID);
182 NotPreservedAnalysisIDs.insert(ID);
184 for (auto ID : PreservedIDs)
185 if (!Arg.PreservedIDs.count(ID))
186 PreservedIDs.erase(ID);
189 /// \brief Intersect this set with a temporary other set in place.
191 /// This is a mutating operation on this preserved set, removing all
192 /// preserved passes which are not also preserved in the argument.
193 void intersect(PreservedAnalyses &&Arg) {
194 if (Arg.areAllPreserved())
196 if (areAllPreserved()) {
197 *this = std::move(Arg);
200 // The intersection requires the *union* of the explicitly not-preserved
201 // IDs and the *intersection* of the preserved IDs.
202 for (auto ID : Arg.NotPreservedAnalysisIDs) {
203 PreservedIDs.erase(ID);
204 NotPreservedAnalysisIDs.insert(ID);
206 for (auto ID : PreservedIDs)
207 if (!Arg.PreservedIDs.count(ID))
208 PreservedIDs.erase(ID);
211 /// A checker object that makes it easy to query for whether an analysis or
212 /// some set covering it is preserved.
213 class PreservedAnalysisChecker {
214 friend class PreservedAnalyses;
216 const PreservedAnalyses &PA;
217 AnalysisKey *const ID;
218 const bool IsAbandoned;
220 /// A PreservedAnalysisChecker is tied to a particular Analysis because
221 /// `preserved()` and `preservedSet()` both return false if the Analysis
223 PreservedAnalysisChecker(const PreservedAnalyses &PA, AnalysisKey *ID)
224 : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {}
227 /// Returns true if the checker's analysis was not abandoned and either
228 /// - the analysis is explicitly preserved or
229 /// - all analyses are preserved.
231 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
232 PA.PreservedIDs.count(ID));
235 /// Returns true if the checker's analysis was not abandoned and either
236 /// - \p AnalysisSetT is explicitly preserved or
237 /// - all analyses are preserved.
238 template <typename AnalysisSetT> bool preservedSet() {
239 AnalysisSetKey *SetID = AnalysisSetT::ID();
240 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
241 PA.PreservedIDs.count(SetID));
245 /// Build a checker for this `PreservedAnalyses` and the specified analysis
248 /// You can use the returned object to query whether an analysis was
249 /// preserved. See the example in the comment on `PreservedAnalysis`.
250 template <typename AnalysisT> PreservedAnalysisChecker getChecker() const {
251 return PreservedAnalysisChecker(*this, AnalysisT::ID());
254 /// Build a checker for this `PreservedAnalyses` and the specified analysis
257 /// You can use the returned object to query whether an analysis was
258 /// preserved. See the example in the comment on `PreservedAnalysis`.
259 PreservedAnalysisChecker getChecker(AnalysisKey *ID) const {
260 return PreservedAnalysisChecker(*this, ID);
263 /// Test whether all analyses are preserved (and none are abandoned).
265 /// This is used primarily to optimize for the common case of a transformation
266 /// which makes no changes to the IR.
267 bool areAllPreserved() const {
268 return NotPreservedAnalysisIDs.empty() &&
269 PreservedIDs.count(&AllAnalysesKey);
272 /// Directly test whether a set of analyses is preserved.
274 /// This is only true when no analyses have been explicitly abandoned.
275 template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const {
276 return allAnalysesInSetPreserved(AnalysisSetT::ID());
279 /// Directly test whether a set of analyses is preserved.
281 /// This is only true when no analyses have been explicitly abandoned.
282 bool allAnalysesInSetPreserved(AnalysisSetKey *SetID) const {
283 return NotPreservedAnalysisIDs.empty() &&
284 (PreservedIDs.count(&AllAnalysesKey) || PreservedIDs.count(SetID));
288 /// A special key used to indicate all analyses.
289 static AnalysisSetKey AllAnalysesKey;
291 /// The IDs of analyses and analysis sets that are preserved.
292 SmallPtrSet<void *, 2> PreservedIDs;
294 /// The IDs of explicitly not-preserved analyses.
296 /// If an analysis in this set is covered by a set in `PreservedIDs`, we
297 /// consider it not-preserved. That is, `NotPreservedAnalysisIDs` always
298 /// "wins" over analysis sets in `PreservedIDs`.
300 /// Also, a given ID should never occur both here and in `PreservedIDs`.
301 SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs;
304 // Forward declare the analysis manager template.
305 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
307 /// A CRTP mix-in to automatically provide informational APIs needed for
310 /// This provides some boilerplate for types that are passes.
311 template <typename DerivedT> struct PassInfoMixin {
312 /// Gets the name of the pass we are mixed into.
313 static StringRef name() {
314 StringRef Name = getTypeName<DerivedT>();
315 if (Name.startswith("llvm::"))
316 Name = Name.drop_front(strlen("llvm::"));
321 /// A CRTP mix-in that provides informational APIs needed for analysis passes.
323 /// This provides some boilerplate for types that are analysis passes. It
324 /// automatically mixes in \c PassInfoMixin.
325 template <typename DerivedT>
326 struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
327 /// Returns an opaque, unique ID for this analysis type.
329 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
330 /// suitable for use in sets, maps, and other data structures that use the low
331 /// bits of pointers.
333 /// Note that this requires the derived type provide a static \c AnalysisKey
334 /// member called \c Key.
336 /// FIXME: The only reason the mixin type itself can't declare the Key value
337 /// is that some compilers cannot correctly unique a templated static variable
338 /// so it has the same addresses in each instantiation. The only currently
339 /// known platform with this limitation is Windows DLL builds, specifically
340 /// building each part of LLVM as a DLL. If we ever remove that build
341 /// configuration, this mixin can provide the static key as well.
342 static AnalysisKey *ID() { return &DerivedT::Key; }
345 /// This templated class represents "all analyses that operate over \<a
346 /// particular IR unit\>" (e.g. a Function or a Module) in instances of
347 /// PreservedAnalysis.
349 /// This lets a transformation say e.g. "I preserved all function analyses".
351 /// Note that you must provide an explicit instantiation declaration and
352 /// definition for this template in order to get the correct behavior on
353 /// Windows. Otherwise, the address of SetKey will not be stable.
354 template <typename IRUnitT>
355 class AllAnalysesOn {
357 static AnalysisSetKey *ID() { return &SetKey; }
360 static AnalysisSetKey SetKey;
363 template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;
365 extern template class AllAnalysesOn<Module>;
366 extern template class AllAnalysesOn<Function>;
368 /// \brief Manages a sequence of passes over a particular unit of IR.
370 /// A pass manager contains a sequence of passes to run over a particular unit
371 /// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
372 /// IR, and when run over some given IR will run each of its contained passes in
373 /// sequence. Pass managers are the primary and most basic building block of a
376 /// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
377 /// argument. The pass manager will propagate that analysis manager to each
378 /// pass it runs, and will call the analysis manager's invalidation routine with
379 /// the PreservedAnalyses of each pass it runs.
380 template <typename IRUnitT,
381 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
382 typename... ExtraArgTs>
383 class PassManager : public PassInfoMixin<
384 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
386 /// \brief Construct a pass manager.
388 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
389 explicit PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
391 // FIXME: These are equivalent to the default move constructor/move
392 // assignment. However, using = default triggers linker errors due to the
393 // explicit instantiations below. Find away to use the default and remove the
394 // duplicated code here.
395 PassManager(PassManager &&Arg)
396 : Passes(std::move(Arg.Passes)),
397 DebugLogging(std::move(Arg.DebugLogging)) {}
399 PassManager &operator=(PassManager &&RHS) {
400 Passes = std::move(RHS.Passes);
401 DebugLogging = std::move(RHS.DebugLogging);
405 /// \brief Run all of the passes in this manager over the given unit of IR.
406 /// ExtraArgs are passed to each pass.
407 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
408 ExtraArgTs... ExtraArgs) {
409 PreservedAnalyses PA = PreservedAnalyses::all();
412 dbgs() << "Starting " << getTypeName<IRUnitT>() << " pass manager run.\n";
414 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
416 dbgs() << "Running pass: " << Passes[Idx]->name() << " on "
417 << IR.getName() << "\n";
419 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM, ExtraArgs...);
421 // Update the analysis manager as each pass runs and potentially
422 // invalidates analyses.
423 AM.invalidate(IR, PassPA);
425 // Finally, intersect the preserved analyses to compute the aggregate
426 // preserved set for this pass manager.
427 PA.intersect(std::move(PassPA));
429 // FIXME: Historically, the pass managers all called the LLVM context's
430 // yield function here. We don't have a generic way to acquire the
431 // context and it isn't yet clear what the right pattern is for yielding
432 // in the new pass manager so it is currently omitted.
433 //IR.getContext().yield();
436 // Invaliadtion was handled after each pass in the above loop for the
437 // current unit of IR. Therefore, the remaining analysis results in the
438 // AnalysisManager are preserved. We mark this with a set so that we don't
439 // need to inspect each one individually.
440 PA.preserveSet<AllAnalysesOn<IRUnitT>>();
443 dbgs() << "Finished " << getTypeName<IRUnitT>() << " pass manager run.\n";
448 template <typename PassT> void addPass(PassT Pass) {
449 typedef detail::PassModel<IRUnitT, PassT, PreservedAnalyses,
450 AnalysisManagerT, ExtraArgTs...>
452 Passes.emplace_back(new PassModelT(std::move(Pass)));
456 typedef detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>
459 std::vector<std::unique_ptr<PassConceptT>> Passes;
461 /// \brief Flag indicating whether we should do debug logging.
465 extern template class PassManager<Module>;
466 /// \brief Convenience typedef for a pass manager over modules.
467 typedef PassManager<Module> ModulePassManager;
469 extern template class PassManager<Function>;
470 /// \brief Convenience typedef for a pass manager over functions.
471 typedef PassManager<Function> FunctionPassManager;
473 /// \brief A container for analyses that lazily runs them and caches their
476 /// This class can manage analyses for any IR unit where the address of the IR
477 /// unit sufficies as its identity.
478 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
483 // Now that we've defined our invalidator, we can define the concept types.
484 typedef detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>
486 typedef detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator,
490 /// \brief List of analysis pass IDs and associated concept pointers.
492 /// Requires iterators to be valid across appending new entries and arbitrary
493 /// erases. Provides the analysis ID to enable finding iterators to a given
494 /// entry in maps below, and provides the storage for the actual result
496 typedef std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>
499 /// \brief Map type from IRUnitT pointer to our custom list type.
500 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
502 /// \brief Map type from a pair of analysis ID and IRUnitT pointer to an
503 /// iterator into a particular result list (which is where the actual analysis
504 /// result is stored).
505 typedef DenseMap<std::pair<AnalysisKey *, IRUnitT *>,
506 typename AnalysisResultListT::iterator>
510 /// API to communicate dependencies between analyses during invalidation.
512 /// When an analysis result embeds handles to other analysis results, it
513 /// needs to be invalidated both when its own information isn't preserved and
514 /// when any of its embedded analysis results end up invalidated. We pass an
515 /// \c Invalidator object as an argument to \c invalidate() in order to let
516 /// the analysis results themselves define the dependency graph on the fly.
517 /// This lets us avoid building building an explicit representation of the
518 /// dependencies between analysis results.
521 /// Trigger the invalidation of some other analysis pass if not already
522 /// handled and return whether it was in fact invalidated.
524 /// This is expected to be called from within a given analysis result's \c
525 /// invalidate method to trigger a depth-first walk of all inter-analysis
526 /// dependencies. The same \p IR unit and \p PA passed to that result's \c
527 /// invalidate method should in turn be provided to this routine.
529 /// The first time this is called for a given analysis pass, it will call
530 /// the corresponding result's \c invalidate method. Subsequent calls will
531 /// use a cache of the results of that initial call. It is an error to form
532 /// cyclic dependencies between analysis results.
534 /// This returns true if the given analysis's result is invalid. Any
535 /// dependecies on it will become invalid as a result.
536 template <typename PassT>
537 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
538 typedef detail::AnalysisResultModel<IRUnitT, PassT,
539 typename PassT::Result,
540 PreservedAnalyses, Invalidator>
542 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
545 /// A type-erased variant of the above invalidate method with the same core
546 /// API other than passing an analysis ID rather than an analysis type
549 /// This is sadly less efficient than the above routine, which leverages
550 /// the type parameter to avoid the type erasure overhead.
551 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
552 return invalidateImpl<>(ID, IR, PA);
556 friend class AnalysisManager;
558 template <typename ResultT = ResultConceptT>
559 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
560 const PreservedAnalyses &PA) {
561 // If we've already visited this pass, return true if it was invalidated
562 // and false otherwise.
563 auto IMapI = IsResultInvalidated.find(ID);
564 if (IMapI != IsResultInvalidated.end())
565 return IMapI->second;
567 // Otherwise look up the result object.
568 auto RI = Results.find({ID, &IR});
569 assert(RI != Results.end() &&
570 "Trying to invalidate a dependent result that isn't in the "
571 "manager's cache is always an error, likely due to a stale result "
574 auto &Result = static_cast<ResultT &>(*RI->second->second);
576 // Insert into the map whether the result should be invalidated and return
577 // that. Note that we cannot reuse IMapI and must do a fresh insert here,
578 // as calling invalidate could (recursively) insert things into the map,
579 // making any iterator or reference invalid.
581 std::tie(IMapI, Inserted) =
582 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
584 assert(Inserted && "Should not have already inserted this ID, likely "
585 "indicates a dependency cycle!");
586 return IMapI->second;
589 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
590 const AnalysisResultMapT &Results)
591 : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
593 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
594 const AnalysisResultMapT &Results;
597 /// \brief Construct an empty analysis manager.
599 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
600 AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
601 AnalysisManager(AnalysisManager &&) = default;
602 AnalysisManager &operator=(AnalysisManager &&) = default;
604 /// \brief Returns true if the analysis manager has an empty results cache.
606 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
607 "The storage and index of analysis results disagree on how many "
609 return AnalysisResults.empty();
612 /// \brief Clear any cached analysis results for a single unit of IR.
614 /// This doesn't invalidate, but instead simply deletes, the relevant results.
615 /// It is useful when the IR is being removed and we want to clear out all the
616 /// memory pinned for it.
617 void clear(IRUnitT &IR) {
619 dbgs() << "Clearing all analysis results for: " << IR.getName() << "\n";
621 auto ResultsListI = AnalysisResultLists.find(&IR);
622 if (ResultsListI == AnalysisResultLists.end())
624 // Delete the map entries that point into the results list.
625 for (auto &IDAndResult : ResultsListI->second)
626 AnalysisResults.erase({IDAndResult.first, &IR});
628 // And actually destroy and erase the results associated with this IR.
629 AnalysisResultLists.erase(ResultsListI);
632 /// \brief Clear all analysis results cached by this AnalysisManager.
634 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
635 /// deletes them. This lets you clean up the AnalysisManager when the set of
636 /// IR units itself has potentially changed, and thus we can't even look up a
637 /// a result and invalidate/clear it directly.
639 AnalysisResults.clear();
640 AnalysisResultLists.clear();
643 /// \brief Get the result of an analysis pass for a given IR unit.
645 /// Runs the analysis if a cached result is not available.
646 template <typename PassT>
647 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
648 assert(AnalysisPasses.count(PassT::ID()) &&
649 "This analysis pass was not registered prior to being queried");
650 ResultConceptT &ResultConcept =
651 getResultImpl(PassT::ID(), IR, ExtraArgs...);
652 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
653 PreservedAnalyses, Invalidator>
655 return static_cast<ResultModelT &>(ResultConcept).Result;
658 /// \brief Get the cached result of an analysis pass for a given IR unit.
660 /// This method never runs the analysis.
662 /// \returns null if there is no cached result.
663 template <typename PassT>
664 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
665 assert(AnalysisPasses.count(PassT::ID()) &&
666 "This analysis pass was not registered prior to being queried");
668 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
672 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
673 PreservedAnalyses, Invalidator>
675 return &static_cast<ResultModelT *>(ResultConcept)->Result;
678 /// \brief Register an analysis pass with the manager.
680 /// The parameter is a callable whose result is an analysis pass. This allows
681 /// passing in a lambda to construct the analysis.
683 /// The analysis type to register is the type returned by calling the \c
684 /// PassBuilder argument. If that type has already been registered, then the
685 /// argument will not be called and this function will return false.
686 /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
687 /// and this function returns true.
689 /// (Note: Although the return value of this function indicates whether or not
690 /// an analysis was previously registered, there intentionally isn't a way to
691 /// query this directly. Instead, you should just register all the analyses
692 /// you might want and let this class run them lazily. This idiom lets us
693 /// minimize the number of times we have to look up analyses in our
695 template <typename PassBuilderT>
696 bool registerPass(PassBuilderT &&PassBuilder) {
697 typedef decltype(PassBuilder()) PassT;
698 typedef detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses,
699 Invalidator, ExtraArgTs...>
702 auto &PassPtr = AnalysisPasses[PassT::ID()];
704 // Already registered this pass type!
707 // Construct a new model around the instance returned by the builder.
708 PassPtr.reset(new PassModelT(PassBuilder()));
712 /// \brief Invalidate a specific analysis pass for an IR module.
714 /// Note that the analysis result can disregard invalidation, if it determines
715 /// it is in fact still valid.
716 template <typename PassT> void invalidate(IRUnitT &IR) {
717 assert(AnalysisPasses.count(PassT::ID()) &&
718 "This analysis pass was not registered prior to being invalidated");
719 invalidateImpl(PassT::ID(), IR);
722 /// \brief Invalidate cached analyses for an IR unit.
724 /// Walk through all of the analyses pertaining to this unit of IR and
725 /// invalidate them, unless they are preserved by the PreservedAnalyses set.
726 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
727 // We're done if all analyses on this IR unit are preserved.
728 if (PA.allAnalysesInSetPreserved<AllAnalysesOn<IRUnitT>>())
732 dbgs() << "Invalidating all non-preserved analyses for: " << IR.getName()
735 // Track whether each analysis's result is invalidated in
736 // IsResultInvalidated.
737 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
738 Invalidator Inv(IsResultInvalidated, AnalysisResults);
739 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
740 for (auto &AnalysisResultPair : ResultsList) {
741 // This is basically the same thing as Invalidator::invalidate, but we
742 // can't call it here because we're operating on the type-erased result.
743 // Moreover if we instead called invalidate() directly, it would do an
744 // unnecessary look up in ResultsList.
745 AnalysisKey *ID = AnalysisResultPair.first;
746 auto &Result = *AnalysisResultPair.second;
748 auto IMapI = IsResultInvalidated.find(ID);
749 if (IMapI != IsResultInvalidated.end())
750 // This result was already handled via the Invalidator.
753 // Try to invalidate the result, giving it the Invalidator so it can
754 // recursively query for any dependencies it has and record the result.
755 // Note that we cannot reuse 'IMapI' here or pre-insert the ID, as
756 // Result.invalidate may insert things into the map, invalidating our
759 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, Inv)})
762 assert(Inserted && "Should never have already inserted this ID, likely "
763 "indicates a cycle!");
766 // Now erase the results that were marked above as invalidated.
767 if (!IsResultInvalidated.empty()) {
768 for (auto I = ResultsList.begin(), E = ResultsList.end(); I != E;) {
769 AnalysisKey *ID = I->first;
770 if (!IsResultInvalidated.lookup(ID)) {
776 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
779 I = ResultsList.erase(I);
780 AnalysisResults.erase({ID, &IR});
784 if (ResultsList.empty())
785 AnalysisResultLists.erase(&IR);
789 /// \brief Look up a registered analysis pass.
790 PassConceptT &lookUpPass(AnalysisKey *ID) {
791 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
792 assert(PI != AnalysisPasses.end() &&
793 "Analysis passes must be registered prior to being queried!");
797 /// \brief Look up a registered analysis pass.
798 const PassConceptT &lookUpPass(AnalysisKey *ID) const {
799 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
800 assert(PI != AnalysisPasses.end() &&
801 "Analysis passes must be registered prior to being queried!");
805 /// \brief Get an analysis result, running the pass if necessary.
806 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
807 ExtraArgTs... ExtraArgs) {
808 typename AnalysisResultMapT::iterator RI;
810 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
811 std::make_pair(ID, &IR), typename AnalysisResultListT::iterator()));
813 // If we don't have a cached result for this function, look up the pass and
814 // run it to produce a result, which we then add to the cache.
816 auto &P = this->lookUpPass(ID);
818 dbgs() << "Running analysis: " << P.name() << "\n";
819 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
820 ResultList.emplace_back(ID, P.run(IR, *this, ExtraArgs...));
822 // P.run may have inserted elements into AnalysisResults and invalidated
824 RI = AnalysisResults.find({ID, &IR});
825 assert(RI != AnalysisResults.end() && "we just inserted it!");
827 RI->second = std::prev(ResultList.end());
830 return *RI->second->second;
833 /// \brief Get a cached analysis result or return null.
834 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
835 typename AnalysisResultMapT::const_iterator RI =
836 AnalysisResults.find({ID, &IR});
837 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
840 /// \brief Invalidate a function pass result.
841 void invalidateImpl(AnalysisKey *ID, IRUnitT &IR) {
842 typename AnalysisResultMapT::iterator RI =
843 AnalysisResults.find({ID, &IR});
844 if (RI == AnalysisResults.end())
848 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
850 AnalysisResultLists[&IR].erase(RI->second);
851 AnalysisResults.erase(RI);
854 /// \brief Map type from module analysis pass ID to pass concept pointer.
855 typedef DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
857 /// \brief Collection of module analysis passes, indexed by ID.
858 AnalysisPassMapT AnalysisPasses;
860 /// \brief Map from function to a list of function analysis results.
862 /// Provides linear time removal of all analysis results for a function and
863 /// the ultimate storage for a particular cached analysis result.
864 AnalysisResultListMapT AnalysisResultLists;
866 /// \brief Map from an analysis ID and function to a particular cached
868 AnalysisResultMapT AnalysisResults;
870 /// \brief Indicates whether we log to \c llvm::dbgs().
874 extern template class AnalysisManager<Module>;
875 /// \brief Convenience typedef for the Module analysis manager.
876 typedef AnalysisManager<Module> ModuleAnalysisManager;
878 extern template class AnalysisManager<Function>;
879 /// \brief Convenience typedef for the Function analysis manager.
880 typedef AnalysisManager<Function> FunctionAnalysisManager;
882 /// \brief An analysis over an "outer" IR unit that provides access to an
883 /// analysis manager over an "inner" IR unit. The inner unit must be contained
884 /// in the outer unit.
886 /// Fore example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
887 /// an analysis over Modules (the "outer" unit) that provides access to a
888 /// Function analysis manager. The FunctionAnalysisManager is the "inner"
889 /// manager being proxied, and Functions are the "inner" unit. The inner/outer
890 /// relationship is valid because each Function is contained in one Module.
892 /// If you're (transitively) within a pass manager for an IR unit U that
893 /// contains IR unit V, you should never use an analysis manager over V, except
894 /// via one of these proxies.
896 /// Note that the proxy's result is a move-only RAII object. The validity of
897 /// the analyses in the inner analysis manager is tied to its lifetime.
898 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
899 class InnerAnalysisManagerProxy
900 : public AnalysisInfoMixin<
901 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
905 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
906 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
907 // We have to null out the analysis manager in the moved-from state
908 // because we are taking ownership of the responsibilty to clear the
910 Arg.InnerAM = nullptr;
912 Result &operator=(Result &&RHS) {
913 InnerAM = RHS.InnerAM;
914 // We have to null out the analysis manager in the moved-from state
915 // because we are taking ownership of the responsibilty to clear the
917 RHS.InnerAM = nullptr;
921 // InnerAM is cleared in a moved from state where there is nothing to do.
925 // Clear out the analysis manager if we're being destroyed -- it means we
926 // didn't even see an invalidate call when we got invalidated.
930 /// \brief Accessor for the analysis manager.
931 AnalysisManagerT &getManager() { return *InnerAM; }
933 /// \brief Handler for invalidation of the outer IR unit, \c IRUnitT.
935 /// If the proxy analysis itself is not preserved, we assume that the set of
936 /// inner IR objects contained in IRUnit may have changed. In this case,
937 /// we have to call \c clear() on the inner analysis manager, as it may now
938 /// have stale pointers to its inner IR objects.
940 /// Regardless of whether the proxy analysis is marked as preserved, all of
941 /// the analyses in the inner analysis manager are potentially invalidated
942 /// based on the set of preserved analyses.
944 IRUnitT &IR, const PreservedAnalyses &PA,
945 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv);
948 AnalysisManagerT *InnerAM;
951 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
952 : InnerAM(&InnerAM) {}
954 /// \brief Run the analysis pass and create our proxy result object.
956 /// This doesn't do any interesting work; it is primarily used to insert our
957 /// proxy result object into the outer analysis cache so that we can proxy
958 /// invalidation to the inner analysis manager.
959 Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM,
961 return Result(*InnerAM);
965 friend AnalysisInfoMixin<
966 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
967 static AnalysisKey Key;
969 AnalysisManagerT *InnerAM;
972 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
974 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
976 /// Provide the \c FunctionAnalysisManager to \c Module proxy.
977 typedef InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>
978 FunctionAnalysisManagerModuleProxy;
980 /// Specialization of the invalidate method for the \c
981 /// FunctionAnalysisManagerModuleProxy's result.
983 bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
984 Module &M, const PreservedAnalyses &PA,
985 ModuleAnalysisManager::Invalidator &Inv);
987 // Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
989 extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
992 /// \brief An analysis over an "inner" IR unit that provides access to an
993 /// analysis manager over a "outer" IR unit. The inner unit must be contained
994 /// in the outer unit.
996 /// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
997 /// analysis over Functions (the "inner" unit) which provides access to a Module
998 /// analysis manager. The ModuleAnalysisManager is the "outer" manager being
999 /// proxied, and Modules are the "outer" IR unit. The inner/outer relationship
1000 /// is valid because each Function is contained in one Module.
1002 /// This proxy only exposes the const interface of the outer analysis manager,
1003 /// to indicate that you cannot cause an outer analysis to run from within an
1004 /// inner pass. Instead, you must rely on the \c getCachedResult API.
1006 /// This proxy doesn't manage invalidation in any way -- that is handled by the
1007 /// recursive return path of each layer of the pass manager. A consequence of
1008 /// this is the outer analyses may be stale. We invalidate the outer analyses
1009 /// only when we're done running passes over the inner IR units.
1010 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1011 class OuterAnalysisManagerProxy
1012 : public AnalysisInfoMixin<
1013 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
1015 /// \brief Result proxy object for \c OuterAnalysisManagerProxy.
1018 explicit Result(const AnalysisManagerT &AM) : AM(&AM) {}
1020 const AnalysisManagerT &getManager() const { return *AM; }
1022 /// \brief Handle invalidation by ignoring it; this pass is immutable.
1024 IRUnitT &, const PreservedAnalyses &,
1025 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &) {
1029 /// Register a deferred invalidation event for when the outer analysis
1030 /// manager processes its invalidations.
1031 template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
1032 void registerOuterAnalysisInvalidation() {
1033 AnalysisKey *OuterID = OuterAnalysisT::ID();
1034 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
1036 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
1037 // Note, this is a linear scan. If we end up with large numbers of
1038 // analyses that all trigger invalidation on the same outer analysis,
1039 // this entire system should be changed to some other deterministic
1040 // data structure such as a `SetVector` of a pair of pointers.
1041 auto InvalidatedIt = std::find(InvalidatedIDList.begin(),
1042 InvalidatedIDList.end(), InvalidatedID);
1043 if (InvalidatedIt == InvalidatedIDList.end())
1044 InvalidatedIDList.push_back(InvalidatedID);
1047 /// Access the map from outer analyses to deferred invalidation requiring
1049 const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> &
1050 getOuterInvalidations() const {
1051 return OuterAnalysisInvalidationMap;
1055 const AnalysisManagerT *AM;
1057 /// A map from an outer analysis ID to the set of this IR-unit's analyses
1058 /// which need to be invalidated.
1059 SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2>
1060 OuterAnalysisInvalidationMap;
1063 OuterAnalysisManagerProxy(const AnalysisManagerT &AM) : AM(&AM) {}
1065 /// \brief Run the analysis pass and create our proxy result object.
1066 /// Nothing to see here, it just forwards the \c AM reference into the
1068 Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &,
1074 friend AnalysisInfoMixin<
1075 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
1076 static AnalysisKey Key;
1078 const AnalysisManagerT *AM;
1081 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1083 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1085 extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
1087 /// Provide the \c ModuleAnalysisManager to \c Function proxy.
1088 typedef OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>
1089 ModuleAnalysisManagerFunctionProxy;
1091 /// \brief Trivial adaptor that maps from a module to its functions.
1093 /// Designed to allow composition of a FunctionPass(Manager) and
1094 /// a ModulePassManager, by running the FunctionPass(Manager) over every
1095 /// function in the module.
1097 /// Function passes run within this adaptor can rely on having exclusive access
1098 /// to the function they are run over. They should not read or modify any other
1099 /// functions! Other threads or systems may be manipulating other functions in
1100 /// the module, and so their state should never be relied on.
1101 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1102 /// violate this principle.
1104 /// Function passes can also read the module containing the function, but they
1105 /// should not modify that module outside of the use lists of various globals.
1106 /// For example, a function pass is not permitted to add functions to the
1108 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1109 /// violate this principle.
1111 /// Note that although function passes can access module analyses, module
1112 /// analyses are not invalidated while the function passes are running, so they
1113 /// may be stale. Function analyses will not be stale.
1114 template <typename FunctionPassT>
1115 class ModuleToFunctionPassAdaptor
1116 : public PassInfoMixin<ModuleToFunctionPassAdaptor<FunctionPassT>> {
1118 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
1119 : Pass(std::move(Pass)) {}
1121 /// \brief Runs the function pass across every function in the module.
1122 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) {
1123 FunctionAnalysisManager &FAM =
1124 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1126 PreservedAnalyses PA = PreservedAnalyses::all();
1127 for (Function &F : M) {
1128 if (F.isDeclaration())
1131 PreservedAnalyses PassPA = Pass.run(F, FAM);
1133 // We know that the function pass couldn't have invalidated any other
1134 // function's analyses (that's the contract of a function pass), so
1135 // directly handle the function analysis manager's invalidation here.
1136 FAM.invalidate(F, PassPA);
1138 // Then intersect the preserved set so that invalidation of module
1139 // analyses will eventually occur when the module pass completes.
1140 PA.intersect(std::move(PassPA));
1143 // The FunctionAnalysisManagerModuleProxy is preserved because (we assume)
1144 // the function passes we ran didn't add or remove any functions.
1146 // We also preserve all analyses on Functions, because we did all the
1147 // invalidation we needed to do above.
1148 PA.preserveSet<AllAnalysesOn<Function>>();
1149 PA.preserve<FunctionAnalysisManagerModuleProxy>();
1157 /// \brief A function to deduce a function pass type and wrap it in the
1158 /// templated adaptor.
1159 template <typename FunctionPassT>
1160 ModuleToFunctionPassAdaptor<FunctionPassT>
1161 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
1162 return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
1165 /// \brief A utility pass template to force an analysis result to be available.
1167 /// If there are extra arguments at the pass's run level there may also be
1168 /// extra arguments to the analysis manager's \c getResult routine. We can't
1169 /// guess how to effectively map the arguments from one to the other, and so
1170 /// this specialization just ignores them.
1172 /// Specific patterns of run-method extra arguments and analysis manager extra
1173 /// arguments will have to be defined as appropriate specializations.
1174 template <typename AnalysisT, typename IRUnitT,
1175 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
1176 typename... ExtraArgTs>
1177 struct RequireAnalysisPass
1178 : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
1180 /// \brief Run this pass over some unit of IR.
1182 /// This pass can be run over any unit of IR and use any analysis manager
1183 /// provided they satisfy the basic API requirements. When this pass is
1184 /// created, these methods can be instantiated to satisfy whatever the
1185 /// context requires.
1186 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
1187 ExtraArgTs &&... Args) {
1188 (void)AM.template getResult<AnalysisT>(Arg,
1189 std::forward<ExtraArgTs>(Args)...);
1191 return PreservedAnalyses::all();
1195 /// \brief A no-op pass template which simply forces a specific analysis result
1196 /// to be invalidated.
1197 template <typename AnalysisT>
1198 struct InvalidateAnalysisPass
1199 : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
1200 /// \brief Run this pass over some unit of IR.
1202 /// This pass can be run over any unit of IR and use any analysis manager,
1203 /// provided they satisfy the basic API requirements. When this pass is
1204 /// created, these methods can be instantiated to satisfy whatever the
1205 /// context requires.
1206 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1207 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
1208 auto PA = PreservedAnalyses::all();
1209 PA.abandon<AnalysisT>();
1214 /// \brief A utility pass that does nothing, but preserves no analyses.
1216 /// Because this preserves no analyses, any analysis passes queried after this
1217 /// pass runs will recompute fresh results.
1218 struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
1219 /// \brief Run this pass over some unit of IR.
1220 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1221 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
1222 return PreservedAnalyses::none();
1226 /// A utility pass template that simply runs another pass multiple times.
1228 /// This can be useful when debugging or testing passes. It also serves as an
1229 /// example of how to extend the pass manager in ways beyond composition.
1230 template <typename PassT>
1231 class RepeatedPass : public PassInfoMixin<RepeatedPass<PassT>> {
1233 RepeatedPass(int Count, PassT P) : Count(Count), P(std::move(P)) {}
1235 template <typename IRUnitT, typename AnalysisManagerT, typename... Ts>
1236 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, Ts &&... Args) {
1237 auto PA = PreservedAnalyses::all();
1238 for (int i = 0; i < Count; ++i)
1239 PA.intersect(P.run(Arg, AM, std::forward<Ts>(Args)...));
1248 template <typename PassT>
1249 RepeatedPass<PassT> createRepeatedPass(int Count, PassT P) {
1250 return RepeatedPass<PassT>(Count, std::move(P));