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