[PM] Switch analysis managers to be threaded through the run methods
[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 Wrapper to model the analysis result concept.
245 ///
246 /// By default, this will implement the invalidate method with a trivial
247 /// implementation so that the actual analysis result doesn't need to provide
248 /// an invalidation handler. It is only selected when the invalidation handler
249 /// is not part of the ResultT's interface.
250 template <typename IRUnitT, typename PassT, typename ResultT,
251           bool HasInvalidateHandler = false>
252 struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
253   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
254   virtual AnalysisResultModel *clone() {
255     return new AnalysisResultModel(Result);
256   }
257
258   /// \brief The model bases invalidation solely on being in the preserved set.
259   //
260   // FIXME: We should actually use two different concepts for analysis results
261   // rather than two different models, and avoid the indirect function call for
262   // ones that use the trivial behavior.
263   virtual bool invalidate(IRUnitT *, const PreservedAnalyses &PA) {
264     return !PA.preserved(PassT::ID());
265   }
266
267   ResultT Result;
268 };
269
270 /// \brief Wrapper to model the analysis result concept.
271 ///
272 /// Can wrap any type which implements a suitable invalidate member and model
273 /// the AnalysisResultConcept for the AnalysisManager.
274 template <typename IRUnitT, typename PassT, typename ResultT>
275 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
276                            true> : AnalysisResultConcept<IRUnitT> {
277   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
278   virtual AnalysisResultModel *clone() {
279     return new AnalysisResultModel(Result);
280   }
281
282   /// \brief The model delegates to the \c ResultT method.
283   virtual bool invalidate(IRUnitT *IR, const PreservedAnalyses &PA) {
284     return Result.invalidate(IR, PA);
285   }
286
287   ResultT Result;
288 };
289
290 /// \brief SFINAE metafunction for computing whether \c ResultT provides an
291 /// \c invalidate member function.
292 template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod {
293   typedef char SmallType;
294   struct BigType { char a, b; };
295
296   template <typename T, bool (T::*)(IRUnitT *, const PreservedAnalyses &)>
297   struct Checker;
298
299   template <typename T> static SmallType f(Checker<T, &T::invalidate> *);
300   template <typename T> static BigType f(...);
301
302 public:
303   enum { Value = sizeof(f<ResultT>(0)) == sizeof(SmallType) };
304 };
305
306 /// \brief Abstract concept of an analysis pass.
307 ///
308 /// This concept is parameterized over the IR unit that it can run over and
309 /// produce an analysis result.
310 template <typename IRUnitT> struct AnalysisPassConcept {
311   virtual ~AnalysisPassConcept() {}
312   virtual AnalysisPassConcept *clone() = 0;
313
314   /// \brief Method to run this analysis over a unit of IR.
315   /// \returns The analysis result object to be queried by users, the caller
316   /// takes ownership.
317   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
318 };
319
320 /// \brief Wrapper to model the analysis pass concept.
321 ///
322 /// Can wrap any type which implements a suitable \c run method. The method
323 /// must accept the IRUnitT as an argument and produce an object which can be
324 /// wrapped in a \c AnalysisResultModel.
325 template <typename PassT>
326 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
327   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
328   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
329
330   // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
331   typedef typename PassT::IRUnitT IRUnitT;
332
333   // FIXME: Replace PassT::Result with type traits when we use C++11.
334   typedef AnalysisResultModel<
335       IRUnitT, PassT, typename PassT::Result,
336       ResultHasInvalidateMethod<IRUnitT, typename PassT::Result>::Value>
337           ResultModelT;
338
339   /// \brief The model delegates to the \c PassT::run method.
340   ///
341   /// The return is wrapped in an \c AnalysisResultModel.
342   virtual ResultModelT *run(IRUnitT *IR) {
343     return new ResultModelT(Pass.run(IR));
344   }
345
346   PassT Pass;
347 };
348
349 }
350
351 class ModuleAnalysisManager;
352
353 class ModulePassManager {
354 public:
355   explicit ModulePassManager() {}
356
357   /// \brief Run all of the module passes in this module pass manager over
358   /// a module.
359   ///
360   /// This method should only be called for a single module as there is the
361   /// expectation that the lifetime of a pass is bounded to that of a module.
362   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM = 0);
363
364   template <typename ModulePassT> void addPass(ModulePassT Pass) {
365     Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
366   }
367
368 private:
369   // Pull in the concept type and model template specialized for modules.
370   typedef detail::PassConcept<Module *, ModuleAnalysisManager> ModulePassConcept;
371   template <typename PassT>
372   struct ModulePassModel
373       : detail::PassModel<Module *, PassT, ModuleAnalysisManager> {
374     ModulePassModel(PassT Pass)
375         : detail::PassModel<Module *, PassT, ModuleAnalysisManager>(Pass) {}
376   };
377
378   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
379 };
380
381 class FunctionAnalysisManager;
382
383 class FunctionPassManager {
384 public:
385   explicit FunctionPassManager() {}
386
387   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
388     Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
389   }
390
391   PreservedAnalyses run(Function *F, FunctionAnalysisManager *AM = 0);
392
393 private:
394   // Pull in the concept type and model template specialized for functions.
395   typedef detail::PassConcept<Function *, FunctionAnalysisManager>
396       FunctionPassConcept;
397   template <typename PassT>
398   struct FunctionPassModel
399       : detail::PassModel<Function *, PassT, FunctionAnalysisManager> {
400     FunctionPassModel(PassT Pass)
401         : detail::PassModel<Function *, PassT, FunctionAnalysisManager>(Pass) {}
402   };
403
404   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
405 };
406
407 /// \brief A module analysis pass manager with lazy running and caching of
408 /// results.
409 class ModuleAnalysisManager {
410 public:
411   ModuleAnalysisManager() {}
412
413   /// \brief Get the result of an analysis pass for this module.
414   ///
415   /// If there is not a valid cached result in the manager already, this will
416   /// re-run the analysis to produce a valid result.
417   template <typename PassT> const typename PassT::Result &getResult(Module *M) {
418     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
419                        "The analysis pass must be over a Module.");
420     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
421            "This analysis pass was not registered prior to being queried");
422
423     const detail::AnalysisResultConcept<Module> &ResultConcept =
424         getResultImpl(PassT::ID(), M);
425     typedef detail::AnalysisResultModel<
426         Module, PassT, typename PassT::Result,
427         detail::ResultHasInvalidateMethod<
428             Module, typename PassT::Result>::Value> ResultModelT;
429     return static_cast<const ResultModelT &>(ResultConcept).Result;
430   }
431
432   /// \brief Register an analysis pass with the manager.
433   ///
434   /// This provides an initialized and set-up analysis pass to the
435   /// analysis
436   /// manager. Whomever is setting up analysis passes must use this to
437   /// populate
438   /// the manager with all of the analysis passes available.
439   template <typename PassT> void registerPass(PassT Pass) {
440     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
441                        "The analysis pass must be over a Module.");
442     assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
443            "Registered the same analysis pass twice!");
444     ModuleAnalysisPasses[PassT::ID()] =
445         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
446   }
447
448   /// \brief Invalidate a specific analysis pass for an IR module.
449   ///
450   /// Note that the analysis result can disregard invalidation.
451   template <typename PassT> void invalidate(Module *M) {
452     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
453                        "The analysis pass must be over a Module.");
454     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
455            "This analysis pass was not registered prior to being invalidated");
456     invalidateImpl(PassT::ID(), M);
457   }
458
459   /// \brief Invalidate analyses cached for an IR Module.
460   ///
461   /// Walk through all of the analyses pertaining to this module and invalidate
462   /// them unless they are preserved by the PreservedAnalyses set.
463   void invalidate(Module *M, const PreservedAnalyses &PA);
464
465 private:
466   /// \brief Get a module pass result, running the pass if necessary.
467   const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
468                                                              Module *M);
469
470   /// \brief Invalidate a module pass result.
471   void invalidateImpl(void *PassID, Module *M);
472
473   /// \brief Map type from module analysis pass ID to pass concept pointer.
474   typedef DenseMap<void *,
475                    polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
476       ModuleAnalysisPassMapT;
477
478   /// \brief Collection of module analysis passes, indexed by ID.
479   ModuleAnalysisPassMapT ModuleAnalysisPasses;
480
481   /// \brief Map type from module analysis pass ID to pass result concept pointer.
482   typedef DenseMap<void *,
483                    polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
484       ModuleAnalysisResultMapT;
485
486   /// \brief Cache of computed module analysis results for this module.
487   ModuleAnalysisResultMapT ModuleAnalysisResults;
488 };
489
490 /// \brief A function analysis manager to coordinate and cache analyses run over
491 /// a module.
492 class FunctionAnalysisManager {
493 public:
494   FunctionAnalysisManager() {}
495
496   /// \brief Get the result of an analysis pass for a function.
497   ///
498   /// If there is not a valid cached result in the manager already, this will
499   /// re-run the analysis to produce a valid result.
500   template <typename PassT>
501   const typename PassT::Result &getResult(Function *F) {
502     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
503                        "The analysis pass must be over a Function.");
504     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
505            "This analysis pass was not registered prior to being queried");
506
507     const detail::AnalysisResultConcept<Function> &ResultConcept =
508         getResultImpl(PassT::ID(), F);
509     typedef detail::AnalysisResultModel<
510         Function, PassT, typename PassT::Result,
511         detail::ResultHasInvalidateMethod<
512             Function, typename PassT::Result>::Value> ResultModelT;
513     return static_cast<const ResultModelT &>(ResultConcept).Result;
514   }
515
516   /// \brief Register an analysis pass with the manager.
517   ///
518   /// This provides an initialized and set-up analysis pass to the
519   /// analysis
520   /// manager. Whomever is setting up analysis passes must use this to
521   /// populate
522   /// the manager with all of the analysis passes available.
523   template <typename PassT> void registerPass(PassT Pass) {
524     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
525                        "The analysis pass must be over a Function.");
526     assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
527            "Registered the same analysis pass twice!");
528     FunctionAnalysisPasses[PassT::ID()] =
529         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
530   }
531
532   /// \brief Invalidate a specific analysis pass for an IR module.
533   ///
534   /// Note that the analysis result can disregard invalidation.
535   template <typename PassT> void invalidate(Function *F) {
536     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
537                        "The analysis pass must be over a Function.");
538     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
539            "This analysis pass was not registered prior to being invalidated");
540     invalidateImpl(PassT::ID(), F);
541   }
542
543   /// \brief Invalidate analyses cached for an IR Function.
544   ///
545   /// Walk through all of the analyses cache for this IR function and
546   /// invalidate them unless they are preserved by the provided
547   /// PreservedAnalyses set.
548   void invalidate(Function *F, const PreservedAnalyses &PA);
549
550   /// \brief Returns true if the analysis manager has an empty results cache.
551   bool empty() const;
552
553   /// \brief Clear the function analysis result cache.
554   ///
555   /// This routine allows cleaning up when the set of functions itself has
556   /// potentially changed, and thus we can't even look up a a result and
557   /// invalidate it directly. Notably, this does *not* call invalidate
558   /// functions as there is nothing to be done for them.
559   void clear();
560
561 private:
562   /// \brief Get a function pass result, running the pass if necessary.
563   const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
564                                                                Function *F);
565
566   /// \brief Invalidate a function pass result.
567   void invalidateImpl(void *PassID, Function *F);
568
569   /// \brief Map type from function analysis pass ID to pass concept pointer.
570   typedef DenseMap<void *,
571                    polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
572       FunctionAnalysisPassMapT;
573
574   /// \brief Collection of function analysis passes, indexed by ID.
575   FunctionAnalysisPassMapT FunctionAnalysisPasses;
576
577   /// \brief List of function analysis pass IDs and associated concept pointers.
578   ///
579   /// Requires iterators to be valid across appending new entries and arbitrary
580   /// erases. Provides both the pass ID and concept pointer such that it is
581   /// half of a bijection and provides storage for the actual result concept.
582   typedef std::list<std::pair<
583       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
584       FunctionAnalysisResultListT;
585
586   /// \brief Map type from function pointer to our custom list type.
587   typedef DenseMap<Function *, FunctionAnalysisResultListT>
588   FunctionAnalysisResultListMapT;
589
590   /// \brief Map from function to a list of function analysis results.
591   ///
592   /// Provides linear time removal of all analysis results for a function and
593   /// the ultimate storage for a particular cached analysis result.
594   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
595
596   /// \brief Map type from a pair of analysis ID and function pointer to an
597   /// iterator into a particular result list.
598   typedef DenseMap<std::pair<void *, Function *>,
599                    FunctionAnalysisResultListT::iterator>
600       FunctionAnalysisResultMapT;
601
602   /// \brief Map from an analysis ID and function to a particular cached
603   /// analysis result.
604   FunctionAnalysisResultMapT FunctionAnalysisResults;
605 };
606
607 /// \brief A module analysis which acts as a proxy for a function analysis
608 /// manager.
609 ///
610 /// This primarily proxies invalidation information from the module analysis
611 /// manager and module pass manager to a function analysis manager. You should
612 /// never use a function analysis manager from within (transitively) a module
613 /// pass manager unless your parent module pass has received a proxy result
614 /// object for it.
615 ///
616 /// FIXME: It might be really nice to "enforce" this (softly) by making this
617 /// proxy the API path to access a function analysis manager within a module
618 /// pass.
619 class FunctionAnalysisManagerModuleProxy {
620 public:
621   typedef Module IRUnitT;
622   class Result;
623
624   static void *ID() { return (void *)&PassID; }
625
626   FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
627
628   /// \brief Run the analysis pass and create our proxy result object.
629   ///
630   /// This doesn't do any interesting work, it is primarily used to insert our
631   /// proxy result object into the module analysis cache so that we can proxy
632   /// invalidation to the function analysis manager.
633   ///
634   /// In debug builds, it will also assert that the analysis manager is empty
635   /// as no queries should arrive at the function analysis manager prior to
636   /// this analysis being requested.
637   Result run(Module *M);
638
639 private:
640   static char PassID;
641
642   FunctionAnalysisManager &FAM;
643 };
644
645 /// \brief The result proxy object for the
646 /// \c FunctionAnalysisManagerModuleProxy.
647 ///
648 /// See its documentation for more information.
649 class FunctionAnalysisManagerModuleProxy::Result {
650 public:
651   Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
652   ~Result();
653
654   /// \brief Accessor for the \c FunctionAnalysisManager.
655   FunctionAnalysisManager &getManager() const { return FAM; }
656
657   /// \brief Handler for invalidation of the module.
658   ///
659   /// If this analysis itself is preserved, then we assume that the set of \c
660   /// Function objects in the \c Module hasn't changed and thus we don't need
661   /// to invalidate *all* cached data associated with a \c Function* in the \c
662   /// FunctionAnalysisManager.
663   ///
664   /// Regardless of whether this analysis is marked as preserved, all of the
665   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
666   /// based on the set of preserved analyses.
667   bool invalidate(Module *M, const PreservedAnalyses &PA);
668
669 private:
670   FunctionAnalysisManager &FAM;
671 };
672
673 /// \brief Trivial adaptor that maps from a module to its functions.
674 ///
675 /// Designed to allow composition of a FunctionPass(Manager) and
676 /// a ModulePassManager. Note that if this pass is constructed with a pointer
677 /// to a \c ModuleAnalysisManager it will run the
678 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
679 /// pass over the module to enable a \c FunctionAnalysisManager to be used
680 /// within this run safely.
681 template <typename FunctionPassT>
682 class ModuleToFunctionPassAdaptor {
683 public:
684   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
685       : Pass(llvm_move(Pass)) {}
686
687   /// \brief Runs the function pass across every function in the module.
688   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM) {
689     FunctionAnalysisManager *FAM = 0;
690     if (AM)
691       // Setup the function analysis manager from its proxy.
692       FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
693
694     PreservedAnalyses PA = PreservedAnalyses::all();
695     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
696       PreservedAnalyses PassPA = Pass.run(I, FAM);
697       PA.intersect(llvm_move(PassPA));
698     }
699
700     // By definition we preserve the proxy.
701     PA.preserve<FunctionAnalysisManagerModuleProxy>();
702     return PA;
703   }
704
705 private:
706   FunctionPassT Pass;
707 };
708
709 /// \brief A function to deduce a function pass type and wrap it in the
710 /// templated adaptor.
711 template <typename FunctionPassT>
712 ModuleToFunctionPassAdaptor<FunctionPassT>
713 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
714   return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass));
715 }
716
717 }