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