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