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