c997f3a46909e519a5bd94a8ac43e6fd2bfecfe2
[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 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/polymorphic_ptr.h"
41 #include "llvm/Support/type_traits.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Module.h"
44 #include <list>
45 #include <vector>
46
47 namespace llvm {
48
49 class Module;
50 class Function;
51
52 /// \brief An abstract set of preserved analyses following a transformation pass
53 /// run.
54 ///
55 /// When a transformation pass is run, it can return a set of analyses whose
56 /// results were preserved by that transformation. The default set is "none",
57 /// and preserving analyses must be done explicitly.
58 ///
59 /// There is also an explicit all state which can be used (for example) when
60 /// the IR is not mutated at all.
61 class PreservedAnalyses {
62 public:
63   /// \brief Convenience factory function for the empty preserved set.
64   static PreservedAnalyses none() { return PreservedAnalyses(); }
65
66   /// \brief Construct a special preserved set that preserves all passes.
67   static PreservedAnalyses all() {
68     PreservedAnalyses PA;
69     PA.PreservedPassIDs.insert((void *)AllPassesID);
70     return PA;
71   }
72
73   PreservedAnalyses &operator=(PreservedAnalyses Arg) {
74     swap(Arg);
75     return *this;
76   }
77
78   void swap(PreservedAnalyses &Arg) {
79     PreservedPassIDs.swap(Arg.PreservedPassIDs);
80   }
81
82   /// \brief Mark a particular pass as preserved, adding it to the set.
83   template <typename PassT> void preserve() {
84     if (!areAllPreserved())
85       PreservedPassIDs.insert(PassT::ID());
86   }
87
88   /// \brief Intersect this set with another in place.
89   ///
90   /// This is a mutating operation on this preserved set, removing all
91   /// preserved passes which are not also preserved in the argument.
92   void intersect(const PreservedAnalyses &Arg) {
93     if (Arg.areAllPreserved())
94       return;
95     if (areAllPreserved()) {
96       PreservedPassIDs = Arg.PreservedPassIDs;
97       return;
98     }
99     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
100                                                 E = PreservedPassIDs.end();
101          I != E; ++I)
102       if (!Arg.PreservedPassIDs.count(*I))
103         PreservedPassIDs.erase(*I);
104   }
105
106 #if LLVM_HAS_RVALUE_REFERENCES
107   /// \brief Intersect this set with a temporary other set in place.
108   ///
109   /// This is a mutating operation on this preserved set, removing all
110   /// preserved passes which are not also preserved in the argument.
111   void intersect(PreservedAnalyses &&Arg) {
112     if (Arg.areAllPreserved())
113       return;
114     if (areAllPreserved()) {
115       PreservedPassIDs = std::move(Arg.PreservedPassIDs);
116       return;
117     }
118     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
119                                                 E = PreservedPassIDs.end();
120          I != E; ++I)
121       if (!Arg.PreservedPassIDs.count(*I))
122         PreservedPassIDs.erase(*I);
123   }
124 #endif
125
126   /// \brief Query whether a pass is marked as preserved by this set.
127   template <typename PassT> bool preserved() const {
128     return preserved(PassT::ID());
129   }
130
131   /// \brief Query whether an abstract pass ID is marked as preserved by this
132   /// set.
133   bool preserved(void *PassID) const {
134     return PreservedPassIDs.count((void *)AllPassesID) ||
135            PreservedPassIDs.count(PassID);
136   }
137
138 private:
139   // Note that this must not be -1 or -2 as those are already used by the
140   // SmallPtrSet.
141   static const uintptr_t AllPassesID = (intptr_t)-3;
142
143   bool areAllPreserved() const { return PreservedPassIDs.count((void *)AllPassesID); }
144
145   SmallPtrSet<void *, 2> PreservedPassIDs;
146 };
147
148 inline void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
149   LHS.swap(RHS);
150 }
151
152 /// \brief Implementation details of the pass manager interfaces.
153 namespace detail {
154
155 /// \brief Template for the abstract base class used to dispatch
156 /// polymorphically over pass objects.
157 template <typename IRUnitT, typename AnalysisManagerT> struct PassConcept {
158   // Boiler plate necessary for the container of derived classes.
159   virtual ~PassConcept() {}
160   virtual PassConcept *clone() = 0;
161
162   /// \brief The polymorphic API which runs the pass over a given IR entity.
163   ///
164   /// Note that actual pass object can omit the analysis manager argument if
165   /// desired. Also that the analysis manager may be null if there is no
166   /// analysis manager in the pass pipeline.
167   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) = 0;
168 };
169
170 /// \brief SFINAE metafunction for computing whether \c PassT has a run method
171 /// accepting an \c AnalysisManagerT.
172 template <typename IRUnitT, typename PassT, typename AnalysisManagerT>
173 class PassRunAcceptsAnalysisManager {
174   typedef char SmallType;
175   struct BigType { char a, b; };
176
177   template <typename T, PreservedAnalyses (T::*)(IRUnitT, AnalysisManagerT *)>
178   struct Checker;
179
180   template <typename T> static SmallType f(Checker<T, &T::run> *);
181   template <typename T> static BigType f(...);
182
183 public:
184   enum { Value = sizeof(f<PassT>(0)) == sizeof(SmallType) };
185 };
186
187 /// \brief A template wrapper used to implement the polymorphic API.
188 ///
189 /// Can be instantiated for any object which provides a \c run method accepting
190 /// an \c IRUnitT. It requires the pass to be a copyable object. When the
191 /// \c run method also accepts an \c AnalysisManagerT*, we pass it along.
192 template <typename IRUnitT, typename PassT, typename AnalysisManagerT,
193           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
194               IRUnitT, PassT, AnalysisManagerT>::Value>
195 struct PassModel;
196
197 /// \brief Specialization of \c PassModel for passes that accept an analyis
198 /// manager.
199 template <typename IRUnitT, typename PassT, typename AnalysisManagerT>
200 struct PassModel<IRUnitT, PassT, AnalysisManagerT,
201                  true> : PassConcept<IRUnitT, AnalysisManagerT> {
202   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
203   virtual PassModel *clone() { return new PassModel(Pass); }
204   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
205     return Pass.run(IR, AM);
206   }
207   PassT Pass;
208 };
209
210 /// \brief Specialization of \c PassModel for passes that accept an analyis
211 /// manager.
212 template <typename IRUnitT, typename PassT, typename AnalysisManagerT>
213 struct PassModel<IRUnitT, PassT, AnalysisManagerT,
214                  false> : PassConcept<IRUnitT, AnalysisManagerT> {
215   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
216   virtual PassModel *clone() { return new PassModel(Pass); }
217   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
218     return Pass.run(IR);
219   }
220   PassT Pass;
221 };
222
223 /// \brief Abstract concept of an analysis result.
224 ///
225 /// This concept is parameterized over the IR unit that this result pertains
226 /// to.
227 template <typename IRUnitT> struct AnalysisResultConcept {
228   virtual ~AnalysisResultConcept() {}
229   virtual AnalysisResultConcept *clone() = 0;
230
231   /// \brief Method to try and mark a result as invalid.
232   ///
233   /// When the outer analysis manager detects a change in some underlying
234   /// unit of the IR, it will call this method on all of the results cached.
235   ///
236   /// This method also receives a set of preserved analyses which can be used
237   /// to avoid invalidation because the pass which changed the underlying IR
238   /// took care to update or preserve the analysis result in some way.
239   ///
240   /// \returns true if the result is indeed invalid (the default).
241   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) = 0;
242 };
243
244 /// \brief SFINAE metafunction for computing whether \c ResultT provides an
245 /// \c invalidate member function.
246 template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod {
247   typedef char SmallType;
248   struct BigType { char a, b; };
249
250   template <typename T, bool (T::*)(IRUnitT, const PreservedAnalyses &)>
251   struct Checker;
252
253   template <typename T> static SmallType f(Checker<T, &T::invalidate> *);
254   template <typename T> static BigType f(...);
255
256 public:
257   enum { Value = sizeof(f<ResultT>(0)) == sizeof(SmallType) };
258 };
259
260 /// \brief Wrapper to model the analysis result concept.
261 ///
262 /// By default, this will implement the invalidate method with a trivial
263 /// implementation so that the actual analysis result doesn't need to provide
264 /// an invalidation handler. It is only selected when the invalidation handler
265 /// is not part of the ResultT's interface.
266 template <typename IRUnitT, typename PassT, typename ResultT,
267           bool HasInvalidateHandler =
268               ResultHasInvalidateMethod<IRUnitT, ResultT>::Value>
269 struct AnalysisResultModel;
270
271 /// \brief Specialization of \c AnalysisResultModel which provides the default
272 /// invalidate functionality.
273 template <typename IRUnitT, typename PassT, typename ResultT>
274 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
275                            false> : AnalysisResultConcept<IRUnitT> {
276   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
277   virtual AnalysisResultModel *clone() {
278     return new AnalysisResultModel(Result);
279   }
280
281   /// \brief The model bases invalidation solely on being in the preserved set.
282   //
283   // FIXME: We should actually use two different concepts for analysis results
284   // rather than two different models, and avoid the indirect function call for
285   // ones that use the trivial behavior.
286   virtual bool invalidate(IRUnitT, const PreservedAnalyses &PA) {
287     return !PA.preserved(PassT::ID());
288   }
289
290   ResultT Result;
291 };
292
293 /// \brief Specialization of \c AnalysisResultModel which delegates invalidate
294 /// handling to \c ResultT.
295 template <typename IRUnitT, typename PassT, typename ResultT>
296 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
297                            true> : AnalysisResultConcept<IRUnitT> {
298   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
299   virtual AnalysisResultModel *clone() {
300     return new AnalysisResultModel(Result);
301   }
302
303   /// \brief The model delegates to the \c ResultT method.
304   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
305     return Result.invalidate(IR, PA);
306   }
307
308   ResultT Result;
309 };
310
311 /// \brief Abstract concept of an analysis pass.
312 ///
313 /// This concept is parameterized over the IR unit that it can run over and
314 /// produce an analysis result.
315 template <typename IRUnitT> struct AnalysisPassConcept {
316   virtual ~AnalysisPassConcept() {}
317   virtual AnalysisPassConcept *clone() = 0;
318
319   /// \brief Method to run this analysis over a unit of IR.
320   /// \returns The analysis result object to be queried by users, the caller
321   /// takes ownership.
322   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT IR) = 0;
323 };
324
325 /// \brief Wrapper to model the analysis pass concept.
326 ///
327 /// Can wrap any type which implements a suitable \c run method. The method
328 /// must accept the IRUnitT as an argument and produce an object which can be
329 /// wrapped in a \c AnalysisResultModel.
330 template <typename PassT>
331 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
332   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
333   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
334
335   // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
336   typedef typename PassT::IRUnitT IRUnitT;
337
338   // FIXME: Replace PassT::Result with type traits when we use C++11.
339   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
340       ResultModelT;
341
342   /// \brief The model delegates to the \c PassT::run method.
343   ///
344   /// The return is wrapped in an \c AnalysisResultModel.
345   virtual ResultModelT *run(IRUnitT IR) {
346     return new ResultModelT(Pass.run(IR));
347   }
348
349   PassT Pass;
350 };
351
352 }
353
354 class ModuleAnalysisManager;
355
356 class ModulePassManager {
357 public:
358   explicit ModulePassManager() {}
359
360   /// \brief Run all of the module passes in this module pass manager over
361   /// a module.
362   ///
363   /// This method should only be called for a single module as there is the
364   /// expectation that the lifetime of a pass is bounded to that of a module.
365   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM = 0);
366
367   template <typename ModulePassT> void addPass(ModulePassT Pass) {
368     Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
369   }
370
371 private:
372   // Pull in the concept type and model template specialized for modules.
373   typedef detail::PassConcept<Module *, ModuleAnalysisManager> ModulePassConcept;
374   template <typename PassT>
375   struct ModulePassModel
376       : detail::PassModel<Module *, PassT, ModuleAnalysisManager> {
377     ModulePassModel(PassT Pass)
378         : detail::PassModel<Module *, PassT, ModuleAnalysisManager>(Pass) {}
379   };
380
381   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
382 };
383
384 class FunctionAnalysisManager;
385
386 class FunctionPassManager {
387 public:
388   explicit FunctionPassManager() {}
389
390   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
391     Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
392   }
393
394   PreservedAnalyses run(Function *F, FunctionAnalysisManager *AM = 0);
395
396 private:
397   // Pull in the concept type and model template specialized for functions.
398   typedef detail::PassConcept<Function *, FunctionAnalysisManager>
399       FunctionPassConcept;
400   template <typename PassT>
401   struct FunctionPassModel
402       : detail::PassModel<Function *, PassT, FunctionAnalysisManager> {
403     FunctionPassModel(PassT Pass)
404         : detail::PassModel<Function *, PassT, FunctionAnalysisManager>(Pass) {}
405   };
406
407   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
408 };
409
410 /// \brief A module analysis pass manager with lazy running and caching of
411 /// results.
412 class ModuleAnalysisManager {
413 public:
414   ModuleAnalysisManager() {}
415
416   /// \brief Get the result of an analysis pass for this module.
417   ///
418   /// If there is not a valid cached result in the manager already, this will
419   /// re-run the analysis to produce a valid result.
420   template <typename PassT> const typename PassT::Result &getResult(Module *M) {
421     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module *>::value),
422                        "The analysis pass must be over a Module.");
423     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
424            "This analysis pass was not registered prior to being queried");
425
426     const detail::AnalysisResultConcept<Module *> &ResultConcept =
427         getResultImpl(PassT::ID(), M);
428     typedef detail::AnalysisResultModel<Module *, PassT, typename PassT::Result>
429         ResultModelT;
430     return static_cast<const ResultModelT &>(ResultConcept).Result;
431   }
432
433   /// \brief Register an analysis pass with the manager.
434   ///
435   /// This provides an initialized and set-up analysis pass to the
436   /// analysis
437   /// manager. Whomever is setting up analysis passes must use this to
438   /// populate
439   /// the manager with all of the analysis passes available.
440   template <typename PassT> void registerPass(PassT Pass) {
441     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module *>::value),
442                        "The analysis pass must be over a Module.");
443     assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
444            "Registered the same analysis pass twice!");
445     ModuleAnalysisPasses[PassT::ID()] =
446         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
447   }
448
449   /// \brief Invalidate a specific analysis pass for an IR module.
450   ///
451   /// Note that the analysis result can disregard invalidation.
452   template <typename PassT> void invalidate(Module *M) {
453     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module *>::value),
454                        "The analysis pass must be over a Module.");
455     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
456            "This analysis pass was not registered prior to being invalidated");
457     invalidateImpl(PassT::ID(), M);
458   }
459
460   /// \brief Invalidate analyses cached for an IR Module.
461   ///
462   /// Walk through all of the analyses pertaining to this module and invalidate
463   /// them unless they are preserved by the PreservedAnalyses set.
464   void invalidate(Module *M, const PreservedAnalyses &PA);
465
466 private:
467   /// \brief Get a module pass result, running the pass if necessary.
468   const detail::AnalysisResultConcept<Module *> &getResultImpl(void *PassID,
469                                                                Module *M);
470
471   /// \brief Invalidate a module pass result.
472   void invalidateImpl(void *PassID, Module *M);
473
474   /// \brief Map type from module analysis pass ID to pass concept pointer.
475   typedef DenseMap<void *,
476                    polymorphic_ptr<detail::AnalysisPassConcept<Module *> > >
477       ModuleAnalysisPassMapT;
478
479   /// \brief Collection of module analysis passes, indexed by ID.
480   ModuleAnalysisPassMapT ModuleAnalysisPasses;
481
482   /// \brief Map type from module analysis pass ID to pass result concept pointer.
483   typedef DenseMap<void *,
484                    polymorphic_ptr<detail::AnalysisResultConcept<Module *> > >
485       ModuleAnalysisResultMapT;
486
487   /// \brief Cache of computed module analysis results for this module.
488   ModuleAnalysisResultMapT ModuleAnalysisResults;
489 };
490
491 /// \brief A function analysis manager to coordinate and cache analyses run over
492 /// a module.
493 class FunctionAnalysisManager {
494 public:
495   FunctionAnalysisManager() {}
496
497   /// \brief Get the result of an analysis pass for a function.
498   ///
499   /// If there is not a valid cached result in the manager already, this will
500   /// re-run the analysis to produce a valid result.
501   template <typename PassT>
502   const typename PassT::Result &getResult(Function *F) {
503     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function *>::value),
504                        "The analysis pass must be over a Function.");
505     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
506            "This analysis pass was not registered prior to being queried");
507
508     const detail::AnalysisResultConcept<Function *> &ResultConcept =
509         getResultImpl(PassT::ID(), F);
510     typedef detail::AnalysisResultModel<Function *, PassT,
511                                         typename PassT::Result> ResultModelT;
512     return static_cast<const ResultModelT &>(ResultConcept).Result;
513   }
514
515   /// \brief Register an analysis pass with the manager.
516   ///
517   /// This provides an initialized and set-up analysis pass to the
518   /// analysis
519   /// manager. Whomever is setting up analysis passes must use this to
520   /// populate
521   /// the manager with all of the analysis passes available.
522   template <typename PassT> void registerPass(PassT Pass) {
523     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function *>::value),
524                        "The analysis pass must be over a Function.");
525     assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
526            "Registered the same analysis pass twice!");
527     FunctionAnalysisPasses[PassT::ID()] =
528         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
529   }
530
531   /// \brief Invalidate a specific analysis pass for an IR module.
532   ///
533   /// Note that the analysis result can disregard invalidation.
534   template <typename PassT> void invalidate(Function *F) {
535     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function *>::value),
536                        "The analysis pass must be over a Function.");
537     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
538            "This analysis pass was not registered prior to being invalidated");
539     invalidateImpl(PassT::ID(), F);
540   }
541
542   /// \brief Invalidate analyses cached for an IR Function.
543   ///
544   /// Walk through all of the analyses cache for this IR function and
545   /// invalidate them unless they are preserved by the provided
546   /// PreservedAnalyses set.
547   void invalidate(Function *F, const PreservedAnalyses &PA);
548
549   /// \brief Returns true if the analysis manager has an empty results cache.
550   bool empty() const;
551
552   /// \brief Clear the function analysis result cache.
553   ///
554   /// This routine allows cleaning up when the set of functions itself has
555   /// potentially changed, and thus we can't even look up a a result and
556   /// invalidate it directly. Notably, this does *not* call invalidate
557   /// functions as there is nothing to be done for them.
558   void clear();
559
560 private:
561   /// \brief Get a function pass result, running the pass if necessary.
562   const detail::AnalysisResultConcept<Function *> &getResultImpl(void *PassID,
563                                                                  Function *F);
564
565   /// \brief Invalidate a function pass result.
566   void invalidateImpl(void *PassID, Function *F);
567
568   /// \brief Map type from function analysis pass ID to pass concept pointer.
569   typedef DenseMap<void *,
570                    polymorphic_ptr<detail::AnalysisPassConcept<Function *> > >
571       FunctionAnalysisPassMapT;
572
573   /// \brief Collection of function analysis passes, indexed by ID.
574   FunctionAnalysisPassMapT FunctionAnalysisPasses;
575
576   /// \brief List of function analysis pass IDs and associated concept pointers.
577   ///
578   /// Requires iterators to be valid across appending new entries and arbitrary
579   /// erases. Provides both the pass ID and concept pointer such that it is
580   /// half of a bijection and provides storage for the actual result concept.
581   typedef std::list<std::pair<
582       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function *> > > >
583       FunctionAnalysisResultListT;
584
585   /// \brief Map type from function pointer to our custom list type.
586   typedef DenseMap<Function *, FunctionAnalysisResultListT>
587   FunctionAnalysisResultListMapT;
588
589   /// \brief Map from function to a list of function analysis results.
590   ///
591   /// Provides linear time removal of all analysis results for a function and
592   /// the ultimate storage for a particular cached analysis result.
593   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
594
595   /// \brief Map type from a pair of analysis ID and function pointer to an
596   /// iterator into a particular result list.
597   typedef DenseMap<std::pair<void *, Function *>,
598                    FunctionAnalysisResultListT::iterator>
599       FunctionAnalysisResultMapT;
600
601   /// \brief Map from an analysis ID and function to a particular cached
602   /// analysis result.
603   FunctionAnalysisResultMapT FunctionAnalysisResults;
604 };
605
606 /// \brief A module analysis which acts as a proxy for a function analysis
607 /// manager.
608 ///
609 /// This primarily proxies invalidation information from the module analysis
610 /// manager and module pass manager to a function analysis manager. You should
611 /// never use a function analysis manager from within (transitively) a module
612 /// pass manager unless your parent module pass has received a proxy result
613 /// object for it.
614 ///
615 /// FIXME: It might be really nice to "enforce" this (softly) by making this
616 /// proxy the API path to access a function analysis manager within a module
617 /// pass.
618 class FunctionAnalysisManagerModuleProxy {
619 public:
620   typedef Module *IRUnitT;
621   class Result;
622
623   static void *ID() { return (void *)&PassID; }
624
625   FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
626
627   /// \brief Run the analysis pass and create our proxy result object.
628   ///
629   /// This doesn't do any interesting work, it is primarily used to insert our
630   /// proxy result object into the module analysis cache so that we can proxy
631   /// invalidation to the function analysis manager.
632   ///
633   /// In debug builds, it will also assert that the analysis manager is empty
634   /// as no queries should arrive at the function analysis manager prior to
635   /// this analysis being requested.
636   Result run(Module *M);
637
638 private:
639   static char PassID;
640
641   FunctionAnalysisManager &FAM;
642 };
643
644 /// \brief The result proxy object for the
645 /// \c FunctionAnalysisManagerModuleProxy.
646 ///
647 /// See its documentation for more information.
648 class FunctionAnalysisManagerModuleProxy::Result {
649 public:
650   Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
651   ~Result();
652
653   /// \brief Accessor for the \c FunctionAnalysisManager.
654   FunctionAnalysisManager &getManager() const { return FAM; }
655
656   /// \brief Handler for invalidation of the module.
657   ///
658   /// If this analysis itself is preserved, then we assume that the set of \c
659   /// Function objects in the \c Module hasn't changed and thus we don't need
660   /// to invalidate *all* cached data associated with a \c Function* in the \c
661   /// FunctionAnalysisManager.
662   ///
663   /// Regardless of whether this analysis is marked as preserved, all of the
664   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
665   /// based on the set of preserved analyses.
666   bool invalidate(Module *M, const PreservedAnalyses &PA);
667
668 private:
669   FunctionAnalysisManager &FAM;
670 };
671
672 /// \brief Trivial adaptor that maps from a module to its functions.
673 ///
674 /// Designed to allow composition of a FunctionPass(Manager) and
675 /// a ModulePassManager. Note that if this pass is constructed with a pointer
676 /// to a \c ModuleAnalysisManager it will run the
677 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
678 /// pass over the module to enable a \c FunctionAnalysisManager to be used
679 /// within this run safely.
680 template <typename FunctionPassT>
681 class ModuleToFunctionPassAdaptor {
682 public:
683   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
684       : Pass(llvm_move(Pass)) {}
685
686   /// \brief Runs the function pass across every function in the module.
687   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM) {
688     FunctionAnalysisManager *FAM = 0;
689     if (AM)
690       // Setup the function analysis manager from its proxy.
691       FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
692
693     PreservedAnalyses PA = PreservedAnalyses::all();
694     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
695       PreservedAnalyses PassPA = Pass.run(I, FAM);
696       PA.intersect(llvm_move(PassPA));
697     }
698
699     // By definition we preserve the proxy.
700     PA.preserve<FunctionAnalysisManagerModuleProxy>();
701     return PA;
702   }
703
704 private:
705   FunctionPassT Pass;
706 };
707
708 /// \brief A function to deduce a function pass type and wrap it in the
709 /// templated adaptor.
710 template <typename FunctionPassT>
711 ModuleToFunctionPassAdaptor<FunctionPassT>
712 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
713   return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass));
714 }
715
716 }