[PM] Add a utility to the new pass manager for generating a pass which
[oota-llvm.git] / include / llvm / IR / PassManager.h
1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
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.
20 ///
21 /// The core IR library provides managers for running passes over
22 /// modules and functions.
23 ///
24 /// * FunctionPassManager can run over a Module, runs each pass over
25 ///   a Function.
26 /// * ModulePassManager must be directly run, runs each pass over the Module.
27 ///
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
35 ///
36 //===----------------------------------------------------------------------===//
37
38 #ifndef LLVM_IR_PASSMANAGER_H
39 #define LLVM_IR_PASSMANAGER_H
40
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/type_traits.h"
48 #include <list>
49 #include <memory>
50 #include <vector>
51
52 namespace llvm {
53
54 class Module;
55 class Function;
56
57 /// \brief An abstract set of preserved analyses following a transformation pass
58 /// run.
59 ///
60 /// When a transformation pass is run, it can return a set of analyses whose
61 /// results were preserved by that transformation. The default set is "none",
62 /// and preserving analyses must be done explicitly.
63 ///
64 /// There is also an explicit all state which can be used (for example) when
65 /// the IR is not mutated at all.
66 class PreservedAnalyses {
67 public:
68   // We have to explicitly define all the special member functions because MSVC
69   // refuses to generate them.
70   PreservedAnalyses() {}
71   PreservedAnalyses(const PreservedAnalyses &Arg)
72       : PreservedPassIDs(Arg.PreservedPassIDs) {}
73   PreservedAnalyses(PreservedAnalyses &&Arg)
74       : PreservedPassIDs(std::move(Arg.PreservedPassIDs)) {}
75   friend void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
76     using std::swap;
77     swap(LHS.PreservedPassIDs, RHS.PreservedPassIDs);
78   }
79   PreservedAnalyses &operator=(PreservedAnalyses RHS) {
80     swap(*this, RHS);
81     return *this;
82   }
83
84   /// \brief Convenience factory function for the empty preserved set.
85   static PreservedAnalyses none() { return PreservedAnalyses(); }
86
87   /// \brief Construct a special preserved set that preserves all passes.
88   static PreservedAnalyses all() {
89     PreservedAnalyses PA;
90     PA.PreservedPassIDs.insert((void *)AllPassesID);
91     return PA;
92   }
93
94   /// \brief Mark a particular pass as preserved, adding it to the set.
95   template <typename PassT> void preserve() {
96     if (!areAllPreserved())
97       PreservedPassIDs.insert(PassT::ID());
98   }
99
100   /// \brief Intersect this set with another in place.
101   ///
102   /// This is a mutating operation on this preserved set, removing all
103   /// preserved passes which are not also preserved in the argument.
104   void intersect(const PreservedAnalyses &Arg) {
105     if (Arg.areAllPreserved())
106       return;
107     if (areAllPreserved()) {
108       PreservedPassIDs = Arg.PreservedPassIDs;
109       return;
110     }
111     for (void *P : PreservedPassIDs)
112       if (!Arg.PreservedPassIDs.count(P))
113         PreservedPassIDs.erase(P);
114   }
115
116   /// \brief Intersect this set with a temporary other set in place.
117   ///
118   /// This is a mutating operation on this preserved set, removing all
119   /// preserved passes which are not also preserved in the argument.
120   void intersect(PreservedAnalyses &&Arg) {
121     if (Arg.areAllPreserved())
122       return;
123     if (areAllPreserved()) {
124       PreservedPassIDs = std::move(Arg.PreservedPassIDs);
125       return;
126     }
127     for (void *P : PreservedPassIDs)
128       if (!Arg.PreservedPassIDs.count(P))
129         PreservedPassIDs.erase(P);
130   }
131
132   /// \brief Query whether a pass is marked as preserved by this set.
133   template <typename PassT> bool preserved() const {
134     return preserved(PassT::ID());
135   }
136
137   /// \brief Query whether an abstract pass ID is marked as preserved by this
138   /// set.
139   bool preserved(void *PassID) const {
140     return PreservedPassIDs.count((void *)AllPassesID) ||
141            PreservedPassIDs.count(PassID);
142   }
143
144   /// \brief Test whether all passes are preserved.
145   ///
146   /// This is used primarily to optimize for the case of no changes which will
147   /// common in many scenarios.
148   bool areAllPreserved() const {
149     return PreservedPassIDs.count((void *)AllPassesID);
150   }
151
152 private:
153   // Note that this must not be -1 or -2 as those are already used by the
154   // SmallPtrSet.
155   static const uintptr_t AllPassesID = (intptr_t)(-3);
156
157   SmallPtrSet<void *, 2> PreservedPassIDs;
158 };
159
160 // We define the pass managers prior to the analysis managers that they use.
161 class ModuleAnalysisManager;
162
163 /// \brief Manages a sequence of passes over Modules of IR.
164 ///
165 /// A module pass manager contains a sequence of module passes. It is also
166 /// itself a module pass. When it is run over a module of LLVM IR, it will
167 /// sequentially run each pass it contains over that module.
168 ///
169 /// If it is run with a \c ModuleAnalysisManager argument, it will propagate
170 /// that analysis manager to each pass it runs, as well as calling the analysis
171 /// manager's invalidation routine with the PreservedAnalyses of each pass it
172 /// runs.
173 ///
174 /// Module passes can rely on having exclusive access to the module they are
175 /// run over. No other threads will access that module, and they can mutate it
176 /// freely. However, they must not mutate other LLVM IR modules.
177 class ModulePassManager {
178 public:
179   // We have to explicitly define all the special member functions because MSVC
180   // refuses to generate them.
181   ModulePassManager() {}
182   ModulePassManager(ModulePassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
183   ModulePassManager &operator=(ModulePassManager &&RHS) {
184     Passes = std::move(RHS.Passes);
185     return *this;
186   }
187
188   /// \brief Run all of the module passes in this module pass manager over
189   /// a module.
190   ///
191   /// This method should only be called for a single module as there is the
192   /// expectation that the lifetime of a pass is bounded to that of a module.
193   PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM = nullptr);
194
195   template <typename ModulePassT> void addPass(ModulePassT Pass) {
196     Passes.emplace_back(new ModulePassModel<ModulePassT>(std::move(Pass)));
197   }
198
199   static StringRef name() { return "ModulePassManager"; }
200
201 private:
202   // Pull in the concept type and model template specialized for modules.
203   typedef detail::PassConcept<Module &, ModuleAnalysisManager>
204       ModulePassConcept;
205   template <typename PassT>
206   struct ModulePassModel
207       : detail::PassModel<Module &, ModuleAnalysisManager, PassT> {
208     ModulePassModel(PassT Pass)
209         : detail::PassModel<Module &, ModuleAnalysisManager, PassT>(
210               std::move(Pass)) {}
211   };
212
213   ModulePassManager(const ModulePassManager &) LLVM_DELETED_FUNCTION;
214   ModulePassManager &operator=(const ModulePassManager &) LLVM_DELETED_FUNCTION;
215
216   std::vector<std::unique_ptr<ModulePassConcept>> Passes;
217 };
218
219 // We define the pass managers prior to the analysis managers that they use.
220 class FunctionAnalysisManager;
221
222 /// \brief Manages a sequence of passes over a Function of IR.
223 ///
224 /// A function pass manager contains a sequence of function passes. It is also
225 /// itself a function pass. When it is run over a function of LLVM IR, it will
226 /// sequentially run each pass it contains over that function.
227 ///
228 /// If it is run with a \c FunctionAnalysisManager argument, it will propagate
229 /// that analysis manager to each pass it runs, as well as calling the analysis
230 /// manager's invalidation routine with the PreservedAnalyses of each pass it
231 /// runs.
232 ///
233 /// Function passes can rely on having exclusive access to the function they
234 /// are run over. They should not read or modify any other functions! Other
235 /// threads or systems may be manipulating other functions in the module, and
236 /// so their state should never be relied on.
237 /// FIXME: Make the above true for all of LLVM's actual passes, some still
238 /// violate this principle.
239 ///
240 /// Function passes can also read the module containing the function, but they
241 /// should not modify that module outside of the use lists of various globals.
242 /// For example, a function pass is not permitted to add functions to the
243 /// module.
244 /// FIXME: Make the above true for all of LLVM's actual passes, some still
245 /// violate this principle.
246 class FunctionPassManager {
247 public:
248   // We have to explicitly define all the special member functions because MSVC
249   // refuses to generate them.
250   FunctionPassManager() {}
251   FunctionPassManager(FunctionPassManager &&Arg)
252       : Passes(std::move(Arg.Passes)) {}
253   FunctionPassManager &operator=(FunctionPassManager &&RHS) {
254     Passes = std::move(RHS.Passes);
255     return *this;
256   }
257
258   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
259     Passes.emplace_back(new FunctionPassModel<FunctionPassT>(std::move(Pass)));
260   }
261
262   PreservedAnalyses run(Function &F, FunctionAnalysisManager *AM = nullptr);
263
264   static StringRef name() { return "FunctionPassManager"; }
265
266 private:
267   // Pull in the concept type and model template specialized for functions.
268   typedef detail::PassConcept<Function &, FunctionAnalysisManager>
269       FunctionPassConcept;
270   template <typename PassT>
271   struct FunctionPassModel
272       : detail::PassModel<Function &, FunctionAnalysisManager, PassT> {
273     FunctionPassModel(PassT Pass)
274         : detail::PassModel<Function &, FunctionAnalysisManager, PassT>(
275               std::move(Pass)) {}
276   };
277
278   FunctionPassManager(const FunctionPassManager &) LLVM_DELETED_FUNCTION;
279   FunctionPassManager &
280   operator=(const FunctionPassManager &) LLVM_DELETED_FUNCTION;
281
282   std::vector<std::unique_ptr<FunctionPassConcept>> Passes;
283 };
284
285 namespace detail {
286
287 /// \brief A CRTP base used to implement analysis managers.
288 ///
289 /// This class template serves as the boiler plate of an analysis manager. Any
290 /// analysis manager can be implemented on top of this base class. Any
291 /// implementation will be required to provide specific hooks:
292 ///
293 /// - getResultImpl
294 /// - getCachedResultImpl
295 /// - invalidateImpl
296 ///
297 /// The details of the call pattern are within.
298 template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
299   DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
300   const DerivedT *derived_this() const {
301     return static_cast<const DerivedT *>(this);
302   }
303
304   AnalysisManagerBase(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
305   AnalysisManagerBase &
306   operator=(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
307
308 protected:
309   typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
310   typedef detail::AnalysisPassConcept<IRUnitT, DerivedT> PassConceptT;
311
312   // FIXME: Provide template aliases for the models when we're using C++11 in
313   // a mode supporting them.
314
315   // We have to explicitly define all the special member functions because MSVC
316   // refuses to generate them.
317   AnalysisManagerBase() {}
318   AnalysisManagerBase(AnalysisManagerBase &&Arg)
319       : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
320   AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
321     AnalysisPasses = std::move(RHS.AnalysisPasses);
322     return *this;
323   }
324
325 public:
326   /// \brief Get the result of an analysis pass for this module.
327   ///
328   /// If there is not a valid cached result in the manager already, this will
329   /// re-run the analysis to produce a valid result.
330   template <typename PassT> typename PassT::Result &getResult(IRUnitT IR) {
331     assert(AnalysisPasses.count(PassT::ID()) &&
332            "This analysis pass was not registered prior to being queried");
333
334     ResultConceptT &ResultConcept =
335         derived_this()->getResultImpl(PassT::ID(), IR);
336     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
337         ResultModelT;
338     return static_cast<ResultModelT &>(ResultConcept).Result;
339   }
340
341   /// \brief Get the cached result of an analysis pass for this module.
342   ///
343   /// This method never runs the analysis.
344   ///
345   /// \returns null if there is no cached result.
346   template <typename PassT>
347   typename PassT::Result *getCachedResult(IRUnitT IR) const {
348     assert(AnalysisPasses.count(PassT::ID()) &&
349            "This analysis pass was not registered prior to being queried");
350
351     ResultConceptT *ResultConcept =
352         derived_this()->getCachedResultImpl(PassT::ID(), IR);
353     if (!ResultConcept)
354       return nullptr;
355
356     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
357         ResultModelT;
358     return &static_cast<ResultModelT *>(ResultConcept)->Result;
359   }
360
361   /// \brief Register an analysis pass with the manager.
362   ///
363   /// This provides an initialized and set-up analysis pass to the analysis
364   /// manager. Whomever is setting up analysis passes must use this to populate
365   /// the manager with all of the analysis passes available.
366   template <typename PassT> void registerPass(PassT Pass) {
367     assert(!AnalysisPasses.count(PassT::ID()) &&
368            "Registered the same analysis pass twice!");
369     typedef detail::AnalysisPassModel<IRUnitT, DerivedT, PassT> PassModelT;
370     AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
371   }
372
373   /// \brief Invalidate a specific analysis pass for an IR module.
374   ///
375   /// Note that the analysis result can disregard invalidation.
376   template <typename PassT> void invalidate(Module &M) {
377     assert(AnalysisPasses.count(PassT::ID()) &&
378            "This analysis pass was not registered prior to being invalidated");
379     derived_this()->invalidateImpl(PassT::ID(), M);
380   }
381
382   /// \brief Invalidate analyses cached for an IR unit.
383   ///
384   /// Walk through all of the analyses pertaining to this unit of IR and
385   /// invalidate them unless they are preserved by the PreservedAnalyses set.
386   void invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
387     derived_this()->invalidateImpl(IR, PA);
388   }
389
390 protected:
391   /// \brief Lookup a registered analysis pass.
392   PassConceptT &lookupPass(void *PassID) {
393     typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
394     assert(PI != AnalysisPasses.end() &&
395            "Analysis passes must be registered prior to being queried!");
396     return *PI->second;
397   }
398
399   /// \brief Lookup a registered analysis pass.
400   const PassConceptT &lookupPass(void *PassID) const {
401     typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
402     assert(PI != AnalysisPasses.end() &&
403            "Analysis passes must be registered prior to being queried!");
404     return *PI->second;
405   }
406
407 private:
408   /// \brief Map type from module analysis pass ID to pass concept pointer.
409   typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
410
411   /// \brief Collection of module analysis passes, indexed by ID.
412   AnalysisPassMapT AnalysisPasses;
413 };
414
415 } // End namespace detail
416
417 /// \brief A module analysis pass manager with lazy running and caching of
418 /// results.
419 class ModuleAnalysisManager
420     : public detail::AnalysisManagerBase<ModuleAnalysisManager, Module &> {
421   friend class detail::AnalysisManagerBase<ModuleAnalysisManager, Module &>;
422   typedef detail::AnalysisManagerBase<ModuleAnalysisManager, Module &> BaseT;
423   typedef BaseT::ResultConceptT ResultConceptT;
424   typedef BaseT::PassConceptT PassConceptT;
425
426 public:
427   // We have to explicitly define all the special member functions because MSVC
428   // refuses to generate them.
429   ModuleAnalysisManager() {}
430   ModuleAnalysisManager(ModuleAnalysisManager &&Arg)
431       : BaseT(std::move(static_cast<BaseT &>(Arg))),
432         ModuleAnalysisResults(std::move(Arg.ModuleAnalysisResults)) {}
433   ModuleAnalysisManager &operator=(ModuleAnalysisManager &&RHS) {
434     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
435     ModuleAnalysisResults = std::move(RHS.ModuleAnalysisResults);
436     return *this;
437   }
438
439 private:
440   ModuleAnalysisManager(const ModuleAnalysisManager &) LLVM_DELETED_FUNCTION;
441   ModuleAnalysisManager &
442   operator=(const ModuleAnalysisManager &) LLVM_DELETED_FUNCTION;
443
444   /// \brief Get a module pass result, running the pass if necessary.
445   ResultConceptT &getResultImpl(void *PassID, Module &M);
446
447   /// \brief Get a cached module pass result or return null.
448   ResultConceptT *getCachedResultImpl(void *PassID, Module &M) const;
449
450   /// \brief Invalidate a module pass result.
451   void invalidateImpl(void *PassID, Module &M);
452
453   /// \brief Invalidate results across a module.
454   void invalidateImpl(Module &M, const PreservedAnalyses &PA);
455
456   /// \brief Map type from module analysis pass ID to pass result concept
457   /// pointer.
458   typedef DenseMap<void *,
459                    std::unique_ptr<detail::AnalysisResultConcept<Module &>>>
460       ModuleAnalysisResultMapT;
461
462   /// \brief Cache of computed module analysis results for this module.
463   ModuleAnalysisResultMapT ModuleAnalysisResults;
464 };
465
466 /// \brief A function analysis manager to coordinate and cache analyses run over
467 /// a module.
468 class FunctionAnalysisManager
469     : public detail::AnalysisManagerBase<FunctionAnalysisManager, Function &> {
470   friend class detail::AnalysisManagerBase<FunctionAnalysisManager, Function &>;
471   typedef detail::AnalysisManagerBase<FunctionAnalysisManager, Function &>
472       BaseT;
473   typedef BaseT::ResultConceptT ResultConceptT;
474   typedef BaseT::PassConceptT PassConceptT;
475
476 public:
477   // Most public APIs are inherited from the CRTP base class.
478
479   // We have to explicitly define all the special member functions because MSVC
480   // refuses to generate them.
481   FunctionAnalysisManager() {}
482   FunctionAnalysisManager(FunctionAnalysisManager &&Arg)
483       : BaseT(std::move(static_cast<BaseT &>(Arg))),
484         FunctionAnalysisResults(std::move(Arg.FunctionAnalysisResults)) {}
485   FunctionAnalysisManager &operator=(FunctionAnalysisManager &&RHS) {
486     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
487     FunctionAnalysisResults = std::move(RHS.FunctionAnalysisResults);
488     return *this;
489   }
490
491   /// \brief Returns true if the analysis manager has an empty results cache.
492   bool empty() const;
493
494   /// \brief Clear the function analysis result cache.
495   ///
496   /// This routine allows cleaning up when the set of functions itself has
497   /// potentially changed, and thus we can't even look up a a result and
498   /// invalidate it directly. Notably, this does *not* call invalidate
499   /// functions as there is nothing to be done for them.
500   void clear();
501
502 private:
503   FunctionAnalysisManager(const FunctionAnalysisManager &)
504       LLVM_DELETED_FUNCTION;
505   FunctionAnalysisManager &
506   operator=(const FunctionAnalysisManager &) LLVM_DELETED_FUNCTION;
507
508   /// \brief Get a function pass result, running the pass if necessary.
509   ResultConceptT &getResultImpl(void *PassID, Function &F);
510
511   /// \brief Get a cached function pass result or return null.
512   ResultConceptT *getCachedResultImpl(void *PassID, Function &F) const;
513
514   /// \brief Invalidate a function pass result.
515   void invalidateImpl(void *PassID, Function &F);
516
517   /// \brief Invalidate the results for a function..
518   void invalidateImpl(Function &F, const PreservedAnalyses &PA);
519
520   /// \brief List of function analysis pass IDs and associated concept pointers.
521   ///
522   /// Requires iterators to be valid across appending new entries and arbitrary
523   /// erases. Provides both the pass ID and concept pointer such that it is
524   /// half of a bijection and provides storage for the actual result concept.
525   typedef std::list<std::pair<
526       void *, std::unique_ptr<detail::AnalysisResultConcept<Function &>>>>
527       FunctionAnalysisResultListT;
528
529   /// \brief Map type from function pointer to our custom list type.
530   typedef DenseMap<Function *, FunctionAnalysisResultListT>
531       FunctionAnalysisResultListMapT;
532
533   /// \brief Map from function to a list of function analysis results.
534   ///
535   /// Provides linear time removal of all analysis results for a function and
536   /// the ultimate storage for a particular cached analysis result.
537   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
538
539   /// \brief Map type from a pair of analysis ID and function pointer to an
540   /// iterator into a particular result list.
541   typedef DenseMap<std::pair<void *, Function *>,
542                    FunctionAnalysisResultListT::iterator>
543       FunctionAnalysisResultMapT;
544
545   /// \brief Map from an analysis ID and function to a particular cached
546   /// analysis result.
547   FunctionAnalysisResultMapT FunctionAnalysisResults;
548 };
549
550 /// \brief A module analysis which acts as a proxy for a function analysis
551 /// manager.
552 ///
553 /// This primarily proxies invalidation information from the module analysis
554 /// manager and module pass manager to a function analysis manager. You should
555 /// never use a function analysis manager from within (transitively) a module
556 /// pass manager unless your parent module pass has received a proxy result
557 /// object for it.
558 class FunctionAnalysisManagerModuleProxy {
559 public:
560   class Result;
561
562   static void *ID() { return (void *)&PassID; }
563
564   static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
565
566   explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
567       : FAM(&FAM) {}
568   // We have to explicitly define all the special member functions because MSVC
569   // refuses to generate them.
570   FunctionAnalysisManagerModuleProxy(
571       const FunctionAnalysisManagerModuleProxy &Arg)
572       : FAM(Arg.FAM) {}
573   FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
574       : FAM(std::move(Arg.FAM)) {}
575   FunctionAnalysisManagerModuleProxy &
576   operator=(FunctionAnalysisManagerModuleProxy RHS) {
577     std::swap(FAM, RHS.FAM);
578     return *this;
579   }
580
581   /// \brief Run the analysis pass and create our proxy result object.
582   ///
583   /// This doesn't do any interesting work, it is primarily used to insert our
584   /// proxy result object into the module analysis cache so that we can proxy
585   /// invalidation to the function analysis manager.
586   ///
587   /// In debug builds, it will also assert that the analysis manager is empty
588   /// as no queries should arrive at the function analysis manager prior to
589   /// this analysis being requested.
590   Result run(Module &M);
591
592 private:
593   static char PassID;
594
595   FunctionAnalysisManager *FAM;
596 };
597
598 /// \brief The result proxy object for the
599 /// \c FunctionAnalysisManagerModuleProxy.
600 ///
601 /// See its documentation for more information.
602 class FunctionAnalysisManagerModuleProxy::Result {
603 public:
604   explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
605   // We have to explicitly define all the special member functions because MSVC
606   // refuses to generate them.
607   Result(const Result &Arg) : FAM(Arg.FAM) {}
608   Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
609   Result &operator=(Result RHS) {
610     std::swap(FAM, RHS.FAM);
611     return *this;
612   }
613   ~Result();
614
615   /// \brief Accessor for the \c FunctionAnalysisManager.
616   FunctionAnalysisManager &getManager() { return *FAM; }
617
618   /// \brief Handler for invalidation of the module.
619   ///
620   /// If this analysis itself is preserved, then we assume that the set of \c
621   /// Function objects in the \c Module hasn't changed and thus we don't need
622   /// to invalidate *all* cached data associated with a \c Function* in the \c
623   /// FunctionAnalysisManager.
624   ///
625   /// Regardless of whether this analysis is marked as preserved, all of the
626   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
627   /// based on the set of preserved analyses.
628   bool invalidate(Module &M, const PreservedAnalyses &PA);
629
630 private:
631   FunctionAnalysisManager *FAM;
632 };
633
634 /// \brief A function analysis which acts as a proxy for a module analysis
635 /// manager.
636 ///
637 /// This primarily provides an accessor to a parent module analysis manager to
638 /// function passes. Only the const interface of the module analysis manager is
639 /// provided to indicate that once inside of a function analysis pass you
640 /// cannot request a module analysis to actually run. Instead, the user must
641 /// rely on the \c getCachedResult API.
642 ///
643 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
644 /// the recursive return path of each layer of the pass manager and the
645 /// returned PreservedAnalysis set.
646 class ModuleAnalysisManagerFunctionProxy {
647 public:
648   /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
649   class Result {
650   public:
651     explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
652     // We have to explicitly define all the special member functions because
653     // MSVC refuses to generate them.
654     Result(const Result &Arg) : MAM(Arg.MAM) {}
655     Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
656     Result &operator=(Result RHS) {
657       std::swap(MAM, RHS.MAM);
658       return *this;
659     }
660
661     const ModuleAnalysisManager &getManager() const { return *MAM; }
662
663     /// \brief Handle invalidation by ignoring it, this pass is immutable.
664     bool invalidate(Function &) { return false; }
665
666   private:
667     const ModuleAnalysisManager *MAM;
668   };
669
670   static void *ID() { return (void *)&PassID; }
671
672   static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
673
674   ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
675       : MAM(&MAM) {}
676   // We have to explicitly define all the special member functions because MSVC
677   // refuses to generate them.
678   ModuleAnalysisManagerFunctionProxy(
679       const ModuleAnalysisManagerFunctionProxy &Arg)
680       : MAM(Arg.MAM) {}
681   ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
682       : MAM(std::move(Arg.MAM)) {}
683   ModuleAnalysisManagerFunctionProxy &
684   operator=(ModuleAnalysisManagerFunctionProxy RHS) {
685     std::swap(MAM, RHS.MAM);
686     return *this;
687   }
688
689   /// \brief Run the analysis pass and create our proxy result object.
690   /// Nothing to see here, it just forwards the \c MAM reference into the
691   /// result.
692   Result run(Function &) { return Result(*MAM); }
693
694 private:
695   static char PassID;
696
697   const ModuleAnalysisManager *MAM;
698 };
699
700 /// \brief Trivial adaptor that maps from a module to its functions.
701 ///
702 /// Designed to allow composition of a FunctionPass(Manager) and
703 /// a ModulePassManager. Note that if this pass is constructed with a pointer
704 /// to a \c ModuleAnalysisManager it will run the
705 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
706 /// pass over the module to enable a \c FunctionAnalysisManager to be used
707 /// within this run safely.
708 template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
709 public:
710   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
711       : Pass(std::move(Pass)) {}
712   // We have to explicitly define all the special member functions because MSVC
713   // refuses to generate them.
714   ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
715       : Pass(Arg.Pass) {}
716   ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
717       : Pass(std::move(Arg.Pass)) {}
718   friend void swap(ModuleToFunctionPassAdaptor &LHS,
719                    ModuleToFunctionPassAdaptor &RHS) {
720     using std::swap;
721     swap(LHS.Pass, RHS.Pass);
722   }
723   ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
724     swap(*this, RHS);
725     return *this;
726   }
727
728   /// \brief Runs the function pass across every function in the module.
729   PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
730     FunctionAnalysisManager *FAM = nullptr;
731     if (AM)
732       // Setup the function analysis manager from its proxy.
733       FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
734
735     PreservedAnalyses PA = PreservedAnalyses::all();
736     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
737       PreservedAnalyses PassPA = Pass.run(*I, FAM);
738
739       // We know that the function pass couldn't have invalidated any other
740       // function's analyses (that's the contract of a function pass), so
741       // directly handle the function analysis manager's invalidation here.
742       if (FAM)
743         FAM->invalidate(*I, PassPA);
744
745       // Then intersect the preserved set so that invalidation of module
746       // analyses will eventually occur when the module pass completes.
747       PA.intersect(std::move(PassPA));
748     }
749
750     // By definition we preserve the proxy. This precludes *any* invalidation
751     // of function analyses by the proxy, but that's OK because we've taken
752     // care to invalidate analyses in the function analysis manager
753     // incrementally above.
754     PA.preserve<FunctionAnalysisManagerModuleProxy>();
755     return PA;
756   }
757
758   static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
759
760 private:
761   FunctionPassT Pass;
762 };
763
764 /// \brief A function to deduce a function pass type and wrap it in the
765 /// templated adaptor.
766 template <typename FunctionPassT>
767 ModuleToFunctionPassAdaptor<FunctionPassT>
768 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
769   return std::move(ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)));
770 }
771
772 /// \brief A template utility pass to force an analysis result to be available.
773 ///
774 /// This is a no-op pass which simply forces a specific analysis pass's result
775 /// to be available when it is run.
776 template <typename AnalysisT> struct NoopAnalysisRequirementPass {
777   /// \brief Run this pass over some unit of IR.
778   ///
779   /// This pass can be run over any unit of IR and use any analysis manager
780   /// provided they satisfy the basic API requirements. When this pass is
781   /// created, these methods can be instantiated to satisfy whatever the
782   /// context requires.
783   template <typename T, typename AnalysisManagerT>
784   PreservedAnalyses run(T &&Arg, AnalysisManagerT *AM) {
785     if (AM)
786       (void)AM->template getResult<AnalysisT>(std::forward<T>(Arg));
787
788     return PreservedAnalyses::all();
789   }
790
791   static StringRef name() { return "No-op Analysis Requirement Pass"; }
792 };
793
794 }
795
796 #endif