1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
21 /// The core IR library provides managers for running passes over
22 /// modules and functions.
24 /// * FunctionPassManager can run over a Module, runs each pass over
26 /// * ModulePassManager must be directly run, runs each pass over the Module.
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
36 //===----------------------------------------------------------------------===//
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/polymorphic_ptr.h"
41 #include "llvm/Support/type_traits.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Module.h"
52 /// \brief An abstract set of preserved analyses following a transformation pass
55 /// When a transformation pass is run, it can return a set of analyses whose
56 /// results were preserved by that transformation. The default set is "none",
57 /// and preserving analyses must be done explicitly.
59 /// There is also an explicit all state which can be used (for example) when
60 /// the IR is not mutated at all.
61 class PreservedAnalyses {
63 /// \brief Convenience factory function for the empty preserved set.
64 static PreservedAnalyses none() { return PreservedAnalyses(); }
66 /// \brief Construct a special preserved set that preserves all passes.
67 static PreservedAnalyses all() {
69 PA.PreservedPassIDs.insert((void *)AllPassesID);
73 PreservedAnalyses &operator=(PreservedAnalyses Arg) {
78 void swap(PreservedAnalyses &Arg) {
79 PreservedPassIDs.swap(Arg.PreservedPassIDs);
82 /// \brief Mark a particular pass as preserved, adding it to the set.
83 template <typename PassT> void preserve() {
84 if (!areAllPreserved())
85 PreservedPassIDs.insert(PassT::ID());
88 /// \brief Intersect this set with another in place.
90 /// This is a mutating operation on this preserved set, removing all
91 /// preserved passes which are not also preserved in the argument.
92 void intersect(const PreservedAnalyses &Arg) {
93 if (Arg.areAllPreserved())
95 if (areAllPreserved()) {
96 PreservedPassIDs = Arg.PreservedPassIDs;
99 for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
100 E = PreservedPassIDs.end();
102 if (!Arg.PreservedPassIDs.count(*I))
103 PreservedPassIDs.erase(*I);
106 #if LLVM_HAS_RVALUE_REFERENCES
107 /// \brief Intersect this set with a temporary other set in place.
109 /// This is a mutating operation on this preserved set, removing all
110 /// preserved passes which are not also preserved in the argument.
111 void intersect(PreservedAnalyses &&Arg) {
112 if (Arg.areAllPreserved())
114 if (areAllPreserved()) {
115 PreservedPassIDs = std::move(Arg.PreservedPassIDs);
118 for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
119 E = PreservedPassIDs.end();
121 if (!Arg.PreservedPassIDs.count(*I))
122 PreservedPassIDs.erase(*I);
126 /// \brief Query whether a pass is marked as preserved by this set.
127 template <typename PassT> bool preserved() const {
128 return preserved(PassT::ID());
131 /// \brief Query whether an abstract pass ID is marked as preserved by this
133 bool preserved(void *PassID) const {
134 return PreservedPassIDs.count((void *)AllPassesID) ||
135 PreservedPassIDs.count(PassID);
139 // Note that this must not be -1 or -2 as those are already used by the
141 static const uintptr_t AllPassesID = (intptr_t)-3;
143 bool areAllPreserved() const { return PreservedPassIDs.count((void *)AllPassesID); }
145 SmallPtrSet<void *, 2> PreservedPassIDs;
148 inline void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
152 /// \brief Implementation details of the pass manager interfaces.
155 /// \brief Template for the abstract base class used to dispatch
156 /// polymorphically over pass objects.
157 template <typename T> struct PassConcept {
158 // Boiler plate necessary for the container of derived classes.
159 virtual ~PassConcept() {}
160 virtual PassConcept *clone() = 0;
162 /// \brief The polymorphic API which runs the pass over a given IR entity.
163 virtual PreservedAnalyses run(T Arg) = 0;
166 /// \brief A template wrapper used to implement the polymorphic API.
168 /// Can be instantiated for any object which provides a \c run method
169 /// accepting a \c T. It requires the pass to be a copyable
171 template <typename T, typename PassT> struct PassModel : PassConcept<T> {
172 PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
173 virtual PassModel *clone() { return new PassModel(Pass); }
174 virtual PreservedAnalyses run(T Arg) { return Pass.run(Arg); }
178 /// \brief Abstract concept of an analysis result.
180 /// This concept is parameterized over the IR unit that this result pertains
182 template <typename IRUnitT> struct AnalysisResultConcept {
183 virtual ~AnalysisResultConcept() {}
184 virtual AnalysisResultConcept *clone() = 0;
186 /// \brief Method to try and mark a result as invalid.
188 /// When the outer \c AnalysisManager detects a change in some underlying
189 /// unit of the IR, it will call this method on all of the results cached.
191 /// \returns true if the result should indeed be invalidated (the default).
192 virtual bool invalidate(IRUnitT *IR) = 0;
195 /// \brief Wrapper to model the analysis result concept.
197 /// Can wrap any type which implements a suitable invalidate member and model
198 /// the AnalysisResultConcept for the AnalysisManager.
199 template <typename IRUnitT, typename ResultT>
200 struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
201 AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
202 virtual AnalysisResultModel *clone() {
203 return new AnalysisResultModel(Result);
206 /// \brief The model delegates to the \c ResultT method.
207 virtual bool invalidate(IRUnitT *IR) { return Result.invalidate(IR); }
212 /// \brief Abstract concept of an analysis pass.
214 /// This concept is parameterized over the IR unit that it can run over and
215 /// produce an analysis result.
216 template <typename IRUnitT> struct AnalysisPassConcept {
217 virtual ~AnalysisPassConcept() {}
218 virtual AnalysisPassConcept *clone() = 0;
220 /// \brief Method to run this analysis over a unit of IR.
221 /// \returns The analysis result object to be queried by users, the caller
223 virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
226 /// \brief Wrapper to model the analysis pass concept.
228 /// Can wrap any type which implements a suitable \c run method. The method
229 /// must accept the IRUnitT as an argument and produce an object which can be
230 /// wrapped in a \c AnalysisResultModel.
231 template <typename PassT>
232 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
233 AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
234 virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
236 // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
237 typedef typename PassT::IRUnitT IRUnitT;
239 // FIXME: Replace PassT::Result with type traits when we use C++11.
240 typedef AnalysisResultModel<IRUnitT, typename PassT::Result> ResultModelT;
242 /// \brief The model delegates to the \c PassT::run method.
244 /// The return is wrapped in an \c AnalysisResultModel.
245 virtual ResultModelT *run(IRUnitT *IR) {
246 return new ResultModelT(Pass.run(IR));
254 class ModuleAnalysisManager;
256 class ModulePassManager {
258 explicit ModulePassManager(ModuleAnalysisManager *AM = 0) : AM(AM) {}
260 /// \brief Run all of the module passes in this module pass manager over
263 /// This method should only be called for a single module as there is the
264 /// expectation that the lifetime of a pass is bounded to that of a module.
265 PreservedAnalyses run(Module *M);
267 template <typename ModulePassT> void addPass(ModulePassT Pass) {
268 Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
272 // Pull in the concept type and model template specialized for modules.
273 typedef detail::PassConcept<Module *> ModulePassConcept;
274 template <typename PassT>
275 struct ModulePassModel : detail::PassModel<Module *, PassT> {
276 ModulePassModel(PassT Pass) : detail::PassModel<Module *, PassT>(Pass) {}
279 ModuleAnalysisManager *AM;
280 std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
283 class FunctionAnalysisManager;
285 class FunctionPassManager {
287 explicit FunctionPassManager(FunctionAnalysisManager *AM = 0) : AM(AM) {}
289 template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
290 Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
293 PreservedAnalyses run(Function *F);
296 // Pull in the concept type and model template specialized for functions.
297 typedef detail::PassConcept<Function *> FunctionPassConcept;
298 template <typename PassT>
299 struct FunctionPassModel : detail::PassModel<Function *, PassT> {
300 FunctionPassModel(PassT Pass)
301 : detail::PassModel<Function *, PassT>(Pass) {}
304 FunctionAnalysisManager *AM;
305 std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
308 /// \brief Trivial adaptor that maps from a module to its functions.
310 /// Designed to allow composition of a FunctionPass(Manager) and a
311 /// ModulePassManager.
312 template <typename FunctionPassT>
313 class ModuleToFunctionPassAdaptor {
315 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
316 : Pass(llvm_move(Pass)) {}
318 /// \brief Runs the function pass across every function in the module.
319 PreservedAnalyses run(Module *M) {
320 PreservedAnalyses PA = PreservedAnalyses::all();
321 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
322 PreservedAnalyses PassPA = Pass.run(I);
323 PA.intersect(llvm_move(PassPA));
332 /// \brief A function to deduce a function pass type and wrap it in the
333 /// templated adaptor.
334 template <typename FunctionPassT>
335 ModuleToFunctionPassAdaptor<FunctionPassT>
336 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
337 return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass));
340 /// \brief A module analysis pass manager with lazy running and caching of
342 class ModuleAnalysisManager {
344 ModuleAnalysisManager() {}
346 /// \brief Get the result of an analysis pass for this module.
348 /// If there is not a valid cached result in the manager already, this will
349 /// re-run the analysis to produce a valid result.
350 template <typename PassT> const typename PassT::Result &getResult(Module *M) {
351 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
352 "The analysis pass must be over a Module.");
353 assert(ModuleAnalysisPasses.count(PassT::ID()) &&
354 "This analysis pass was not registered prior to being queried");
356 const detail::AnalysisResultConcept<Module> &ResultConcept =
357 getResultImpl(PassT::ID(), M);
358 typedef detail::AnalysisResultModel<Module, typename PassT::Result>
360 return static_cast<const ResultModelT &>(ResultConcept).Result;
363 /// \brief Register an analysis pass with the manager.
365 /// This provides an initialized and set-up analysis pass to the
367 /// manager. Whomever is setting up analysis passes must use this to
369 /// the manager with all of the analysis passes available.
370 template <typename PassT> void registerPass(PassT Pass) {
371 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
372 "The analysis pass must be over a Module.");
373 assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
374 "Registered the same analysis pass twice!");
375 ModuleAnalysisPasses[PassT::ID()] =
376 new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
379 /// \brief Invalidate a specific analysis pass for an IR module.
381 /// Note that the analysis result can disregard invalidation.
382 template <typename PassT> void invalidate(Module *M) {
383 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
384 "The analysis pass must be over a Module.");
385 assert(ModuleAnalysisPasses.count(PassT::ID()) &&
386 "This analysis pass was not registered prior to being invalidated");
387 invalidateImpl(PassT::ID(), M);
390 /// \brief Invalidate analyses cached for an IR Module.
392 /// Walk through all of the analyses pertaining to this module and invalidate
393 /// them unless they are preserved by the PreservedAnalyses set.
394 void invalidate(Module *M, const PreservedAnalyses &PA);
397 /// \brief Get a module pass result, running the pass if necessary.
398 const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
401 /// \brief Invalidate a module pass result.
402 void invalidateImpl(void *PassID, Module *M);
404 /// \brief Map type from module analysis pass ID to pass concept pointer.
405 typedef DenseMap<void *,
406 polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
407 ModuleAnalysisPassMapT;
409 /// \brief Collection of module analysis passes, indexed by ID.
410 ModuleAnalysisPassMapT ModuleAnalysisPasses;
412 /// \brief Map type from module analysis pass ID to pass result concept pointer.
413 typedef DenseMap<void *,
414 polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
415 ModuleAnalysisResultMapT;
417 /// \brief Cache of computed module analysis results for this module.
418 ModuleAnalysisResultMapT ModuleAnalysisResults;
421 /// \brief A function analysis manager to coordinate and cache analyses run over
423 class FunctionAnalysisManager {
425 FunctionAnalysisManager() {}
427 /// \brief Get the result of an analysis pass for a function.
429 /// If there is not a valid cached result in the manager already, this will
430 /// re-run the analysis to produce a valid result.
431 template <typename PassT>
432 const typename PassT::Result &getResult(Function *F) {
433 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
434 "The analysis pass must be over a Function.");
435 assert(FunctionAnalysisPasses.count(PassT::ID()) &&
436 "This analysis pass was not registered prior to being queried");
438 const detail::AnalysisResultConcept<Function> &ResultConcept =
439 getResultImpl(PassT::ID(), F);
440 typedef detail::AnalysisResultModel<Function, typename PassT::Result>
442 return static_cast<const ResultModelT &>(ResultConcept).Result;
445 /// \brief Register an analysis pass with the manager.
447 /// This provides an initialized and set-up analysis pass to the
449 /// manager. Whomever is setting up analysis passes must use this to
451 /// the manager with all of the analysis passes available.
452 template <typename PassT> void registerPass(PassT Pass) {
453 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
454 "The analysis pass must be over a Function.");
455 assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
456 "Registered the same analysis pass twice!");
457 FunctionAnalysisPasses[PassT::ID()] =
458 new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
461 /// \brief Invalidate a specific analysis pass for an IR module.
463 /// Note that the analysis result can disregard invalidation.
464 template <typename PassT> void invalidate(Function *F) {
465 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
466 "The analysis pass must be over a Function.");
467 assert(FunctionAnalysisPasses.count(PassT::ID()) &&
468 "This analysis pass was not registered prior to being invalidated");
469 invalidateImpl(PassT::ID(), F);
472 /// \brief Invalidate analyses cached for an IR Function.
474 /// Walk through all of the analyses cache for this IR function and
475 /// invalidate them unless they are preserved by the provided
476 /// PreservedAnalyses set.
477 void invalidate(Function *F, const PreservedAnalyses &PA);
480 /// \brief Get a function pass result, running the pass if necessary.
481 const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
484 /// \brief Invalidate a function pass result.
485 void invalidateImpl(void *PassID, Function *F);
487 /// \brief Map type from function analysis pass ID to pass concept pointer.
488 typedef DenseMap<void *,
489 polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
490 FunctionAnalysisPassMapT;
492 /// \brief Collection of function analysis passes, indexed by ID.
493 FunctionAnalysisPassMapT FunctionAnalysisPasses;
495 /// \brief List of function analysis pass IDs and associated concept pointers.
497 /// Requires iterators to be valid across appending new entries and arbitrary
498 /// erases. Provides both the pass ID and concept pointer such that it is
499 /// half of a bijection and provides storage for the actual result concept.
500 typedef std::list<std::pair<
501 void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
502 FunctionAnalysisResultListT;
504 /// \brief Map type from function pointer to our custom list type.
505 typedef DenseMap<Function *, FunctionAnalysisResultListT>
506 FunctionAnalysisResultListMapT;
508 /// \brief Map from function to a list of function analysis results.
510 /// Provides linear time removal of all analysis results for a function and
511 /// the ultimate storage for a particular cached analysis result.
512 FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
514 /// \brief Map type from a pair of analysis ID and function pointer to an
515 /// iterator into a particular result list.
516 typedef DenseMap<std::pair<void *, Function *>,
517 FunctionAnalysisResultListT::iterator>
518 FunctionAnalysisResultMapT;
520 /// \brief Map from an analysis ID and function to a particular cached
522 FunctionAnalysisResultMapT FunctionAnalysisResults;