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/IR/Function.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/PassManagerInternal.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/type_traits.h"
59 /// \brief An abstract set of preserved analyses following a transformation pass
62 /// When a transformation pass is run, it can return a set of analyses whose
63 /// results were preserved by that transformation. The default set is "none",
64 /// and preserving analyses must be done explicitly.
66 /// There is also an explicit all state which can be used (for example) when
67 /// the IR is not mutated at all.
68 class PreservedAnalyses {
70 // We have to explicitly define all the special member functions because MSVC
71 // refuses to generate them.
72 PreservedAnalyses() {}
73 PreservedAnalyses(const PreservedAnalyses &Arg)
74 : PreservedPassIDs(Arg.PreservedPassIDs) {}
75 PreservedAnalyses(PreservedAnalyses &&Arg)
76 : PreservedPassIDs(std::move(Arg.PreservedPassIDs)) {}
77 friend void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
79 swap(LHS.PreservedPassIDs, RHS.PreservedPassIDs);
81 PreservedAnalyses &operator=(PreservedAnalyses RHS) {
86 /// \brief Convenience factory function for the empty preserved set.
87 static PreservedAnalyses none() { return PreservedAnalyses(); }
89 /// \brief Construct a special preserved set that preserves all passes.
90 static PreservedAnalyses all() {
92 PA.PreservedPassIDs.insert((void *)AllPassesID);
96 /// \brief Mark a particular pass as preserved, adding it to the set.
97 template <typename PassT> void preserve() { preserve(PassT::ID()); }
99 /// \brief Mark an abstract PassID as preserved, adding it to the set.
100 void preserve(void *PassID) {
101 if (!areAllPreserved())
102 PreservedPassIDs.insert(PassID);
105 /// \brief Intersect this set with another in place.
107 /// This is a mutating operation on this preserved set, removing all
108 /// preserved passes which are not also preserved in the argument.
109 void intersect(const PreservedAnalyses &Arg) {
110 if (Arg.areAllPreserved())
112 if (areAllPreserved()) {
113 PreservedPassIDs = Arg.PreservedPassIDs;
116 for (void *P : PreservedPassIDs)
117 if (!Arg.PreservedPassIDs.count(P))
118 PreservedPassIDs.erase(P);
121 /// \brief Intersect this set with a temporary other set in place.
123 /// This is a mutating operation on this preserved set, removing all
124 /// preserved passes which are not also preserved in the argument.
125 void intersect(PreservedAnalyses &&Arg) {
126 if (Arg.areAllPreserved())
128 if (areAllPreserved()) {
129 PreservedPassIDs = std::move(Arg.PreservedPassIDs);
132 for (void *P : PreservedPassIDs)
133 if (!Arg.PreservedPassIDs.count(P))
134 PreservedPassIDs.erase(P);
137 /// \brief Query whether a pass is marked as preserved by this set.
138 template <typename PassT> bool preserved() const {
139 return preserved(PassT::ID());
142 /// \brief Query whether an abstract pass ID is marked as preserved by this
144 bool preserved(void *PassID) const {
145 return PreservedPassIDs.count((void *)AllPassesID) ||
146 PreservedPassIDs.count(PassID);
149 /// \brief Test whether all passes are preserved.
151 /// This is used primarily to optimize for the case of no changes which will
152 /// common in many scenarios.
153 bool areAllPreserved() const {
154 return PreservedPassIDs.count((void *)AllPassesID);
158 // Note that this must not be -1 or -2 as those are already used by the
160 static const uintptr_t AllPassesID = (intptr_t)(-3);
162 SmallPtrSet<void *, 2> PreservedPassIDs;
165 // Forward declare the analysis manager template.
166 template <typename IRUnitT> class AnalysisManager;
168 /// \brief Manages a sequence of passes over units of IR.
170 /// A pass manager contains a sequence of passes to run over units of IR. It is
171 /// itself a valid pass over that unit of IR, and when over some given IR will
172 /// run each pass in sequence. This is the primary and most basic building
173 /// block of a pass pipeline.
175 /// If it is run with an \c AnalysisManager<IRUnitT> argument, it will propagate
176 /// that analysis manager to each pass it runs, as well as calling the analysis
177 /// manager's invalidation routine with the PreservedAnalyses of each pass it
179 template <typename IRUnitT> class PassManager {
181 /// \brief Construct a pass manager.
183 /// It can be passed a flag to get debug logging as the passes are run.
184 PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
185 // We have to explicitly define all the special member functions because MSVC
186 // refuses to generate them.
187 PassManager(PassManager &&Arg)
188 : Passes(std::move(Arg.Passes)),
189 DebugLogging(std::move(Arg.DebugLogging)) {}
190 PassManager &operator=(PassManager &&RHS) {
191 Passes = std::move(RHS.Passes);
192 DebugLogging = std::move(RHS.DebugLogging);
196 /// \brief Run all of the passes in this manager over the IR.
197 PreservedAnalyses run(IRUnitT &IR, AnalysisManager<IRUnitT> *AM = nullptr) {
198 PreservedAnalyses PA = PreservedAnalyses::all();
201 dbgs() << "Starting pass manager run.\n";
203 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
205 dbgs() << "Running pass: " << Passes[Idx]->name() << "\n";
207 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM);
209 // If we have an active analysis manager at this level we want to ensure
210 // we update it as each pass runs and potentially invalidates analyses.
211 // We also update the preserved set of analyses based on what analyses we
212 // have already handled the invalidation for here and don't need to
213 // invalidate when finished.
215 PassPA = AM->invalidate(IR, std::move(PassPA));
217 // Finally, we intersect the final preserved analyses to compute the
218 // aggregate preserved set for this pass manager.
219 PA.intersect(std::move(PassPA));
221 // FIXME: Historically, the pass managers all called the LLVM context's
222 // yield function here. We don't have a generic way to acquire the
223 // context and it isn't yet clear what the right pattern is for yielding
224 // in the new pass manager so it is currently omitted.
225 //IR.getContext().yield();
229 dbgs() << "Finished pass manager run.\n";
234 template <typename PassT> void addPass(PassT Pass) {
235 typedef detail::PassModel<IRUnitT, PassT> PassModelT;
236 Passes.emplace_back(new PassModelT(std::move(Pass)));
239 static StringRef name() { return "PassManager"; }
242 typedef detail::PassConcept<IRUnitT> PassConceptT;
244 PassManager(const PassManager &) = delete;
245 PassManager &operator=(const PassManager &) = delete;
247 std::vector<std::unique_ptr<PassConceptT>> Passes;
249 /// \brief Flag indicating whether we should do debug logging.
253 /// \brief Convenience typedef for a pass manager over modules.
254 typedef PassManager<Module> ModulePassManager;
256 /// \brief Convenience typedef for a pass manager over functions.
257 typedef PassManager<Function> FunctionPassManager;
261 /// \brief A CRTP base used to implement analysis managers.
263 /// This class template serves as the boiler plate of an analysis manager. Any
264 /// analysis manager can be implemented on top of this base class. Any
265 /// implementation will be required to provide specific hooks:
268 /// - getCachedResultImpl
271 /// The details of the call pattern are within.
273 /// Note that there is also a generic analysis manager template which implements
274 /// the above required functions along with common datastructures used for
275 /// managing analyses. This base class is factored so that if you need to
276 /// customize the handling of a specific IR unit, you can do so without
277 /// replicating *all* of the boilerplate.
278 template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
279 DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
280 const DerivedT *derived_this() const {
281 return static_cast<const DerivedT *>(this);
284 AnalysisManagerBase(const AnalysisManagerBase &) = delete;
285 AnalysisManagerBase &
286 operator=(const AnalysisManagerBase &) = delete;
289 typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
290 typedef detail::AnalysisPassConcept<IRUnitT> PassConceptT;
292 // FIXME: Provide template aliases for the models when we're using C++11 in
293 // a mode supporting them.
295 // We have to explicitly define all the special member functions because MSVC
296 // refuses to generate them.
297 AnalysisManagerBase() {}
298 AnalysisManagerBase(AnalysisManagerBase &&Arg)
299 : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
300 AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
301 AnalysisPasses = std::move(RHS.AnalysisPasses);
306 /// \brief Get the result of an analysis pass for this module.
308 /// If there is not a valid cached result in the manager already, this will
309 /// re-run the analysis to produce a valid result.
310 template <typename PassT> typename PassT::Result &getResult(IRUnitT &IR) {
311 assert(AnalysisPasses.count(PassT::ID()) &&
312 "This analysis pass was not registered prior to being queried");
314 ResultConceptT &ResultConcept =
315 derived_this()->getResultImpl(PassT::ID(), IR);
316 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
318 return static_cast<ResultModelT &>(ResultConcept).Result;
321 /// \brief Get the cached result of an analysis pass for this module.
323 /// This method never runs the analysis.
325 /// \returns null if there is no cached result.
326 template <typename PassT>
327 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
328 assert(AnalysisPasses.count(PassT::ID()) &&
329 "This analysis pass was not registered prior to being queried");
331 ResultConceptT *ResultConcept =
332 derived_this()->getCachedResultImpl(PassT::ID(), IR);
336 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
338 return &static_cast<ResultModelT *>(ResultConcept)->Result;
341 /// \brief Register an analysis pass with the manager.
343 /// This provides an initialized and set-up analysis pass to the analysis
344 /// manager. Whomever is setting up analysis passes must use this to populate
345 /// the manager with all of the analysis passes available.
346 template <typename PassT> void registerPass(PassT Pass) {
347 assert(!AnalysisPasses.count(PassT::ID()) &&
348 "Registered the same analysis pass twice!");
349 typedef detail::AnalysisPassModel<IRUnitT, PassT> PassModelT;
350 AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
353 /// \brief Invalidate a specific analysis pass for an IR module.
355 /// Note that the analysis result can disregard invalidation.
356 template <typename PassT> void invalidate(IRUnitT &IR) {
357 assert(AnalysisPasses.count(PassT::ID()) &&
358 "This analysis pass was not registered prior to being invalidated");
359 derived_this()->invalidateImpl(PassT::ID(), IR);
362 /// \brief Invalidate analyses cached for an IR unit.
364 /// Walk through all of the analyses pertaining to this unit of IR and
365 /// invalidate them unless they are preserved by the PreservedAnalyses set.
366 /// We accept the PreservedAnalyses set by value and update it with each
367 /// analyis pass which has been successfully invalidated and thus can be
368 /// preserved going forward. The updated set is returned.
369 PreservedAnalyses invalidate(IRUnitT &IR, PreservedAnalyses PA) {
370 return derived_this()->invalidateImpl(IR, std::move(PA));
374 /// \brief Lookup a registered analysis pass.
375 PassConceptT &lookupPass(void *PassID) {
376 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
377 assert(PI != AnalysisPasses.end() &&
378 "Analysis passes must be registered prior to being queried!");
382 /// \brief Lookup a registered analysis pass.
383 const PassConceptT &lookupPass(void *PassID) const {
384 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
385 assert(PI != AnalysisPasses.end() &&
386 "Analysis passes must be registered prior to being queried!");
391 /// \brief Map type from module analysis pass ID to pass concept pointer.
392 typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
394 /// \brief Collection of module analysis passes, indexed by ID.
395 AnalysisPassMapT AnalysisPasses;
398 } // End namespace detail
400 /// \brief A generic analysis pass manager with lazy running and caching of
403 /// This analysis manager can be used for any IR unit where the address of the
404 /// IR unit sufficies as its identity. It manages the cache for a unit of IR via
405 /// the address of each unit of IR cached.
406 template <typename IRUnitT>
407 class AnalysisManager
408 : public detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> {
409 friend class detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT>;
410 typedef detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> BaseT;
411 typedef typename BaseT::ResultConceptT ResultConceptT;
412 typedef typename BaseT::PassConceptT PassConceptT;
415 // Most public APIs are inherited from the CRTP base class.
417 /// \brief Construct an empty analysis manager.
419 /// A flag can be passed to indicate that the manager should perform debug
421 AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
423 // We have to explicitly define all the special member functions because MSVC
424 // refuses to generate them.
425 AnalysisManager(AnalysisManager &&Arg)
426 : BaseT(std::move(static_cast<BaseT &>(Arg))),
427 AnalysisResults(std::move(Arg.AnalysisResults)),
428 DebugLogging(std::move(Arg.DebugLogging)) {}
429 AnalysisManager &operator=(AnalysisManager &&RHS) {
430 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
431 AnalysisResults = std::move(RHS.AnalysisResults);
432 DebugLogging = std::move(RHS.DebugLogging);
436 /// \brief Returns true if the analysis manager has an empty results cache.
438 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
439 "The storage and index of analysis results disagree on how many "
441 return AnalysisResults.empty();
444 /// \brief Clear the analysis result cache.
446 /// This routine allows cleaning up when the set of IR units itself has
447 /// potentially changed, and thus we can't even look up a a result and
448 /// invalidate it directly. Notably, this does *not* call invalidate functions
449 /// as there is nothing to be done for them.
451 AnalysisResults.clear();
452 AnalysisResultLists.clear();
456 AnalysisManager(const AnalysisManager &) = delete;
457 AnalysisManager &operator=(const AnalysisManager &) = delete;
459 /// \brief Get an analysis result, running the pass if necessary.
460 ResultConceptT &getResultImpl(void *PassID, IRUnitT &IR) {
461 typename AnalysisResultMapT::iterator RI;
463 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
464 std::make_pair(PassID, &IR), typename AnalysisResultListT::iterator()));
466 // If we don't have a cached result for this function, look up the pass and
467 // run it to produce a result, which we then add to the cache.
469 auto &P = this->lookupPass(PassID);
471 dbgs() << "Running analysis: " << P.name() << "\n";
472 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
473 ResultList.emplace_back(PassID, P.run(IR, this));
475 // P.run may have inserted elements into AnalysisResults and invalidated
477 RI = AnalysisResults.find(std::make_pair(PassID, &IR));
478 assert(RI != AnalysisResults.end() && "we just inserted it!");
480 RI->second = std::prev(ResultList.end());
483 return *RI->second->second;
486 /// \brief Get a cached analysis result or return null.
487 ResultConceptT *getCachedResultImpl(void *PassID, IRUnitT &IR) const {
488 typename AnalysisResultMapT::const_iterator RI =
489 AnalysisResults.find(std::make_pair(PassID, &IR));
490 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
493 /// \brief Invalidate a function pass result.
494 void invalidateImpl(void *PassID, IRUnitT &IR) {
495 typename AnalysisResultMapT::iterator RI =
496 AnalysisResults.find(std::make_pair(PassID, &IR));
497 if (RI == AnalysisResults.end())
501 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
503 AnalysisResultLists[&IR].erase(RI->second);
504 AnalysisResults.erase(RI);
507 /// \brief Invalidate the results for a function..
508 PreservedAnalyses invalidateImpl(IRUnitT &IR, PreservedAnalyses PA) {
509 // Short circuit for a common case of all analyses being preserved.
510 if (PA.areAllPreserved())
511 return std::move(PA);
514 dbgs() << "Invalidating all non-preserved analyses for: "
515 << IR.getName() << "\n";
517 // Clear all the invalidated results associated specifically with this
519 SmallVector<void *, 8> InvalidatedPassIDs;
520 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
521 for (typename AnalysisResultListT::iterator I = ResultsList.begin(),
522 E = ResultsList.end();
524 void *PassID = I->first;
526 // Pass the invalidation down to the pass itself to see if it thinks it is
527 // necessary. The analysis pass can return false if no action on the part
528 // of the analysis manager is required for this invalidation event.
529 if (I->second->invalidate(IR, PA)) {
531 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
534 InvalidatedPassIDs.push_back(I->first);
535 I = ResultsList.erase(I);
540 // After handling each pass, we mark it as preserved. Once we've
541 // invalidated any stale results, the rest of the system is allowed to
542 // start preserving this analysis again.
545 while (!InvalidatedPassIDs.empty())
546 AnalysisResults.erase(
547 std::make_pair(InvalidatedPassIDs.pop_back_val(), &IR));
548 if (ResultsList.empty())
549 AnalysisResultLists.erase(&IR);
551 return std::move(PA);
554 /// \brief List of function analysis pass IDs and associated concept pointers.
556 /// Requires iterators to be valid across appending new entries and arbitrary
557 /// erases. Provides both the pass ID and concept pointer such that it is
558 /// half of a bijection and provides storage for the actual result concept.
559 typedef std::list<std::pair<
560 void *, std::unique_ptr<detail::AnalysisResultConcept<IRUnitT>>>>
563 /// \brief Map type from function pointer to our custom list type.
564 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
566 /// \brief Map from function to a list of function analysis results.
568 /// Provides linear time removal of all analysis results for a function and
569 /// the ultimate storage for a particular cached analysis result.
570 AnalysisResultListMapT AnalysisResultLists;
572 /// \brief Map type from a pair of analysis ID and function pointer to an
573 /// iterator into a particular result list.
574 typedef DenseMap<std::pair<void *, IRUnitT *>,
575 typename AnalysisResultListT::iterator> AnalysisResultMapT;
577 /// \brief Map from an analysis ID and function to a particular cached
579 AnalysisResultMapT AnalysisResults;
581 /// \brief A flag indicating whether debug logging is enabled.
585 /// \brief Convenience typedef for the Module analysis manager.
586 typedef AnalysisManager<Module> ModuleAnalysisManager;
588 /// \brief Convenience typedef for the Function analysis manager.
589 typedef AnalysisManager<Function> FunctionAnalysisManager;
591 /// \brief A module analysis which acts as a proxy for a function analysis
594 /// This primarily proxies invalidation information from the module analysis
595 /// manager and module pass manager to a function analysis manager. You should
596 /// never use a function analysis manager from within (transitively) a module
597 /// pass manager unless your parent module pass has received a proxy result
599 class FunctionAnalysisManagerModuleProxy {
603 static void *ID() { return (void *)&PassID; }
605 static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
607 explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
609 // We have to explicitly define all the special member functions because MSVC
610 // refuses to generate them.
611 FunctionAnalysisManagerModuleProxy(
612 const FunctionAnalysisManagerModuleProxy &Arg)
614 FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
615 : FAM(std::move(Arg.FAM)) {}
616 FunctionAnalysisManagerModuleProxy &
617 operator=(FunctionAnalysisManagerModuleProxy RHS) {
618 std::swap(FAM, RHS.FAM);
622 /// \brief Run the analysis pass and create our proxy result object.
624 /// This doesn't do any interesting work, it is primarily used to insert our
625 /// proxy result object into the module analysis cache so that we can proxy
626 /// invalidation to the function analysis manager.
628 /// In debug builds, it will also assert that the analysis manager is empty
629 /// as no queries should arrive at the function analysis manager prior to
630 /// this analysis being requested.
631 Result run(Module &M);
636 FunctionAnalysisManager *FAM;
639 /// \brief The result proxy object for the
640 /// \c FunctionAnalysisManagerModuleProxy.
642 /// See its documentation for more information.
643 class FunctionAnalysisManagerModuleProxy::Result {
645 explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
646 // We have to explicitly define all the special member functions because MSVC
647 // refuses to generate them.
648 Result(const Result &Arg) : FAM(Arg.FAM) {}
649 Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
650 Result &operator=(Result RHS) {
651 std::swap(FAM, RHS.FAM);
656 /// \brief Accessor for the \c FunctionAnalysisManager.
657 FunctionAnalysisManager &getManager() { return *FAM; }
659 /// \brief Handler for invalidation of the module.
661 /// If this analysis itself is preserved, then we assume that the set of \c
662 /// Function objects in the \c Module hasn't changed and thus we don't need
663 /// to invalidate *all* cached data associated with a \c Function* in the \c
664 /// FunctionAnalysisManager.
666 /// Regardless of whether this analysis is marked as preserved, all of the
667 /// analyses in the \c FunctionAnalysisManager are potentially invalidated
668 /// based on the set of preserved analyses.
669 bool invalidate(Module &M, const PreservedAnalyses &PA);
672 FunctionAnalysisManager *FAM;
675 /// \brief A function analysis which acts as a proxy for a module analysis
678 /// This primarily provides an accessor to a parent module analysis manager to
679 /// function passes. Only the const interface of the module analysis manager is
680 /// provided to indicate that once inside of a function analysis pass you
681 /// cannot request a module analysis to actually run. Instead, the user must
682 /// rely on the \c getCachedResult API.
684 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
685 /// the recursive return path of each layer of the pass manager and the
686 /// returned PreservedAnalysis set.
687 class ModuleAnalysisManagerFunctionProxy {
689 /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
692 explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
693 // We have to explicitly define all the special member functions because
694 // MSVC refuses to generate them.
695 Result(const Result &Arg) : MAM(Arg.MAM) {}
696 Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
697 Result &operator=(Result RHS) {
698 std::swap(MAM, RHS.MAM);
702 const ModuleAnalysisManager &getManager() const { return *MAM; }
704 /// \brief Handle invalidation by ignoring it, this pass is immutable.
705 bool invalidate(Function &) { return false; }
708 const ModuleAnalysisManager *MAM;
711 static void *ID() { return (void *)&PassID; }
713 static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
715 ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
717 // We have to explicitly define all the special member functions because MSVC
718 // refuses to generate them.
719 ModuleAnalysisManagerFunctionProxy(
720 const ModuleAnalysisManagerFunctionProxy &Arg)
722 ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
723 : MAM(std::move(Arg.MAM)) {}
724 ModuleAnalysisManagerFunctionProxy &
725 operator=(ModuleAnalysisManagerFunctionProxy RHS) {
726 std::swap(MAM, RHS.MAM);
730 /// \brief Run the analysis pass and create our proxy result object.
731 /// Nothing to see here, it just forwards the \c MAM reference into the
733 Result run(Function &) { return Result(*MAM); }
738 const ModuleAnalysisManager *MAM;
741 /// \brief Trivial adaptor that maps from a module to its functions.
743 /// Designed to allow composition of a FunctionPass(Manager) and
744 /// a ModulePassManager. Note that if this pass is constructed with a pointer
745 /// to a \c ModuleAnalysisManager it will run the
746 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
747 /// pass over the module to enable a \c FunctionAnalysisManager to be used
748 /// within this run safely.
750 /// Function passes run within this adaptor can rely on having exclusive access
751 /// to the function they are run over. They should not read or modify any other
752 /// functions! Other threads or systems may be manipulating other functions in
753 /// the module, and so their state should never be relied on.
754 /// FIXME: Make the above true for all of LLVM's actual passes, some still
755 /// violate this principle.
757 /// Function passes can also read the module containing the function, but they
758 /// should not modify that module outside of the use lists of various globals.
759 /// For example, a function pass is not permitted to add functions to the
761 /// FIXME: Make the above true for all of LLVM's actual passes, some still
762 /// violate this principle.
763 template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
765 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
766 : Pass(std::move(Pass)) {}
767 // We have to explicitly define all the special member functions because MSVC
768 // refuses to generate them.
769 ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
771 ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
772 : Pass(std::move(Arg.Pass)) {}
773 friend void swap(ModuleToFunctionPassAdaptor &LHS,
774 ModuleToFunctionPassAdaptor &RHS) {
776 swap(LHS.Pass, RHS.Pass);
778 ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
783 /// \brief Runs the function pass across every function in the module.
784 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
785 FunctionAnalysisManager *FAM = nullptr;
787 // Setup the function analysis manager from its proxy.
788 FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
790 PreservedAnalyses PA = PreservedAnalyses::all();
791 for (Function &F : M) {
792 if (F.isDeclaration())
795 PreservedAnalyses PassPA = Pass.run(F, FAM);
797 // We know that the function pass couldn't have invalidated any other
798 // function's analyses (that's the contract of a function pass), so
799 // directly handle the function analysis manager's invalidation here and
800 // update our preserved set to reflect that these have already been
803 PassPA = FAM->invalidate(F, std::move(PassPA));
805 // Then intersect the preserved set so that invalidation of module
806 // analyses will eventually occur when the module pass completes.
807 PA.intersect(std::move(PassPA));
810 // By definition we preserve the proxy. This precludes *any* invalidation
811 // of function analyses by the proxy, but that's OK because we've taken
812 // care to invalidate analyses in the function analysis manager
813 // incrementally above.
814 PA.preserve<FunctionAnalysisManagerModuleProxy>();
818 static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
824 /// \brief A function to deduce a function pass type and wrap it in the
825 /// templated adaptor.
826 template <typename FunctionPassT>
827 ModuleToFunctionPassAdaptor<FunctionPassT>
828 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
829 return std::move(ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)));
832 /// \brief A template utility pass to force an analysis result to be available.
834 /// This is a no-op pass which simply forces a specific analysis pass's result
835 /// to be available when it is run.
836 template <typename AnalysisT> struct RequireAnalysisPass {
837 /// \brief Run this pass over some unit of IR.
839 /// This pass can be run over any unit of IR and use any analysis manager
840 /// provided they satisfy the basic API requirements. When this pass is
841 /// created, these methods can be instantiated to satisfy whatever the
842 /// context requires.
843 template <typename IRUnitT>
844 PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
846 (void)AM->template getResult<AnalysisT>(Arg);
848 return PreservedAnalyses::all();
851 static StringRef name() { return "RequireAnalysisPass"; }
854 /// \brief A template utility pass to force an analysis result to be
857 /// This is a no-op pass which simply forces a specific analysis result to be
858 /// invalidated when it is run.
859 template <typename AnalysisT> struct InvalidateAnalysisPass {
860 /// \brief Run this pass over some unit of IR.
862 /// This pass can be run over any unit of IR and use any analysis manager
863 /// provided they satisfy the basic API requirements. When this pass is
864 /// created, these methods can be instantiated to satisfy whatever the
865 /// context requires.
866 template <typename IRUnitT>
867 PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
869 // We have to directly invalidate the analysis result as we can't
870 // enumerate all other analyses and use the preserved set to control it.
871 (void)AM->template invalidate<AnalysisT>(Arg);
873 return PreservedAnalyses::all();
876 static StringRef name() { return "InvalidateAnalysisPass"; }
879 /// \brief A utility pass that does nothing but preserves no analyses.
881 /// As a consequence fo not preserving any analyses, this pass will force all
882 /// analysis passes to be re-run to produce fresh results if any are needed.
883 struct InvalidateAllAnalysesPass {
884 /// \brief Run this pass over some unit of IR.
885 template <typename IRUnitT> PreservedAnalyses run(IRUnitT &Arg) {
886 return PreservedAnalyses::none();
889 static StringRef name() { return "InvalidateAllAnalysesPass"; }