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.
173 template <typename IRUnitT> class AnalysisManager;
175 /// \brief Manages a sequence of passes over units of IR.
177 /// A pass manager contains a sequence of passes to run over units of IR. It is
178 /// itself a valid pass over that unit of IR, and when over some given IR will
179 /// run each pass in sequence. This is the primary and most basic building
180 /// block of a pass pipeline.
182 /// If it is run with an \c AnalysisManager<IRUnitT> argument, it will propagate
183 /// that analysis manager to each pass it runs, as well as calling the analysis
184 /// manager's invalidation routine with the PreservedAnalyses of each pass it
186 template <typename IRUnitT> class PassManager {
188 // We have to explicitly define all the special member functions because MSVC
189 // refuses to generate them.
191 PassManager(PassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
192 PassManager &operator=(PassManager &&RHS) {
193 Passes = std::move(RHS.Passes);
197 /// \brief Run all of the passes in this manager over the IR.
198 PreservedAnalyses run(IRUnitT &IR, AnalysisManager<IRUnitT> *AM = nullptr) {
199 PreservedAnalyses PA = PreservedAnalyses::all();
202 dbgs() << "Starting pass manager run.\n";
204 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
206 dbgs() << "Running pass: " << Passes[Idx]->name() << "\n";
208 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM);
210 // If we have an active analysis manager at this level we want to ensure
211 // we update it as each pass runs and potentially invalidates analyses.
212 // We also update the preserved set of analyses based on what analyses we
213 // have already handled the invalidation for here and don't need to
214 // invalidate when finished.
216 PassPA = AM->invalidate(IR, std::move(PassPA));
218 // Finally, we intersect the final preserved analyses to compute the
219 // aggregate preserved set for this pass manager.
220 PA.intersect(std::move(PassPA));
222 // FIXME: Historically, the pass managers all called the LLVM context's
223 // yield function here. We don't have a generic way to acquire the
224 // context and it isn't yet clear what the right pattern is for yielding
225 // in the new pass manager so it is currently omitted.
226 //IR.getContext().yield();
230 dbgs() << "Finished pass manager run.\n";
235 template <typename PassT> void addPass(PassT Pass) {
236 typedef detail::PassModel<IRUnitT, PassT> PassModelT;
237 Passes.emplace_back(new PassModelT(std::move(Pass)));
240 static StringRef name() { return "PassManager"; }
243 typedef detail::PassConcept<IRUnitT> PassConceptT;
245 PassManager(const PassManager &) LLVM_DELETED_FUNCTION;
246 PassManager &operator=(const PassManager &) LLVM_DELETED_FUNCTION;
248 std::vector<std::unique_ptr<PassConceptT>> Passes;
251 /// \brief Convenience typedef for a pass manager over modules.
252 typedef PassManager<Module> ModulePassManager;
254 /// \brief Convenience typedef for a pass manager over functions.
255 typedef PassManager<Function> FunctionPassManager;
259 /// \brief A CRTP base used to implement analysis managers.
261 /// This class template serves as the boiler plate of an analysis manager. Any
262 /// analysis manager can be implemented on top of this base class. Any
263 /// implementation will be required to provide specific hooks:
266 /// - getCachedResultImpl
269 /// The details of the call pattern are within.
271 /// Note that there is also a generic analysis manager template which implements
272 /// the above required functions along with common datastructures used for
273 /// managing analyses. This base class is factored so that if you need to
274 /// customize the handling of a specific IR unit, you can do so without
275 /// replicating *all* of the boilerplate.
276 template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
277 DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
278 const DerivedT *derived_this() const {
279 return static_cast<const DerivedT *>(this);
282 AnalysisManagerBase(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
283 AnalysisManagerBase &
284 operator=(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
287 typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
288 typedef detail::AnalysisPassConcept<IRUnitT> PassConceptT;
290 // FIXME: Provide template aliases for the models when we're using C++11 in
291 // a mode supporting them.
293 // We have to explicitly define all the special member functions because MSVC
294 // refuses to generate them.
295 AnalysisManagerBase() {}
296 AnalysisManagerBase(AnalysisManagerBase &&Arg)
297 : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
298 AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
299 AnalysisPasses = std::move(RHS.AnalysisPasses);
304 /// \brief Get the result of an analysis pass for this module.
306 /// If there is not a valid cached result in the manager already, this will
307 /// re-run the analysis to produce a valid result.
308 template <typename PassT> typename PassT::Result &getResult(IRUnitT &IR) {
309 assert(AnalysisPasses.count(PassT::ID()) &&
310 "This analysis pass was not registered prior to being queried");
312 ResultConceptT &ResultConcept =
313 derived_this()->getResultImpl(PassT::ID(), IR);
314 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
316 return static_cast<ResultModelT &>(ResultConcept).Result;
319 /// \brief Get the cached result of an analysis pass for this module.
321 /// This method never runs the analysis.
323 /// \returns null if there is no cached result.
324 template <typename PassT>
325 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
326 assert(AnalysisPasses.count(PassT::ID()) &&
327 "This analysis pass was not registered prior to being queried");
329 ResultConceptT *ResultConcept =
330 derived_this()->getCachedResultImpl(PassT::ID(), IR);
334 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
336 return &static_cast<ResultModelT *>(ResultConcept)->Result;
339 /// \brief Register an analysis pass with the manager.
341 /// This provides an initialized and set-up analysis pass to the analysis
342 /// manager. Whomever is setting up analysis passes must use this to populate
343 /// the manager with all of the analysis passes available.
344 template <typename PassT> void registerPass(PassT Pass) {
345 assert(!AnalysisPasses.count(PassT::ID()) &&
346 "Registered the same analysis pass twice!");
347 typedef detail::AnalysisPassModel<IRUnitT, PassT> PassModelT;
348 AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
351 /// \brief Invalidate a specific analysis pass for an IR module.
353 /// Note that the analysis result can disregard invalidation.
354 template <typename PassT> void invalidate(IRUnitT &IR) {
355 assert(AnalysisPasses.count(PassT::ID()) &&
356 "This analysis pass was not registered prior to being invalidated");
357 derived_this()->invalidateImpl(PassT::ID(), IR);
360 /// \brief Invalidate analyses cached for an IR unit.
362 /// Walk through all of the analyses pertaining to this unit of IR and
363 /// invalidate them unless they are preserved by the PreservedAnalyses set.
364 /// We accept the PreservedAnalyses set by value and update it with each
365 /// analyis pass which has been successfully invalidated and thus can be
366 /// preserved going forward. The updated set is returned.
367 PreservedAnalyses invalidate(IRUnitT &IR, PreservedAnalyses PA) {
368 return derived_this()->invalidateImpl(IR, std::move(PA));
372 /// \brief Lookup a registered analysis pass.
373 PassConceptT &lookupPass(void *PassID) {
374 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
375 assert(PI != AnalysisPasses.end() &&
376 "Analysis passes must be registered prior to being queried!");
380 /// \brief Lookup a registered analysis pass.
381 const PassConceptT &lookupPass(void *PassID) const {
382 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
383 assert(PI != AnalysisPasses.end() &&
384 "Analysis passes must be registered prior to being queried!");
389 /// \brief Map type from module analysis pass ID to pass concept pointer.
390 typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
392 /// \brief Collection of module analysis passes, indexed by ID.
393 AnalysisPassMapT AnalysisPasses;
396 } // End namespace detail
398 /// \brief A generic analysis pass manager with lazy running and caching of
401 /// This analysis manager can be used for any IR unit where the address of the
402 /// IR unit sufficies as its identity. It manages the cache for a unit of IR via
403 /// the address of each unit of IR cached.
404 template <typename IRUnitT>
405 class AnalysisManager
406 : public detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> {
407 friend class detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT>;
408 typedef detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> BaseT;
409 typedef typename BaseT::ResultConceptT ResultConceptT;
410 typedef typename BaseT::PassConceptT PassConceptT;
413 // Most public APIs are inherited from the CRTP base class.
415 // We have to explicitly define all the special member functions because MSVC
416 // refuses to generate them.
418 AnalysisManager(AnalysisManager &&Arg)
419 : BaseT(std::move(static_cast<BaseT &>(Arg))),
420 AnalysisResults(std::move(Arg.AnalysisResults)) {}
421 AnalysisManager &operator=(AnalysisManager &&RHS) {
422 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
423 AnalysisResults = std::move(RHS.AnalysisResults);
427 /// \brief Returns true if the analysis manager has an empty results cache.
429 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
430 "The storage and index of analysis results disagree on how many "
432 return AnalysisResults.empty();
435 /// \brief Clear the analysis result cache.
437 /// This routine allows cleaning up when the set of IR units itself has
438 /// potentially changed, and thus we can't even look up a a result and
439 /// invalidate it directly. Notably, this does *not* call invalidate functions
440 /// as there is nothing to be done for them.
442 AnalysisResults.clear();
443 AnalysisResultLists.clear();
447 AnalysisManager(const AnalysisManager &) LLVM_DELETED_FUNCTION;
448 AnalysisManager &operator=(const AnalysisManager &) LLVM_DELETED_FUNCTION;
450 /// \brief Get an analysis result, running the pass if necessary.
451 ResultConceptT &getResultImpl(void *PassID, IRUnitT &IR) {
452 typename AnalysisResultMapT::iterator RI;
454 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
455 std::make_pair(PassID, &IR), typename AnalysisResultListT::iterator()));
457 // If we don't have a cached result for this function, look up the pass and
458 // run it to produce a result, which we then add to the cache.
460 auto &P = this->lookupPass(PassID);
462 dbgs() << "Running analysis: " << P.name() << "\n";
463 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
464 ResultList.emplace_back(PassID, P.run(IR, this));
465 RI->second = std::prev(ResultList.end());
468 return *RI->second->second;
471 /// \brief Get a cached analysis result or return null.
472 ResultConceptT *getCachedResultImpl(void *PassID, IRUnitT &IR) const {
473 typename AnalysisResultMapT::const_iterator RI =
474 AnalysisResults.find(std::make_pair(PassID, &IR));
475 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
478 /// \brief Invalidate a function pass result.
479 void invalidateImpl(void *PassID, IRUnitT &IR) {
480 typename AnalysisResultMapT::iterator RI =
481 AnalysisResults.find(std::make_pair(PassID, &IR));
482 if (RI == AnalysisResults.end())
486 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
488 AnalysisResultLists[&IR].erase(RI->second);
489 AnalysisResults.erase(RI);
492 /// \brief Invalidate the results for a function..
493 PreservedAnalyses invalidateImpl(IRUnitT &IR, PreservedAnalyses PA) {
494 // Short circuit for a common case of all analyses being preserved.
495 if (PA.areAllPreserved())
496 return std::move(PA);
499 dbgs() << "Invalidating all non-preserved analyses for: "
500 << IR.getName() << "\n";
502 // Clear all the invalidated results associated specifically with this
504 SmallVector<void *, 8> InvalidatedPassIDs;
505 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
506 for (typename AnalysisResultListT::iterator I = ResultsList.begin(),
507 E = ResultsList.end();
509 void *PassID = I->first;
511 // Pass the invalidation down to the pass itself to see if it thinks it is
512 // necessary. The analysis pass can return false if no action on the part
513 // of the analysis manager is required for this invalidation event.
514 if (I->second->invalidate(IR, PA)) {
516 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
519 InvalidatedPassIDs.push_back(I->first);
520 I = ResultsList.erase(I);
525 // After handling each pass, we mark it as preserved. Once we've
526 // invalidated any stale results, the rest of the system is allowed to
527 // start preserving this analysis again.
530 while (!InvalidatedPassIDs.empty())
531 AnalysisResults.erase(
532 std::make_pair(InvalidatedPassIDs.pop_back_val(), &IR));
533 if (ResultsList.empty())
534 AnalysisResultLists.erase(&IR);
536 return std::move(PA);
539 /// \brief List of function analysis pass IDs and associated concept pointers.
541 /// Requires iterators to be valid across appending new entries and arbitrary
542 /// erases. Provides both the pass ID and concept pointer such that it is
543 /// half of a bijection and provides storage for the actual result concept.
544 typedef std::list<std::pair<
545 void *, std::unique_ptr<detail::AnalysisResultConcept<IRUnitT>>>>
548 /// \brief Map type from function pointer to our custom list type.
549 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
551 /// \brief Map from function to a list of function analysis results.
553 /// Provides linear time removal of all analysis results for a function and
554 /// the ultimate storage for a particular cached analysis result.
555 AnalysisResultListMapT AnalysisResultLists;
557 /// \brief Map type from a pair of analysis ID and function pointer to an
558 /// iterator into a particular result list.
559 typedef DenseMap<std::pair<void *, IRUnitT *>,
560 typename AnalysisResultListT::iterator> AnalysisResultMapT;
562 /// \brief Map from an analysis ID and function to a particular cached
564 AnalysisResultMapT AnalysisResults;
567 /// \brief Convenience typedef for the Module analysis manager.
568 typedef AnalysisManager<Module> ModuleAnalysisManager;
570 /// \brief Convenience typedef for the Function analysis manager.
571 typedef AnalysisManager<Function> FunctionAnalysisManager;
573 /// \brief A module analysis which acts as a proxy for a function analysis
576 /// This primarily proxies invalidation information from the module analysis
577 /// manager and module pass manager to a function analysis manager. You should
578 /// never use a function analysis manager from within (transitively) a module
579 /// pass manager unless your parent module pass has received a proxy result
581 class FunctionAnalysisManagerModuleProxy {
585 static void *ID() { return (void *)&PassID; }
587 static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
589 explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
591 // We have to explicitly define all the special member functions because MSVC
592 // refuses to generate them.
593 FunctionAnalysisManagerModuleProxy(
594 const FunctionAnalysisManagerModuleProxy &Arg)
596 FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
597 : FAM(std::move(Arg.FAM)) {}
598 FunctionAnalysisManagerModuleProxy &
599 operator=(FunctionAnalysisManagerModuleProxy RHS) {
600 std::swap(FAM, RHS.FAM);
604 /// \brief Run the analysis pass and create our proxy result object.
606 /// This doesn't do any interesting work, it is primarily used to insert our
607 /// proxy result object into the module analysis cache so that we can proxy
608 /// invalidation to the function analysis manager.
610 /// In debug builds, it will also assert that the analysis manager is empty
611 /// as no queries should arrive at the function analysis manager prior to
612 /// this analysis being requested.
613 Result run(Module &M);
618 FunctionAnalysisManager *FAM;
621 /// \brief The result proxy object for the
622 /// \c FunctionAnalysisManagerModuleProxy.
624 /// See its documentation for more information.
625 class FunctionAnalysisManagerModuleProxy::Result {
627 explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
628 // We have to explicitly define all the special member functions because MSVC
629 // refuses to generate them.
630 Result(const Result &Arg) : FAM(Arg.FAM) {}
631 Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
632 Result &operator=(Result RHS) {
633 std::swap(FAM, RHS.FAM);
638 /// \brief Accessor for the \c FunctionAnalysisManager.
639 FunctionAnalysisManager &getManager() { return *FAM; }
641 /// \brief Handler for invalidation of the module.
643 /// If this analysis itself is preserved, then we assume that the set of \c
644 /// Function objects in the \c Module hasn't changed and thus we don't need
645 /// to invalidate *all* cached data associated with a \c Function* in the \c
646 /// FunctionAnalysisManager.
648 /// Regardless of whether this analysis is marked as preserved, all of the
649 /// analyses in the \c FunctionAnalysisManager are potentially invalidated
650 /// based on the set of preserved analyses.
651 bool invalidate(Module &M, const PreservedAnalyses &PA);
654 FunctionAnalysisManager *FAM;
657 /// \brief A function analysis which acts as a proxy for a module analysis
660 /// This primarily provides an accessor to a parent module analysis manager to
661 /// function passes. Only the const interface of the module analysis manager is
662 /// provided to indicate that once inside of a function analysis pass you
663 /// cannot request a module analysis to actually run. Instead, the user must
664 /// rely on the \c getCachedResult API.
666 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
667 /// the recursive return path of each layer of the pass manager and the
668 /// returned PreservedAnalysis set.
669 class ModuleAnalysisManagerFunctionProxy {
671 /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
674 explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
675 // We have to explicitly define all the special member functions because
676 // MSVC refuses to generate them.
677 Result(const Result &Arg) : MAM(Arg.MAM) {}
678 Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
679 Result &operator=(Result RHS) {
680 std::swap(MAM, RHS.MAM);
684 const ModuleAnalysisManager &getManager() const { return *MAM; }
686 /// \brief Handle invalidation by ignoring it, this pass is immutable.
687 bool invalidate(Function &) { return false; }
690 const ModuleAnalysisManager *MAM;
693 static void *ID() { return (void *)&PassID; }
695 static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
697 ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
699 // We have to explicitly define all the special member functions because MSVC
700 // refuses to generate them.
701 ModuleAnalysisManagerFunctionProxy(
702 const ModuleAnalysisManagerFunctionProxy &Arg)
704 ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
705 : MAM(std::move(Arg.MAM)) {}
706 ModuleAnalysisManagerFunctionProxy &
707 operator=(ModuleAnalysisManagerFunctionProxy RHS) {
708 std::swap(MAM, RHS.MAM);
712 /// \brief Run the analysis pass and create our proxy result object.
713 /// Nothing to see here, it just forwards the \c MAM reference into the
715 Result run(Function &) { return Result(*MAM); }
720 const ModuleAnalysisManager *MAM;
723 /// \brief Trivial adaptor that maps from a module to its functions.
725 /// Designed to allow composition of a FunctionPass(Manager) and
726 /// a ModulePassManager. Note that if this pass is constructed with a pointer
727 /// to a \c ModuleAnalysisManager it will run the
728 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
729 /// pass over the module to enable a \c FunctionAnalysisManager to be used
730 /// within this run safely.
732 /// Function passes run within this adaptor can rely on having exclusive access
733 /// to the function they are run over. They should not read or modify any other
734 /// functions! Other threads or systems may be manipulating other functions in
735 /// the module, and so their state should never be relied on.
736 /// FIXME: Make the above true for all of LLVM's actual passes, some still
737 /// violate this principle.
739 /// Function passes can also read the module containing the function, but they
740 /// should not modify that module outside of the use lists of various globals.
741 /// For example, a function pass is not permitted to add functions to the
743 /// FIXME: Make the above true for all of LLVM's actual passes, some still
744 /// violate this principle.
745 template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
747 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
748 : Pass(std::move(Pass)) {}
749 // We have to explicitly define all the special member functions because MSVC
750 // refuses to generate them.
751 ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
753 ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
754 : Pass(std::move(Arg.Pass)) {}
755 friend void swap(ModuleToFunctionPassAdaptor &LHS,
756 ModuleToFunctionPassAdaptor &RHS) {
758 swap(LHS.Pass, RHS.Pass);
760 ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
765 /// \brief Runs the function pass across every function in the module.
766 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
767 FunctionAnalysisManager *FAM = nullptr;
769 // Setup the function analysis manager from its proxy.
770 FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
772 PreservedAnalyses PA = PreservedAnalyses::all();
773 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
774 PreservedAnalyses PassPA = Pass.run(*I, FAM);
776 // We know that the function pass couldn't have invalidated any other
777 // function's analyses (that's the contract of a function pass), so
778 // directly handle the function analysis manager's invalidation here and
779 // update our preserved set to reflect that these have already been
782 PassPA = FAM->invalidate(*I, std::move(PassPA));
784 // Then intersect the preserved set so that invalidation of module
785 // analyses will eventually occur when the module pass completes.
786 PA.intersect(std::move(PassPA));
789 // By definition we preserve the proxy. This precludes *any* invalidation
790 // of function analyses by the proxy, but that's OK because we've taken
791 // care to invalidate analyses in the function analysis manager
792 // incrementally above.
793 PA.preserve<FunctionAnalysisManagerModuleProxy>();
797 static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
803 /// \brief A function to deduce a function pass type and wrap it in the
804 /// templated adaptor.
805 template <typename FunctionPassT>
806 ModuleToFunctionPassAdaptor<FunctionPassT>
807 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
808 return std::move(ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)));
811 /// \brief A template utility pass to force an analysis result to be available.
813 /// This is a no-op pass which simply forces a specific analysis pass's result
814 /// to be available when it is run.
815 template <typename AnalysisT> struct RequireAnalysisPass {
816 /// \brief Run this pass over some unit of IR.
818 /// This pass can be run over any unit of IR and use any analysis manager
819 /// provided they satisfy the basic API requirements. When this pass is
820 /// created, these methods can be instantiated to satisfy whatever the
821 /// context requires.
822 template <typename IRUnitT>
823 PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
825 (void)AM->template getResult<AnalysisT>(Arg);
827 return PreservedAnalyses::all();
830 static StringRef name() { return "RequireAnalysisPass"; }
833 /// \brief A template utility pass to force an analysis result to be
836 /// This is a no-op pass which simply forces a specific analysis result to be
837 /// invalidated when it is run.
838 template <typename AnalysisT> struct InvalidateAnalysisPass {
839 /// \brief Run this pass over some unit of IR.
841 /// This pass can be run over any unit of IR and use any analysis manager
842 /// provided they satisfy the basic API requirements. When this pass is
843 /// created, these methods can be instantiated to satisfy whatever the
844 /// context requires.
845 template <typename IRUnitT>
846 PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
848 // We have to directly invalidate the analysis result as we can't
849 // enumerate all other analyses and use the preserved set to control it.
850 (void)AM->template invalidate<AnalysisT>(Arg);
852 return PreservedAnalyses::all();
855 static StringRef name() { return "InvalidateAnalysisPass"; }
858 /// \brief A utility pass that does nothing but preserves no analyses.
860 /// As a consequence fo not preserving any analyses, this pass will force all
861 /// analysis passes to be re-run to produce fresh results if any are needed.
862 struct InvalidateAllAnalysesPass {
863 /// \brief Run this pass over some unit of IR.
864 template <typename IRUnitT> PreservedAnalyses run(IRUnitT &Arg) {
865 return PreservedAnalyses::none();
868 static StringRef name() { return "InvalidateAllAnalysesPass"; }