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