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"
61 // Declare our debug option here so we can refer to it from templates.
62 extern cl::opt<bool> DebugPM;
64 } // End detail namespace
66 /// \brief An abstract set of preserved analyses following a transformation pass
69 /// When a transformation pass is run, it can return a set of analyses whose
70 /// results were preserved by that transformation. The default set is "none",
71 /// and preserving analyses must be done explicitly.
73 /// There is also an explicit all state which can be used (for example) when
74 /// the IR is not mutated at all.
75 class PreservedAnalyses {
77 // We have to explicitly define all the special member functions because MSVC
78 // refuses to generate them.
79 PreservedAnalyses() {}
80 PreservedAnalyses(const PreservedAnalyses &Arg)
81 : PreservedPassIDs(Arg.PreservedPassIDs) {}
82 PreservedAnalyses(PreservedAnalyses &&Arg)
83 : PreservedPassIDs(std::move(Arg.PreservedPassIDs)) {}
84 friend void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
86 swap(LHS.PreservedPassIDs, RHS.PreservedPassIDs);
88 PreservedAnalyses &operator=(PreservedAnalyses RHS) {
93 /// \brief Convenience factory function for the empty preserved set.
94 static PreservedAnalyses none() { return PreservedAnalyses(); }
96 /// \brief Construct a special preserved set that preserves all passes.
97 static PreservedAnalyses all() {
99 PA.PreservedPassIDs.insert((void *)AllPassesID);
103 /// \brief Mark a particular pass as preserved, adding it to the set.
104 template <typename PassT> void preserve() { preserve(PassT::ID()); }
106 /// \brief Mark an abstract PassID as preserved, adding it to the set.
107 void preserve(void *PassID) {
108 if (!areAllPreserved())
109 PreservedPassIDs.insert(PassID);
112 /// \brief Intersect this set with another in place.
114 /// This is a mutating operation on this preserved set, removing all
115 /// preserved passes which are not also preserved in the argument.
116 void intersect(const PreservedAnalyses &Arg) {
117 if (Arg.areAllPreserved())
119 if (areAllPreserved()) {
120 PreservedPassIDs = Arg.PreservedPassIDs;
123 for (void *P : PreservedPassIDs)
124 if (!Arg.PreservedPassIDs.count(P))
125 PreservedPassIDs.erase(P);
128 /// \brief Intersect this set with a temporary other set in place.
130 /// This is a mutating operation on this preserved set, removing all
131 /// preserved passes which are not also preserved in the argument.
132 void intersect(PreservedAnalyses &&Arg) {
133 if (Arg.areAllPreserved())
135 if (areAllPreserved()) {
136 PreservedPassIDs = std::move(Arg.PreservedPassIDs);
139 for (void *P : PreservedPassIDs)
140 if (!Arg.PreservedPassIDs.count(P))
141 PreservedPassIDs.erase(P);
144 /// \brief Query whether a pass is marked as preserved by this set.
145 template <typename PassT> bool preserved() const {
146 return preserved(PassT::ID());
149 /// \brief Query whether an abstract pass ID is marked as preserved by this
151 bool preserved(void *PassID) const {
152 return PreservedPassIDs.count((void *)AllPassesID) ||
153 PreservedPassIDs.count(PassID);
156 /// \brief Test whether all passes are preserved.
158 /// This is used primarily to optimize for the case of no changes which will
159 /// common in many scenarios.
160 bool areAllPreserved() const {
161 return PreservedPassIDs.count((void *)AllPassesID);
165 // Note that this must not be -1 or -2 as those are already used by the
167 static const uintptr_t AllPassesID = (intptr_t)(-3);
169 SmallPtrSet<void *, 2> PreservedPassIDs;
172 // Forward declare the analysis manager template and two typedefs used in the
174 template <typename IRUnitT> class AnalysisManager;
175 typedef AnalysisManager<Module> ModuleAnalysisManager;
176 typedef AnalysisManager<Function> FunctionAnalysisManager;
178 /// \brief Manages a sequence of passes over units of IR.
180 /// A pass manager contains a sequence of passes to run over units of IR. It is
181 /// itself a valid pass over that unit of IR, and when over some given IR will
182 /// run each pass in sequence. This is the primary and most basic building
183 /// block of a pass pipeline.
185 /// If it is run with an \c AnalysisManager<IRUnitT> argument, it will propagate
186 /// that analysis manager to each pass it runs, as well as calling the analysis
187 /// manager's invalidation routine with the PreservedAnalyses of each pass it
189 template <typename IRUnitT> class PassManager {
191 // We have to explicitly define all the special member functions because MSVC
192 // refuses to generate them.
194 PassManager(PassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
195 PassManager &operator=(PassManager &&RHS) {
196 Passes = std::move(RHS.Passes);
200 /// \brief Run all of the passes in this manager over the IR.
201 PreservedAnalyses run(IRUnitT &IR, AnalysisManager<IRUnitT> *AM = nullptr) {
202 PreservedAnalyses PA = PreservedAnalyses::all();
205 dbgs() << "Starting pass manager run.\n";
207 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
209 dbgs() << "Running pass: " << Passes[Idx]->name() << "\n";
211 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM);
213 // If we have an active analysis manager at this level we want to ensure
214 // we update it as each pass runs and potentially invalidates analyses.
215 // We also update the preserved set of analyses based on what analyses we
216 // have already handled the invalidation for here and don't need to
217 // invalidate when finished.
219 PassPA = AM->invalidate(IR, std::move(PassPA));
221 // Finally, we intersect the final preserved analyses to compute the
222 // aggregate preserved set for this pass manager.
223 PA.intersect(std::move(PassPA));
225 // FIXME: Historically, the pass managers all called the LLVM context's
226 // yield function here. We don't have a generic way to acquire the
227 // context and it isn't yet clear what the right pattern is for yielding
228 // in the new pass manager so it is currently omitted.
229 //IR.getContext().yield();
233 dbgs() << "Finished pass manager run.\n";
238 template <typename PassT> void addPass(PassT Pass) {
239 Passes.emplace_back(new PassModel<PassT>(std::move(Pass)));
242 static StringRef name() { return "PassManager"; }
245 // Pull in the concept type and model template specialized for modules.
246 typedef detail::PassConcept<IRUnitT> PassConcept;
247 template <typename PassT>
248 struct PassModel : detail::PassModel<IRUnitT, PassT> {
249 PassModel(PassT Pass)
250 : detail::PassModel<IRUnitT, PassT>(std::move(Pass)) {}
253 PassManager(const PassManager &) LLVM_DELETED_FUNCTION;
254 PassManager &operator=(const PassManager &) LLVM_DELETED_FUNCTION;
256 std::vector<std::unique_ptr<PassConcept>> Passes;
259 /// \brief Convenience typedef for a pass manager over modules.
260 typedef PassManager<Module> ModulePassManager;
262 /// \brief Convenience typedef for a pass manager over functions.
263 typedef PassManager<Function> FunctionPassManager;
267 /// \brief A CRTP base used to implement analysis managers.
269 /// This class template serves as the boiler plate of an analysis manager. Any
270 /// analysis manager can be implemented on top of this base class. Any
271 /// implementation will be required to provide specific hooks:
274 /// - getCachedResultImpl
277 /// The details of the call pattern are within.
279 /// Note that there is also a generic analysis manager template which implements
280 /// the above required functions along with common datastructures used for
281 /// managing analyses. This base class is factored so that if you need to
282 /// customize the handling of a specific IR unit, you can do so without
283 /// replicating *all* of the boilerplate.
284 template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
285 DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
286 const DerivedT *derived_this() const {
287 return static_cast<const DerivedT *>(this);
290 AnalysisManagerBase(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
291 AnalysisManagerBase &
292 operator=(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
295 typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
296 typedef detail::AnalysisPassConcept<IRUnitT> PassConceptT;
298 // FIXME: Provide template aliases for the models when we're using C++11 in
299 // a mode supporting them.
301 // We have to explicitly define all the special member functions because MSVC
302 // refuses to generate them.
303 AnalysisManagerBase() {}
304 AnalysisManagerBase(AnalysisManagerBase &&Arg)
305 : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
306 AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
307 AnalysisPasses = std::move(RHS.AnalysisPasses);
312 /// \brief Get the result of an analysis pass for this module.
314 /// If there is not a valid cached result in the manager already, this will
315 /// re-run the analysis to produce a valid result.
316 template <typename PassT> typename PassT::Result &getResult(IRUnitT &IR) {
317 assert(AnalysisPasses.count(PassT::ID()) &&
318 "This analysis pass was not registered prior to being queried");
320 ResultConceptT &ResultConcept =
321 derived_this()->getResultImpl(PassT::ID(), IR);
322 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
324 return static_cast<ResultModelT &>(ResultConcept).Result;
327 /// \brief Get the cached result of an analysis pass for this module.
329 /// This method never runs the analysis.
331 /// \returns null if there is no cached result.
332 template <typename PassT>
333 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
334 assert(AnalysisPasses.count(PassT::ID()) &&
335 "This analysis pass was not registered prior to being queried");
337 ResultConceptT *ResultConcept =
338 derived_this()->getCachedResultImpl(PassT::ID(), IR);
342 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
344 return &static_cast<ResultModelT *>(ResultConcept)->Result;
347 /// \brief Register an analysis pass with the manager.
349 /// This provides an initialized and set-up analysis pass to the analysis
350 /// manager. Whomever is setting up analysis passes must use this to populate
351 /// the manager with all of the analysis passes available.
352 template <typename PassT> void registerPass(PassT Pass) {
353 assert(!AnalysisPasses.count(PassT::ID()) &&
354 "Registered the same analysis pass twice!");
355 typedef detail::AnalysisPassModel<IRUnitT, PassT> PassModelT;
356 AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
359 /// \brief Invalidate a specific analysis pass for an IR module.
361 /// Note that the analysis result can disregard invalidation.
362 template <typename PassT> void invalidate(IRUnitT &IR) {
363 assert(AnalysisPasses.count(PassT::ID()) &&
364 "This analysis pass was not registered prior to being invalidated");
365 derived_this()->invalidateImpl(PassT::ID(), IR);
368 /// \brief Invalidate analyses cached for an IR unit.
370 /// Walk through all of the analyses pertaining to this unit of IR and
371 /// invalidate them unless they are preserved by the PreservedAnalyses set.
372 /// We accept the PreservedAnalyses set by value and update it with each
373 /// analyis pass which has been successfully invalidated and thus can be
374 /// preserved going forward. The updated set is returned.
375 PreservedAnalyses invalidate(IRUnitT &IR, PreservedAnalyses PA) {
376 return derived_this()->invalidateImpl(IR, std::move(PA));
380 /// \brief Lookup a registered analysis pass.
381 PassConceptT &lookupPass(void *PassID) {
382 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
383 assert(PI != AnalysisPasses.end() &&
384 "Analysis passes must be registered prior to being queried!");
388 /// \brief Lookup a registered analysis pass.
389 const PassConceptT &lookupPass(void *PassID) const {
390 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
391 assert(PI != AnalysisPasses.end() &&
392 "Analysis passes must be registered prior to being queried!");
397 /// \brief Map type from module analysis pass ID to pass concept pointer.
398 typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
400 /// \brief Collection of module analysis passes, indexed by ID.
401 AnalysisPassMapT AnalysisPasses;
404 } // End namespace detail
406 /// \brief A generic analysis pass manager with lazy running and caching of
409 /// This analysis manager can be used for any IR unit where the address of the
410 /// IR unit sufficies as its identity. It manages the cache for a unit of IR via
411 /// the address of each unit of IR cached.
412 template <typename IRUnitT>
413 class AnalysisManager
414 : public detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> {
415 friend class detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT>;
416 typedef detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> BaseT;
417 typedef typename BaseT::ResultConceptT ResultConceptT;
418 typedef typename BaseT::PassConceptT PassConceptT;
421 // Most public APIs are inherited from the CRTP base class.
423 // We have to explicitly define all the special member functions because MSVC
424 // refuses to generate them.
426 AnalysisManager(AnalysisManager &&Arg)
427 : BaseT(std::move(static_cast<BaseT &>(Arg))),
428 AnalysisResults(std::move(Arg.AnalysisResults)) {}
429 AnalysisManager &operator=(AnalysisManager &&RHS) {
430 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
431 AnalysisResults = std::move(RHS.AnalysisResults);
435 /// \brief Returns true if the analysis manager has an empty results cache.
437 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
438 "The storage and index of analysis results disagree on how many "
440 return AnalysisResults.empty();
443 /// \brief Clear the analysis result cache.
445 /// This routine allows cleaning up when the set of IR units itself has
446 /// potentially changed, and thus we can't even look up a a result and
447 /// invalidate it directly. Notably, this does *not* call invalidate functions
448 /// as there is nothing to be done for them.
450 AnalysisResults.clear();
451 AnalysisResultLists.clear();
455 AnalysisManager(const AnalysisManager &) LLVM_DELETED_FUNCTION;
456 AnalysisManager &operator=(const AnalysisManager &) LLVM_DELETED_FUNCTION;
458 /// \brief Get an analysis result, running the pass if necessary.
459 ResultConceptT &getResultImpl(void *PassID, IRUnitT &IR) {
460 typename AnalysisResultMapT::iterator RI;
462 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
463 std::make_pair(PassID, &IR), typename AnalysisResultListT::iterator()));
465 // If we don't have a cached result for this function, look up the pass and
466 // run it to produce a result, which we then add to the cache.
468 auto &P = this->lookupPass(PassID);
470 dbgs() << "Running analysis: " << P.name() << "\n";
471 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
472 ResultList.emplace_back(PassID, P.run(IR, this));
473 RI->second = std::prev(ResultList.end());
476 return *RI->second->second;
479 /// \brief Get a cached analysis result or return null.
480 ResultConceptT *getCachedResultImpl(void *PassID, IRUnitT &IR) const {
481 typename AnalysisResultMapT::const_iterator RI =
482 AnalysisResults.find(std::make_pair(PassID, &IR));
483 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
486 /// \brief Invalidate a function pass result.
487 void invalidateImpl(void *PassID, IRUnitT &IR) {
488 typename AnalysisResultMapT::iterator RI =
489 AnalysisResults.find(std::make_pair(PassID, &IR));
490 if (RI == AnalysisResults.end())
494 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
496 AnalysisResultLists[&IR].erase(RI->second);
497 AnalysisResults.erase(RI);
500 /// \brief Invalidate the results for a function..
501 PreservedAnalyses invalidateImpl(IRUnitT &IR, PreservedAnalyses PA) {
502 // Short circuit for a common case of all analyses being preserved.
503 if (PA.areAllPreserved())
504 return std::move(PA);
507 dbgs() << "Invalidating all non-preserved analyses for: "
508 << IR.getName() << "\n";
510 // Clear all the invalidated results associated specifically with this
512 SmallVector<void *, 8> InvalidatedPassIDs;
513 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
514 for (typename AnalysisResultListT::iterator I = ResultsList.begin(),
515 E = ResultsList.end();
517 void *PassID = I->first;
519 // Pass the invalidation down to the pass itself to see if it thinks it is
520 // necessary. The analysis pass can return false if no action on the part
521 // of the analysis manager is required for this invalidation event.
522 if (I->second->invalidate(IR, PA)) {
524 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
527 InvalidatedPassIDs.push_back(I->first);
528 I = ResultsList.erase(I);
533 // After handling each pass, we mark it as preserved. Once we've
534 // invalidated any stale results, the rest of the system is allowed to
535 // start preserving this analysis again.
538 while (!InvalidatedPassIDs.empty())
539 AnalysisResults.erase(
540 std::make_pair(InvalidatedPassIDs.pop_back_val(), &IR));
541 if (ResultsList.empty())
542 AnalysisResultLists.erase(&IR);
544 return std::move(PA);
547 /// \brief List of function analysis pass IDs and associated concept pointers.
549 /// Requires iterators to be valid across appending new entries and arbitrary
550 /// erases. Provides both the pass ID and concept pointer such that it is
551 /// half of a bijection and provides storage for the actual result concept.
552 typedef std::list<std::pair<
553 void *, std::unique_ptr<detail::AnalysisResultConcept<IRUnitT>>>>
556 /// \brief Map type from function pointer to our custom list type.
557 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
559 /// \brief Map from function to a list of function analysis results.
561 /// Provides linear time removal of all analysis results for a function and
562 /// the ultimate storage for a particular cached analysis result.
563 AnalysisResultListMapT AnalysisResultLists;
565 /// \brief Map type from a pair of analysis ID and function pointer to an
566 /// iterator into a particular result list.
567 typedef DenseMap<std::pair<void *, IRUnitT *>,
568 typename AnalysisResultListT::iterator> AnalysisResultMapT;
570 /// \brief Map from an analysis ID and function to a particular cached
572 AnalysisResultMapT AnalysisResults;
575 /// \brief A module analysis which acts as a proxy for a function analysis
578 /// This primarily proxies invalidation information from the module analysis
579 /// manager and module pass manager to a function analysis manager. You should
580 /// never use a function analysis manager from within (transitively) a module
581 /// pass manager unless your parent module pass has received a proxy result
583 class FunctionAnalysisManagerModuleProxy {
587 static void *ID() { return (void *)&PassID; }
589 static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
591 explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
593 // We have to explicitly define all the special member functions because MSVC
594 // refuses to generate them.
595 FunctionAnalysisManagerModuleProxy(
596 const FunctionAnalysisManagerModuleProxy &Arg)
598 FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
599 : FAM(std::move(Arg.FAM)) {}
600 FunctionAnalysisManagerModuleProxy &
601 operator=(FunctionAnalysisManagerModuleProxy RHS) {
602 std::swap(FAM, RHS.FAM);
606 /// \brief Run the analysis pass and create our proxy result object.
608 /// This doesn't do any interesting work, it is primarily used to insert our
609 /// proxy result object into the module analysis cache so that we can proxy
610 /// invalidation to the function analysis manager.
612 /// In debug builds, it will also assert that the analysis manager is empty
613 /// as no queries should arrive at the function analysis manager prior to
614 /// this analysis being requested.
615 Result run(Module &M);
620 FunctionAnalysisManager *FAM;
623 /// \brief The result proxy object for the
624 /// \c FunctionAnalysisManagerModuleProxy.
626 /// See its documentation for more information.
627 class FunctionAnalysisManagerModuleProxy::Result {
629 explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
630 // We have to explicitly define all the special member functions because MSVC
631 // refuses to generate them.
632 Result(const Result &Arg) : FAM(Arg.FAM) {}
633 Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
634 Result &operator=(Result RHS) {
635 std::swap(FAM, RHS.FAM);
640 /// \brief Accessor for the \c FunctionAnalysisManager.
641 FunctionAnalysisManager &getManager() { return *FAM; }
643 /// \brief Handler for invalidation of the module.
645 /// If this analysis itself is preserved, then we assume that the set of \c
646 /// Function objects in the \c Module hasn't changed and thus we don't need
647 /// to invalidate *all* cached data associated with a \c Function* in the \c
648 /// FunctionAnalysisManager.
650 /// Regardless of whether this analysis is marked as preserved, all of the
651 /// analyses in the \c FunctionAnalysisManager are potentially invalidated
652 /// based on the set of preserved analyses.
653 bool invalidate(Module &M, const PreservedAnalyses &PA);
656 FunctionAnalysisManager *FAM;
659 /// \brief A function analysis which acts as a proxy for a module analysis
662 /// This primarily provides an accessor to a parent module analysis manager to
663 /// function passes. Only the const interface of the module analysis manager is
664 /// provided to indicate that once inside of a function analysis pass you
665 /// cannot request a module analysis to actually run. Instead, the user must
666 /// rely on the \c getCachedResult API.
668 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
669 /// the recursive return path of each layer of the pass manager and the
670 /// returned PreservedAnalysis set.
671 class ModuleAnalysisManagerFunctionProxy {
673 /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
676 explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
677 // We have to explicitly define all the special member functions because
678 // MSVC refuses to generate them.
679 Result(const Result &Arg) : MAM(Arg.MAM) {}
680 Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
681 Result &operator=(Result RHS) {
682 std::swap(MAM, RHS.MAM);
686 const ModuleAnalysisManager &getManager() const { return *MAM; }
688 /// \brief Handle invalidation by ignoring it, this pass is immutable.
689 bool invalidate(Function &) { return false; }
692 const ModuleAnalysisManager *MAM;
695 static void *ID() { return (void *)&PassID; }
697 static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
699 ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
701 // We have to explicitly define all the special member functions because MSVC
702 // refuses to generate them.
703 ModuleAnalysisManagerFunctionProxy(
704 const ModuleAnalysisManagerFunctionProxy &Arg)
706 ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
707 : MAM(std::move(Arg.MAM)) {}
708 ModuleAnalysisManagerFunctionProxy &
709 operator=(ModuleAnalysisManagerFunctionProxy RHS) {
710 std::swap(MAM, RHS.MAM);
714 /// \brief Run the analysis pass and create our proxy result object.
715 /// Nothing to see here, it just forwards the \c MAM reference into the
717 Result run(Function &) { return Result(*MAM); }
722 const ModuleAnalysisManager *MAM;
725 /// \brief Trivial adaptor that maps from a module to its functions.
727 /// Designed to allow composition of a FunctionPass(Manager) and
728 /// a ModulePassManager. Note that if this pass is constructed with a pointer
729 /// to a \c ModuleAnalysisManager it will run the
730 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
731 /// pass over the module to enable a \c FunctionAnalysisManager to be used
732 /// within this run safely.
734 /// Function passes run within this adaptor can rely on having exclusive access
735 /// to the function they are run over. They should not read or modify any other
736 /// functions! Other threads or systems may be manipulating other functions in
737 /// the module, and so their state should never be relied on.
738 /// FIXME: Make the above true for all of LLVM's actual passes, some still
739 /// violate this principle.
741 /// Function passes can also read the module containing the function, but they
742 /// should not modify that module outside of the use lists of various globals.
743 /// For example, a function pass is not permitted to add functions to the
745 /// FIXME: Make the above true for all of LLVM's actual passes, some still
746 /// violate this principle.
747 template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
749 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
750 : Pass(std::move(Pass)) {}
751 // We have to explicitly define all the special member functions because MSVC
752 // refuses to generate them.
753 ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
755 ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
756 : Pass(std::move(Arg.Pass)) {}
757 friend void swap(ModuleToFunctionPassAdaptor &LHS,
758 ModuleToFunctionPassAdaptor &RHS) {
760 swap(LHS.Pass, RHS.Pass);
762 ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
767 /// \brief Runs the function pass across every function in the module.
768 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
769 FunctionAnalysisManager *FAM = nullptr;
771 // Setup the function analysis manager from its proxy.
772 FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
774 PreservedAnalyses PA = PreservedAnalyses::all();
775 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
776 PreservedAnalyses PassPA = Pass.run(*I, FAM);
778 // We know that the function pass couldn't have invalidated any other
779 // function's analyses (that's the contract of a function pass), so
780 // directly handle the function analysis manager's invalidation here and
781 // update our preserved set to reflect that these have already been
784 PassPA = FAM->invalidate(*I, std::move(PassPA));
786 // Then intersect the preserved set so that invalidation of module
787 // analyses will eventually occur when the module pass completes.
788 PA.intersect(std::move(PassPA));
791 // By definition we preserve the proxy. This precludes *any* invalidation
792 // of function analyses by the proxy, but that's OK because we've taken
793 // care to invalidate analyses in the function analysis manager
794 // incrementally above.
795 PA.preserve<FunctionAnalysisManagerModuleProxy>();
799 static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
805 /// \brief A function to deduce a function pass type and wrap it in the
806 /// templated adaptor.
807 template <typename FunctionPassT>
808 ModuleToFunctionPassAdaptor<FunctionPassT>
809 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
810 return std::move(ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)));
813 /// \brief A template utility pass to force an analysis result to be available.
815 /// This is a no-op pass which simply forces a specific analysis pass's result
816 /// to be available when it is run.
817 template <typename AnalysisT> struct RequireAnalysisPass {
818 /// \brief Run this pass over some unit of IR.
820 /// This pass can be run over any unit of IR and use any analysis manager
821 /// provided they satisfy the basic API requirements. When this pass is
822 /// created, these methods can be instantiated to satisfy whatever the
823 /// context requires.
824 template <typename IRUnitT>
825 PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
827 (void)AM->template getResult<AnalysisT>(Arg);
829 return PreservedAnalyses::all();
832 static StringRef name() { return "RequireAnalysisPass"; }
835 /// \brief A template utility pass to force an analysis result to be
838 /// This is a no-op pass which simply forces a specific analysis result to be
839 /// invalidated when it is run.
840 template <typename AnalysisT> struct InvalidateAnalysisPass {
841 /// \brief Run this pass over some unit of IR.
843 /// This pass can be run over any unit of IR and use any analysis manager
844 /// provided they satisfy the basic API requirements. When this pass is
845 /// created, these methods can be instantiated to satisfy whatever the
846 /// context requires.
847 template <typename IRUnitT>
848 PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
850 // We have to directly invalidate the analysis result as we can't
851 // enumerate all other analyses and use the preserved set to control it.
852 (void)AM->template invalidate<AnalysisT>(Arg);
854 return PreservedAnalyses::all();
857 static StringRef name() { return "InvalidateAnalysisPass"; }
860 /// \brief A utility pass that does nothing but preserves no analyses.
862 /// As a consequence fo not preserving any analyses, this pass will force all
863 /// analysis passes to be re-run to produce fresh results if any are needed.
864 struct InvalidateAllAnalysesPass {
865 /// \brief Run this pass over some unit of IR.
866 template <typename IRUnitT> PreservedAnalyses run(IRUnitT &Arg) {
867 return PreservedAnalyses::none();
870 static StringRef name() { return "InvalidateAllAnalysesPass"; }