[PM] Somehow I missed the header guards on this file. Yikes!
[oota-llvm.git] / include / llvm / IR / PassManager.h
1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This header defines various interfaces for pass management in LLVM. There
12 /// is no "pass" interface in LLVM per se. Instead, an instance of any class
13 /// which supports a method to 'run' it over a unit of IR can be used as
14 /// a pass. A pass manager is generally a tool to collect a sequence of passes
15 /// which run over a particular IR construct, and run each of them in sequence
16 /// over each such construct in the containing IR construct. As there is no
17 /// containing IR construct for a Module, a manager for passes over modules
18 /// forms the base case which runs its managed passes in sequence over the
19 /// single module provided.
20 ///
21 /// The core IR library provides managers for running passes over
22 /// modules and functions.
23 ///
24 /// * FunctionPassManager can run over a Module, runs each pass over
25 ///   a Function.
26 /// * ModulePassManager must be directly run, runs each pass over the Module.
27 ///
28 /// Note that the implementations of the pass managers use concept-based
29 /// polymorphism as outlined in the "Value Semantics and Concept-based
30 /// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
31 /// Class of Evil") by Sean Parent:
32 /// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
33 /// * http://www.youtube.com/watch?v=_BpMYeUFXv8
34 /// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
35 ///
36 //===----------------------------------------------------------------------===//
37
38 #ifndef LLVM_IR_PASS_MANAGER_H
39 #define LLVM_IR_PASS_MANAGER_H
40
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/polymorphic_ptr.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/type_traits.h"
47 #include <list>
48 #include <vector>
49
50 namespace llvm {
51
52 class Module;
53 class Function;
54
55 /// \brief An abstract set of preserved analyses following a transformation pass
56 /// run.
57 ///
58 /// When a transformation pass is run, it can return a set of analyses whose
59 /// results were preserved by that transformation. The default set is "none",
60 /// and preserving analyses must be done explicitly.
61 ///
62 /// There is also an explicit all state which can be used (for example) when
63 /// the IR is not mutated at all.
64 class PreservedAnalyses {
65 public:
66   /// \brief Convenience factory function for the empty preserved set.
67   static PreservedAnalyses none() { return PreservedAnalyses(); }
68
69   /// \brief Construct a special preserved set that preserves all passes.
70   static PreservedAnalyses all() {
71     PreservedAnalyses PA;
72     PA.PreservedPassIDs.insert((void *)AllPassesID);
73     return PA;
74   }
75
76   PreservedAnalyses &operator=(PreservedAnalyses Arg) {
77     swap(Arg);
78     return *this;
79   }
80
81   void swap(PreservedAnalyses &Arg) {
82     PreservedPassIDs.swap(Arg.PreservedPassIDs);
83   }
84
85   /// \brief Mark a particular pass as preserved, adding it to the set.
86   template <typename PassT> void preserve() {
87     if (!areAllPreserved())
88       PreservedPassIDs.insert(PassT::ID());
89   }
90
91   /// \brief Intersect this set with another in place.
92   ///
93   /// This is a mutating operation on this preserved set, removing all
94   /// preserved passes which are not also preserved in the argument.
95   void intersect(const PreservedAnalyses &Arg) {
96     if (Arg.areAllPreserved())
97       return;
98     if (areAllPreserved()) {
99       PreservedPassIDs = Arg.PreservedPassIDs;
100       return;
101     }
102     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
103                                                 E = PreservedPassIDs.end();
104          I != E; ++I)
105       if (!Arg.PreservedPassIDs.count(*I))
106         PreservedPassIDs.erase(*I);
107   }
108
109 #if LLVM_HAS_RVALUE_REFERENCES
110   /// \brief Intersect this set with a temporary other set in place.
111   ///
112   /// This is a mutating operation on this preserved set, removing all
113   /// preserved passes which are not also preserved in the argument.
114   void intersect(PreservedAnalyses &&Arg) {
115     if (Arg.areAllPreserved())
116       return;
117     if (areAllPreserved()) {
118       PreservedPassIDs = std::move(Arg.PreservedPassIDs);
119       return;
120     }
121     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
122                                                 E = PreservedPassIDs.end();
123          I != E; ++I)
124       if (!Arg.PreservedPassIDs.count(*I))
125         PreservedPassIDs.erase(*I);
126   }
127 #endif
128
129   /// \brief Query whether a pass is marked as preserved by this set.
130   template <typename PassT> bool preserved() const {
131     return preserved(PassT::ID());
132   }
133
134   /// \brief Query whether an abstract pass ID is marked as preserved by this
135   /// set.
136   bool preserved(void *PassID) const {
137     return PreservedPassIDs.count((void *)AllPassesID) ||
138            PreservedPassIDs.count(PassID);
139   }
140
141 private:
142   // Note that this must not be -1 or -2 as those are already used by the
143   // SmallPtrSet.
144   static const uintptr_t AllPassesID = (intptr_t)-3;
145
146   bool areAllPreserved() const { return PreservedPassIDs.count((void *)AllPassesID); }
147
148   SmallPtrSet<void *, 2> PreservedPassIDs;
149 };
150
151 inline void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
152   LHS.swap(RHS);
153 }
154
155 /// \brief Implementation details of the pass manager interfaces.
156 namespace detail {
157
158 /// \brief Template for the abstract base class used to dispatch
159 /// polymorphically over pass objects.
160 template <typename IRUnitT, typename AnalysisManagerT> struct PassConcept {
161   // Boiler plate necessary for the container of derived classes.
162   virtual ~PassConcept() {}
163   virtual PassConcept *clone() = 0;
164
165   /// \brief The polymorphic API which runs the pass over a given IR entity.
166   ///
167   /// Note that actual pass object can omit the analysis manager argument if
168   /// desired. Also that the analysis manager may be null if there is no
169   /// analysis manager in the pass pipeline.
170   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) = 0;
171 };
172
173 /// \brief SFINAE metafunction for computing whether \c PassT has a run method
174 /// accepting an \c AnalysisManagerT.
175 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
176           typename ResultT>
177 class PassRunAcceptsAnalysisManager {
178   typedef char SmallType;
179   struct BigType { char a, b; };
180
181   template <typename T, ResultT (T::*)(IRUnitT, AnalysisManagerT *)>
182   struct Checker;
183
184   template <typename T> static SmallType f(Checker<T, &T::run> *);
185   template <typename T> static BigType f(...);
186
187 public:
188   enum { Value = sizeof(f<PassT>(0)) == sizeof(SmallType) };
189 };
190
191 /// \brief A template wrapper used to implement the polymorphic API.
192 ///
193 /// Can be instantiated for any object which provides a \c run method accepting
194 /// an \c IRUnitT. It requires the pass to be a copyable object. When the
195 /// \c run method also accepts an \c AnalysisManagerT*, we pass it along.
196 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
197           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
198               IRUnitT, AnalysisManagerT, PassT, PreservedAnalyses>::Value>
199 struct PassModel;
200
201 /// \brief Specialization of \c PassModel for passes that accept an analyis
202 /// manager.
203 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
204 struct PassModel<IRUnitT, AnalysisManagerT, PassT,
205                  true> : PassConcept<IRUnitT, AnalysisManagerT> {
206   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
207   virtual PassModel *clone() { return new PassModel(Pass); }
208   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
209     return Pass.run(IR, AM);
210   }
211   PassT Pass;
212 };
213
214 /// \brief Specialization of \c PassModel for passes that accept an analyis
215 /// manager.
216 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
217 struct PassModel<IRUnitT, AnalysisManagerT, PassT,
218                  false> : PassConcept<IRUnitT, AnalysisManagerT> {
219   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
220   virtual PassModel *clone() { return new PassModel(Pass); }
221   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
222     return Pass.run(IR);
223   }
224   PassT Pass;
225 };
226
227 /// \brief Abstract concept of an analysis result.
228 ///
229 /// This concept is parameterized over the IR unit that this result pertains
230 /// to.
231 template <typename IRUnitT> struct AnalysisResultConcept {
232   virtual ~AnalysisResultConcept() {}
233   virtual AnalysisResultConcept *clone() = 0;
234
235   /// \brief Method to try and mark a result as invalid.
236   ///
237   /// When the outer analysis manager detects a change in some underlying
238   /// unit of the IR, it will call this method on all of the results cached.
239   ///
240   /// This method also receives a set of preserved analyses which can be used
241   /// to avoid invalidation because the pass which changed the underlying IR
242   /// took care to update or preserve the analysis result in some way.
243   ///
244   /// \returns true if the result is indeed invalid (the default).
245   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) = 0;
246 };
247
248 /// \brief SFINAE metafunction for computing whether \c ResultT provides an
249 /// \c invalidate member function.
250 template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod {
251   typedef char SmallType;
252   struct BigType { char a, b; };
253
254   template <typename T, bool (T::*)(IRUnitT, const PreservedAnalyses &)>
255   struct Checker;
256
257   template <typename T> static SmallType f(Checker<T, &T::invalidate> *);
258   template <typename T> static BigType f(...);
259
260 public:
261   enum { Value = sizeof(f<ResultT>(0)) == sizeof(SmallType) };
262 };
263
264 /// \brief Wrapper to model the analysis result concept.
265 ///
266 /// By default, this will implement the invalidate method with a trivial
267 /// implementation so that the actual analysis result doesn't need to provide
268 /// an invalidation handler. It is only selected when the invalidation handler
269 /// is not part of the ResultT's interface.
270 template <typename IRUnitT, typename PassT, typename ResultT,
271           bool HasInvalidateHandler =
272               ResultHasInvalidateMethod<IRUnitT, ResultT>::Value>
273 struct AnalysisResultModel;
274
275 /// \brief Specialization of \c AnalysisResultModel which provides the default
276 /// invalidate functionality.
277 template <typename IRUnitT, typename PassT, typename ResultT>
278 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
279                            false> : AnalysisResultConcept<IRUnitT> {
280   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
281   virtual AnalysisResultModel *clone() {
282     return new AnalysisResultModel(Result);
283   }
284
285   /// \brief The model bases invalidation solely on being in the preserved set.
286   //
287   // FIXME: We should actually use two different concepts for analysis results
288   // rather than two different models, and avoid the indirect function call for
289   // ones that use the trivial behavior.
290   virtual bool invalidate(IRUnitT, const PreservedAnalyses &PA) {
291     return !PA.preserved(PassT::ID());
292   }
293
294   ResultT Result;
295 };
296
297 /// \brief Specialization of \c AnalysisResultModel which delegates invalidate
298 /// handling to \c ResultT.
299 template <typename IRUnitT, typename PassT, typename ResultT>
300 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
301                            true> : AnalysisResultConcept<IRUnitT> {
302   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
303   virtual AnalysisResultModel *clone() {
304     return new AnalysisResultModel(Result);
305   }
306
307   /// \brief The model delegates to the \c ResultT method.
308   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
309     return Result.invalidate(IR, PA);
310   }
311
312   ResultT Result;
313 };
314
315 /// \brief Abstract concept of an analysis pass.
316 ///
317 /// This concept is parameterized over the IR unit that it can run over and
318 /// produce an analysis result.
319 template <typename IRUnitT, typename AnalysisManagerT>
320 struct AnalysisPassConcept {
321   virtual ~AnalysisPassConcept() {}
322   virtual AnalysisPassConcept *clone() = 0;
323
324   /// \brief Method to run this analysis over a unit of IR.
325   /// \returns The analysis result object to be queried by users, the caller
326   /// takes ownership.
327   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT IR,
328                                               AnalysisManagerT *AM) = 0;
329 };
330
331 /// \brief Wrapper to model the analysis pass concept.
332 ///
333 /// Can wrap any type which implements a suitable \c run method. The method
334 /// must accept the IRUnitT as an argument and produce an object which can be
335 /// wrapped in a \c AnalysisResultModel.
336 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
337           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
338               IRUnitT, AnalysisManagerT, PassT,
339               typename PassT::Result>::Value> struct AnalysisPassModel;
340
341 /// \brief Specialization of \c AnalysisPassModel which passes an
342 /// \c AnalysisManager to PassT's run method.
343 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
344 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT,
345                          true> : AnalysisPassConcept<IRUnitT,
346                                                      AnalysisManagerT> {
347   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
348   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
349
350   // FIXME: Replace PassT::Result with type traits when we use C++11.
351   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
352       ResultModelT;
353
354   /// \brief The model delegates to the \c PassT::run method.
355   ///
356   /// The return is wrapped in an \c AnalysisResultModel.
357   virtual ResultModelT *run(IRUnitT IR, AnalysisManagerT *AM) {
358     return new ResultModelT(Pass.run(IR, AM));
359   }
360
361   PassT Pass;
362 };
363
364 /// \brief Specialization of \c AnalysisPassModel which does not pass an
365 /// \c AnalysisManager to PassT's run method.
366 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
367 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT,
368                          false> : AnalysisPassConcept<IRUnitT,
369                                                      AnalysisManagerT> {
370   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
371   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
372
373   // FIXME: Replace PassT::Result with type traits when we use C++11.
374   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
375       ResultModelT;
376
377   /// \brief The model delegates to the \c PassT::run method.
378   ///
379   /// The return is wrapped in an \c AnalysisResultModel.
380   virtual ResultModelT *run(IRUnitT IR, AnalysisManagerT *) {
381     return new ResultModelT(Pass.run(IR));
382   }
383
384   PassT Pass;
385 };
386
387 }
388
389 class ModuleAnalysisManager;
390
391 class ModulePassManager {
392 public:
393   explicit ModulePassManager() {}
394
395   /// \brief Run all of the module passes in this module pass manager over
396   /// a module.
397   ///
398   /// This method should only be called for a single module as there is the
399   /// expectation that the lifetime of a pass is bounded to that of a module.
400   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM = 0);
401
402   template <typename ModulePassT> void addPass(ModulePassT Pass) {
403     Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
404   }
405
406 private:
407   // Pull in the concept type and model template specialized for modules.
408   typedef detail::PassConcept<Module *, ModuleAnalysisManager> ModulePassConcept;
409   template <typename PassT>
410   struct ModulePassModel
411       : detail::PassModel<Module *, ModuleAnalysisManager, PassT> {
412     ModulePassModel(PassT Pass)
413         : detail::PassModel<Module *, ModuleAnalysisManager, PassT>(Pass) {}
414   };
415
416   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
417 };
418
419 class FunctionAnalysisManager;
420
421 class FunctionPassManager {
422 public:
423   explicit FunctionPassManager() {}
424
425   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
426     Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
427   }
428
429   PreservedAnalyses run(Function *F, FunctionAnalysisManager *AM = 0);
430
431 private:
432   // Pull in the concept type and model template specialized for functions.
433   typedef detail::PassConcept<Function *, FunctionAnalysisManager>
434       FunctionPassConcept;
435   template <typename PassT>
436   struct FunctionPassModel
437       : detail::PassModel<Function *, FunctionAnalysisManager, PassT> {
438     FunctionPassModel(PassT Pass)
439         : detail::PassModel<Function *, FunctionAnalysisManager, PassT>(Pass) {}
440   };
441
442   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
443 };
444
445 namespace detail {
446
447 /// \brief A CRTP base used to implement analysis managers.
448 ///
449 /// This class template serves as the boiler plate of an analysis manager. Any
450 /// analysis manager can be implemented on top of this base class. Any
451 /// implementation will be required to provide specific hooks:
452 ///
453 /// - getResultImpl
454 /// - getCachedResultImpl
455 /// - invalidateImpl
456 ///
457 /// The details of the call pattern are within.
458 template <typename DerivedT, typename IRUnitT>
459 class AnalysisManagerBase {
460   DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
461   const DerivedT *derived_this() const { return static_cast<const DerivedT *>(this); }
462
463 protected:
464   typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
465   typedef detail::AnalysisPassConcept<IRUnitT, DerivedT> PassConceptT;
466
467   // FIXME: Provide template aliases for the models when we're using C++11 in
468   // a mode supporting them.
469
470 public:
471   /// \brief Get the result of an analysis pass for this module.
472   ///
473   /// If there is not a valid cached result in the manager already, this will
474   /// re-run the analysis to produce a valid result.
475   template <typename PassT> const typename PassT::Result &getResult(IRUnitT IR) {
476     assert(AnalysisPasses.count(PassT::ID()) &&
477            "This analysis pass was not registered prior to being queried");
478
479     const ResultConceptT &ResultConcept =
480         derived_this()->getResultImpl(PassT::ID(), IR);
481     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
482         ResultModelT;
483     return static_cast<const ResultModelT &>(ResultConcept).Result;
484   }
485
486   /// \brief Get the cached result of an analysis pass for this module.
487   ///
488   /// This method never runs the analysis.
489   ///
490   /// \returns null if there is no cached result.
491   template <typename PassT>
492   const typename PassT::Result *getCachedResult(IRUnitT IR) const {
493     assert(AnalysisPasses.count(PassT::ID()) &&
494            "This analysis pass was not registered prior to being queried");
495
496     const ResultConceptT *ResultConcept =
497         derived_this()->getCachedResultImpl(PassT::ID(), IR);
498     if (!ResultConcept)
499       return 0;
500
501     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
502         ResultModelT;
503     return &static_cast<const ResultModelT *>(ResultConcept)->Result;
504   }
505
506   /// \brief Register an analysis pass with the manager.
507   ///
508   /// This provides an initialized and set-up analysis pass to the analysis
509   /// manager. Whomever is setting up analysis passes must use this to populate
510   /// the manager with all of the analysis passes available.
511   template <typename PassT> void registerPass(PassT Pass) {
512     assert(!AnalysisPasses.count(PassT::ID()) &&
513            "Registered the same analysis pass twice!");
514     typedef detail::AnalysisPassModel<IRUnitT, DerivedT, PassT> PassModelT;
515     AnalysisPasses[PassT::ID()] = new PassModelT(llvm_move(Pass));
516   }
517
518   /// \brief Invalidate a specific analysis pass for an IR module.
519   ///
520   /// Note that the analysis result can disregard invalidation.
521   template <typename PassT> void invalidate(Module *M) {
522     assert(AnalysisPasses.count(PassT::ID()) &&
523            "This analysis pass was not registered prior to being invalidated");
524     derived_this()->invalidateImpl(PassT::ID(), M);
525   }
526
527   /// \brief Invalidate analyses cached for an IR unit.
528   ///
529   /// Walk through all of the analyses pertaining to this unit of IR and
530   /// invalidate them unless they are preserved by the PreservedAnalyses set.
531   void invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
532     derived_this()->invalidateImpl(IR, PA);
533   }
534
535 protected:
536   /// \brief Lookup a registered analysis pass.
537   PassConceptT &lookupPass(void *PassID) {
538     typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
539     assert(PI != AnalysisPasses.end() &&
540            "Analysis passes must be registered prior to being queried!");
541     return *PI->second;
542   }
543
544   /// \brief Lookup a registered analysis pass.
545   const PassConceptT &lookupPass(void *PassID) const {
546     typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
547     assert(PI != AnalysisPasses.end() &&
548            "Analysis passes must be registered prior to being queried!");
549     return *PI->second;
550   }
551
552 private:
553   /// \brief Map type from module analysis pass ID to pass concept pointer.
554   typedef DenseMap<void *, polymorphic_ptr<PassConceptT> > AnalysisPassMapT;
555
556   /// \brief Collection of module analysis passes, indexed by ID.
557   AnalysisPassMapT AnalysisPasses;
558 };
559
560 }
561
562 /// \brief A module analysis pass manager with lazy running and caching of
563 /// results.
564 class ModuleAnalysisManager
565     : public detail::AnalysisManagerBase<ModuleAnalysisManager, Module *> {
566   friend class detail::AnalysisManagerBase<ModuleAnalysisManager, Module *>;
567   typedef detail::AnalysisManagerBase<ModuleAnalysisManager, Module *> BaseT;
568   typedef BaseT::ResultConceptT ResultConceptT;
569   typedef BaseT::PassConceptT PassConceptT;
570
571 public:
572   // Public methods provided by the base class.
573
574 private:
575   /// \brief Get a module pass result, running the pass if necessary.
576   const ResultConceptT &getResultImpl(void *PassID, Module *M);
577
578   /// \brief Get a cached module pass result or return null.
579   const ResultConceptT *getCachedResultImpl(void *PassID, Module *M) const;
580
581   /// \brief Invalidate a module pass result.
582   void invalidateImpl(void *PassID, Module *M);
583
584   /// \brief Invalidate results across a module.
585   void invalidateImpl(Module *M, const PreservedAnalyses &PA);
586
587   /// \brief Map type from module analysis pass ID to pass result concept pointer.
588   typedef DenseMap<void *,
589                    polymorphic_ptr<detail::AnalysisResultConcept<Module *> > >
590       ModuleAnalysisResultMapT;
591
592   /// \brief Cache of computed module analysis results for this module.
593   ModuleAnalysisResultMapT ModuleAnalysisResults;
594 };
595
596 /// \brief A function analysis manager to coordinate and cache analyses run over
597 /// a module.
598 class FunctionAnalysisManager
599     : public detail::AnalysisManagerBase<FunctionAnalysisManager, Function *> {
600   friend class detail::AnalysisManagerBase<FunctionAnalysisManager, Function *>;
601   typedef detail::AnalysisManagerBase<FunctionAnalysisManager, Function *> BaseT;
602   typedef BaseT::ResultConceptT ResultConceptT;
603   typedef BaseT::PassConceptT PassConceptT;
604
605 public:
606   // Most public APIs are inherited from the CRTP base class.
607
608   /// \brief Returns true if the analysis manager has an empty results cache.
609   bool empty() const;
610
611   /// \brief Clear the function analysis result cache.
612   ///
613   /// This routine allows cleaning up when the set of functions itself has
614   /// potentially changed, and thus we can't even look up a a result and
615   /// invalidate it directly. Notably, this does *not* call invalidate
616   /// functions as there is nothing to be done for them.
617   void clear();
618
619 private:
620   /// \brief Get a function pass result, running the pass if necessary.
621   const ResultConceptT &getResultImpl(void *PassID, Function *F);
622
623   /// \brief Get a cached function pass result or return null.
624   const ResultConceptT *getCachedResultImpl(void *PassID, Function *F) const;
625
626   /// \brief Invalidate a function pass result.
627   void invalidateImpl(void *PassID, Function *F);
628
629   /// \brief Invalidate the results for a function..
630   void invalidateImpl(Function *F, const PreservedAnalyses &PA);
631
632   /// \brief List of function analysis pass IDs and associated concept pointers.
633   ///
634   /// Requires iterators to be valid across appending new entries and arbitrary
635   /// erases. Provides both the pass ID and concept pointer such that it is
636   /// half of a bijection and provides storage for the actual result concept.
637   typedef std::list<std::pair<
638       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function *> > > >
639       FunctionAnalysisResultListT;
640
641   /// \brief Map type from function pointer to our custom list type.
642   typedef DenseMap<Function *, FunctionAnalysisResultListT>
643   FunctionAnalysisResultListMapT;
644
645   /// \brief Map from function to a list of function analysis results.
646   ///
647   /// Provides linear time removal of all analysis results for a function and
648   /// the ultimate storage for a particular cached analysis result.
649   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
650
651   /// \brief Map type from a pair of analysis ID and function pointer to an
652   /// iterator into a particular result list.
653   typedef DenseMap<std::pair<void *, Function *>,
654                    FunctionAnalysisResultListT::iterator>
655       FunctionAnalysisResultMapT;
656
657   /// \brief Map from an analysis ID and function to a particular cached
658   /// analysis result.
659   FunctionAnalysisResultMapT FunctionAnalysisResults;
660 };
661
662 /// \brief A module analysis which acts as a proxy for a function analysis
663 /// manager.
664 ///
665 /// This primarily proxies invalidation information from the module analysis
666 /// manager and module pass manager to a function analysis manager. You should
667 /// never use a function analysis manager from within (transitively) a module
668 /// pass manager unless your parent module pass has received a proxy result
669 /// object for it.
670 class FunctionAnalysisManagerModuleProxy {
671 public:
672   class Result;
673
674   static void *ID() { return (void *)&PassID; }
675
676   FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
677
678   /// \brief Run the analysis pass and create our proxy result object.
679   ///
680   /// This doesn't do any interesting work, it is primarily used to insert our
681   /// proxy result object into the module analysis cache so that we can proxy
682   /// invalidation to the function analysis manager.
683   ///
684   /// In debug builds, it will also assert that the analysis manager is empty
685   /// as no queries should arrive at the function analysis manager prior to
686   /// this analysis being requested.
687   Result run(Module *M);
688
689 private:
690   static char PassID;
691
692   FunctionAnalysisManager &FAM;
693 };
694
695 /// \brief The result proxy object for the
696 /// \c FunctionAnalysisManagerModuleProxy.
697 ///
698 /// See its documentation for more information.
699 class FunctionAnalysisManagerModuleProxy::Result {
700 public:
701   Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
702   ~Result();
703
704   /// \brief Accessor for the \c FunctionAnalysisManager.
705   FunctionAnalysisManager &getManager() const { return FAM; }
706
707   /// \brief Handler for invalidation of the module.
708   ///
709   /// If this analysis itself is preserved, then we assume that the set of \c
710   /// Function objects in the \c Module hasn't changed and thus we don't need
711   /// to invalidate *all* cached data associated with a \c Function* in the \c
712   /// FunctionAnalysisManager.
713   ///
714   /// Regardless of whether this analysis is marked as preserved, all of the
715   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
716   /// based on the set of preserved analyses.
717   bool invalidate(Module *M, const PreservedAnalyses &PA);
718
719 private:
720   FunctionAnalysisManager &FAM;
721 };
722
723 /// \brief A function analysis which acts as a proxy for a module analysis
724 /// manager.
725 ///
726 /// This primarily provides an accessor to a parent module analysis manager to
727 /// function passes. Only the const interface of the module analysis manager is
728 /// provided to indicate that once inside of a function analysis pass you
729 /// cannot request a module analysis to actually run. Instead, the user must
730 /// rely on the \c getCachedResult API.
731 ///
732 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
733 /// the recursive return path of each layer of the pass manager and the
734 /// returned PreservedAnalysis set.
735 class ModuleAnalysisManagerFunctionProxy {
736 public:
737   /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
738   class Result {
739   public:
740     Result(const ModuleAnalysisManager &MAM) : MAM(MAM) {}
741
742     const ModuleAnalysisManager &getManager() const { return MAM; }
743
744     /// \brief Handle invalidation by ignoring it, this pass is immutable.
745     bool invalidate(Function *) { return false; }
746
747   private:
748     const ModuleAnalysisManager &MAM;
749   };
750
751   static void *ID() { return (void *)&PassID; }
752
753   ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
754       : MAM(MAM) {}
755
756   /// \brief Run the analysis pass and create our proxy result object.
757   /// Nothing to see here, it just forwards the \c MAM reference into the
758   /// result.
759   Result run(Function *) { return Result(MAM); }
760
761 private:
762   static char PassID;
763
764   const ModuleAnalysisManager &MAM;
765 };
766
767 /// \brief Trivial adaptor that maps from a module to its functions.
768 ///
769 /// Designed to allow composition of a FunctionPass(Manager) and
770 /// a ModulePassManager. Note that if this pass is constructed with a pointer
771 /// to a \c ModuleAnalysisManager it will run the
772 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
773 /// pass over the module to enable a \c FunctionAnalysisManager to be used
774 /// within this run safely.
775 template <typename FunctionPassT>
776 class ModuleToFunctionPassAdaptor {
777 public:
778   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
779       : Pass(llvm_move(Pass)) {}
780
781   /// \brief Runs the function pass across every function in the module.
782   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM) {
783     FunctionAnalysisManager *FAM = 0;
784     if (AM)
785       // Setup the function analysis manager from its proxy.
786       FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
787
788     PreservedAnalyses PA = PreservedAnalyses::all();
789     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
790       PreservedAnalyses PassPA = Pass.run(I, FAM);
791
792       // We know that the function pass couldn't have invalidated any other
793       // function's analyses (that's the contract of a function pass), so
794       // directly handle the function analysis manager's invalidation here.
795       if (FAM)
796         FAM->invalidate(I, PassPA);
797
798       // Then intersect the preserved set so that invalidation of module
799       // analyses will eventually occur when the module pass completes.
800       PA.intersect(llvm_move(PassPA));
801     }
802
803     // By definition we preserve the proxy. This precludes *any* invalidation
804     // of function analyses by the proxy, but that's OK because we've taken
805     // care to invalidate analyses in the function analysis manager
806     // incrementally above.
807     PA.preserve<FunctionAnalysisManagerModuleProxy>();
808     return PA;
809   }
810
811 private:
812   FunctionPassT Pass;
813 };
814
815 /// \brief A function to deduce a function pass type and wrap it in the
816 /// templated adaptor.
817 template <typename FunctionPassT>
818 ModuleToFunctionPassAdaptor<FunctionPassT>
819 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
820   return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass));
821 }
822
823 }
824
825 #endif