Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / PassManager.h
blob47bad5b2f1995bc91c17db4d5111d7c646d2bcb8
1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// This header defines various interfaces for pass management in LLVM. There
11 /// is no "pass" interface in LLVM per se. Instead, an instance of any class
12 /// which supports a method to 'run' it over a unit of IR can be used as
13 /// a pass. A pass manager is generally a tool to collect a sequence of passes
14 /// which run over a particular IR construct, and run each of them in sequence
15 /// over each such construct in the containing IR construct. As there is no
16 /// containing IR construct for a Module, a manager for passes over modules
17 /// forms the base case which runs its managed passes in sequence over the
18 /// single module provided.
19 ///
20 /// The core IR library provides managers for running passes over
21 /// modules and functions.
22 ///
23 /// * FunctionPassManager can run over a Module, runs each pass over
24 /// a Function.
25 /// * ModulePassManager must be directly run, runs each pass over the Module.
26 ///
27 /// Note that the implementations of the pass managers use concept-based
28 /// polymorphism as outlined in the "Value Semantics and Concept-based
29 /// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
30 /// Class of Evil") by Sean Parent:
31 /// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
32 /// * http://www.youtube.com/watch?v=_BpMYeUFXv8
33 /// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
34 ///
35 //===----------------------------------------------------------------------===//
37 #ifndef LLVM_IR_PASSMANAGER_H
38 #define LLVM_IR_PASSMANAGER_H
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/ADT/TinyPtrVector.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/PassInstrumentation.h"
47 #include "llvm/IR/PassManagerInternal.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/TypeName.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <cstring>
54 #include <iterator>
55 #include <list>
56 #include <memory>
57 #include <tuple>
58 #include <type_traits>
59 #include <utility>
60 #include <vector>
62 namespace llvm {
64 /// A special type used by analysis passes to provide an address that
65 /// identifies that particular analysis pass type.
66 ///
67 /// Analysis passes should have a static data member of this type and derive
68 /// from the \c AnalysisInfoMixin to get a static ID method used to identify
69 /// the analysis in the pass management infrastructure.
70 struct alignas(8) AnalysisKey {};
72 /// A special type used to provide an address that identifies a set of related
73 /// analyses. These sets are primarily used below to mark sets of analyses as
74 /// preserved.
75 ///
76 /// For example, a transformation can indicate that it preserves the CFG of a
77 /// function by preserving the appropriate AnalysisSetKey. An analysis that
78 /// depends only on the CFG can then check if that AnalysisSetKey is preserved;
79 /// if it is, the analysis knows that it itself is preserved.
80 struct alignas(8) AnalysisSetKey {};
82 /// This templated class represents "all analyses that operate over \<a
83 /// particular IR unit\>" (e.g. a Function or a Module) in instances of
84 /// PreservedAnalysis.
85 ///
86 /// This lets a transformation say e.g. "I preserved all function analyses".
87 ///
88 /// Note that you must provide an explicit instantiation declaration and
89 /// definition for this template in order to get the correct behavior on
90 /// Windows. Otherwise, the address of SetKey will not be stable.
91 template <typename IRUnitT> class AllAnalysesOn {
92 public:
93 static AnalysisSetKey *ID() { return &SetKey; }
95 private:
96 static AnalysisSetKey SetKey;
99 template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;
101 extern template class AllAnalysesOn<Module>;
102 extern template class AllAnalysesOn<Function>;
104 /// Represents analyses that only rely on functions' control flow.
106 /// This can be used with \c PreservedAnalyses to mark the CFG as preserved and
107 /// to query whether it has been preserved.
109 /// The CFG of a function is defined as the set of basic blocks and the edges
110 /// between them. Changing the set of basic blocks in a function is enough to
111 /// mutate the CFG. Mutating the condition of a branch or argument of an
112 /// invoked function does not mutate the CFG, but changing the successor labels
113 /// of those instructions does.
114 class CFGAnalyses {
115 public:
116 static AnalysisSetKey *ID() { return &SetKey; }
118 private:
119 static AnalysisSetKey SetKey;
122 /// A set of analyses that are preserved following a run of a transformation
123 /// pass.
125 /// Transformation passes build and return these objects to communicate which
126 /// analyses are still valid after the transformation. For most passes this is
127 /// fairly simple: if they don't change anything all analyses are preserved,
128 /// otherwise only a short list of analyses that have been explicitly updated
129 /// are preserved.
131 /// This class also lets transformation passes mark abstract *sets* of analyses
132 /// as preserved. A transformation that (say) does not alter the CFG can
133 /// indicate such by marking a particular AnalysisSetKey as preserved, and
134 /// then analyses can query whether that AnalysisSetKey is preserved.
136 /// Finally, this class can represent an "abandoned" analysis, which is
137 /// not preserved even if it would be covered by some abstract set of analyses.
139 /// Given a `PreservedAnalyses` object, an analysis will typically want to
140 /// figure out whether it is preserved. In the example below, MyAnalysisType is
141 /// preserved if it's not abandoned, and (a) it's explicitly marked as
142 /// preserved, (b), the set AllAnalysesOn<MyIRUnit> is preserved, or (c) both
143 /// AnalysisSetA and AnalysisSetB are preserved.
145 /// ```
146 /// auto PAC = PA.getChecker<MyAnalysisType>();
147 /// if (PAC.preserved() || PAC.preservedSet<AllAnalysesOn<MyIRUnit>>() ||
148 /// (PAC.preservedSet<AnalysisSetA>() &&
149 /// PAC.preservedSet<AnalysisSetB>())) {
150 /// // The analysis has been successfully preserved ...
151 /// }
152 /// ```
153 class PreservedAnalyses {
154 public:
155 /// Convenience factory function for the empty preserved set.
156 static PreservedAnalyses none() { return PreservedAnalyses(); }
158 /// Construct a special preserved set that preserves all passes.
159 static PreservedAnalyses all() {
160 PreservedAnalyses PA;
161 PA.PreservedIDs.insert(&AllAnalysesKey);
162 return PA;
165 /// Construct a preserved analyses object with a single preserved set.
166 template <typename AnalysisSetT>
167 static PreservedAnalyses allInSet() {
168 PreservedAnalyses PA;
169 PA.preserveSet<AnalysisSetT>();
170 return PA;
173 /// Mark an analysis as preserved.
174 template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); }
176 /// Given an analysis's ID, mark the analysis as preserved, adding it
177 /// to the set.
178 void preserve(AnalysisKey *ID) {
179 // Clear this ID from the explicit not-preserved set if present.
180 NotPreservedAnalysisIDs.erase(ID);
182 // If we're not already preserving all analyses (other than those in
183 // NotPreservedAnalysisIDs).
184 if (!areAllPreserved())
185 PreservedIDs.insert(ID);
188 /// Mark an analysis set as preserved.
189 template <typename AnalysisSetT> void preserveSet() {
190 preserveSet(AnalysisSetT::ID());
193 /// Mark an analysis set as preserved using its ID.
194 void preserveSet(AnalysisSetKey *ID) {
195 // If we're not already in the saturated 'all' state, add this set.
196 if (!areAllPreserved())
197 PreservedIDs.insert(ID);
200 /// Mark an analysis as abandoned.
202 /// An abandoned analysis is not preserved, even if it is nominally covered
203 /// by some other set or was previously explicitly marked as preserved.
205 /// Note that you can only abandon a specific analysis, not a *set* of
206 /// analyses.
207 template <typename AnalysisT> void abandon() { abandon(AnalysisT::ID()); }
209 /// Mark an analysis as abandoned using its ID.
211 /// An abandoned analysis is not preserved, even if it is nominally covered
212 /// by some other set or was previously explicitly marked as preserved.
214 /// Note that you can only abandon a specific analysis, not a *set* of
215 /// analyses.
216 void abandon(AnalysisKey *ID) {
217 PreservedIDs.erase(ID);
218 NotPreservedAnalysisIDs.insert(ID);
221 /// Intersect this set with another in place.
223 /// This is a mutating operation on this preserved set, removing all
224 /// preserved passes which are not also preserved in the argument.
225 void intersect(const PreservedAnalyses &Arg) {
226 if (Arg.areAllPreserved())
227 return;
228 if (areAllPreserved()) {
229 *this = Arg;
230 return;
232 // The intersection requires the *union* of the explicitly not-preserved
233 // IDs and the *intersection* of the preserved IDs.
234 for (auto ID : Arg.NotPreservedAnalysisIDs) {
235 PreservedIDs.erase(ID);
236 NotPreservedAnalysisIDs.insert(ID);
238 for (auto ID : PreservedIDs)
239 if (!Arg.PreservedIDs.count(ID))
240 PreservedIDs.erase(ID);
243 /// Intersect this set with a temporary other set in place.
245 /// This is a mutating operation on this preserved set, removing all
246 /// preserved passes which are not also preserved in the argument.
247 void intersect(PreservedAnalyses &&Arg) {
248 if (Arg.areAllPreserved())
249 return;
250 if (areAllPreserved()) {
251 *this = std::move(Arg);
252 return;
254 // The intersection requires the *union* of the explicitly not-preserved
255 // IDs and the *intersection* of the preserved IDs.
256 for (auto ID : Arg.NotPreservedAnalysisIDs) {
257 PreservedIDs.erase(ID);
258 NotPreservedAnalysisIDs.insert(ID);
260 for (auto ID : PreservedIDs)
261 if (!Arg.PreservedIDs.count(ID))
262 PreservedIDs.erase(ID);
265 /// A checker object that makes it easy to query for whether an analysis or
266 /// some set covering it is preserved.
267 class PreservedAnalysisChecker {
268 friend class PreservedAnalyses;
270 const PreservedAnalyses &PA;
271 AnalysisKey *const ID;
272 const bool IsAbandoned;
274 /// A PreservedAnalysisChecker is tied to a particular Analysis because
275 /// `preserved()` and `preservedSet()` both return false if the Analysis
276 /// was abandoned.
277 PreservedAnalysisChecker(const PreservedAnalyses &PA, AnalysisKey *ID)
278 : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {}
280 public:
281 /// Returns true if the checker's analysis was not abandoned and either
282 /// - the analysis is explicitly preserved or
283 /// - all analyses are preserved.
284 bool preserved() {
285 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
286 PA.PreservedIDs.count(ID));
289 /// Returns true if the checker's analysis was not abandoned and either
290 /// - \p AnalysisSetT is explicitly preserved or
291 /// - all analyses are preserved.
292 template <typename AnalysisSetT> bool preservedSet() {
293 AnalysisSetKey *SetID = AnalysisSetT::ID();
294 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
295 PA.PreservedIDs.count(SetID));
299 /// Build a checker for this `PreservedAnalyses` and the specified analysis
300 /// type.
302 /// You can use the returned object to query whether an analysis was
303 /// preserved. See the example in the comment on `PreservedAnalysis`.
304 template <typename AnalysisT> PreservedAnalysisChecker getChecker() const {
305 return PreservedAnalysisChecker(*this, AnalysisT::ID());
308 /// Build a checker for this `PreservedAnalyses` and the specified analysis
309 /// ID.
311 /// You can use the returned object to query whether an analysis was
312 /// preserved. See the example in the comment on `PreservedAnalysis`.
313 PreservedAnalysisChecker getChecker(AnalysisKey *ID) const {
314 return PreservedAnalysisChecker(*this, ID);
317 /// Test whether all analyses are preserved (and none are abandoned).
319 /// This is used primarily to optimize for the common case of a transformation
320 /// which makes no changes to the IR.
321 bool areAllPreserved() const {
322 return NotPreservedAnalysisIDs.empty() &&
323 PreservedIDs.count(&AllAnalysesKey);
326 /// Directly test whether a set of analyses is preserved.
328 /// This is only true when no analyses have been explicitly abandoned.
329 template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const {
330 return allAnalysesInSetPreserved(AnalysisSetT::ID());
333 /// Directly test whether a set of analyses is preserved.
335 /// This is only true when no analyses have been explicitly abandoned.
336 bool allAnalysesInSetPreserved(AnalysisSetKey *SetID) const {
337 return NotPreservedAnalysisIDs.empty() &&
338 (PreservedIDs.count(&AllAnalysesKey) || PreservedIDs.count(SetID));
341 private:
342 /// A special key used to indicate all analyses.
343 static AnalysisSetKey AllAnalysesKey;
345 /// The IDs of analyses and analysis sets that are preserved.
346 SmallPtrSet<void *, 2> PreservedIDs;
348 /// The IDs of explicitly not-preserved analyses.
350 /// If an analysis in this set is covered by a set in `PreservedIDs`, we
351 /// consider it not-preserved. That is, `NotPreservedAnalysisIDs` always
352 /// "wins" over analysis sets in `PreservedIDs`.
354 /// Also, a given ID should never occur both here and in `PreservedIDs`.
355 SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs;
358 // Forward declare the analysis manager template.
359 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
361 /// A CRTP mix-in to automatically provide informational APIs needed for
362 /// passes.
364 /// This provides some boilerplate for types that are passes.
365 template <typename DerivedT> struct PassInfoMixin {
366 /// Gets the name of the pass we are mixed into.
367 static StringRef name() {
368 static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value,
369 "Must pass the derived type as the template argument!");
370 StringRef Name = getTypeName<DerivedT>();
371 if (Name.startswith("llvm::"))
372 Name = Name.drop_front(strlen("llvm::"));
373 return Name;
377 /// A CRTP mix-in that provides informational APIs needed for analysis passes.
379 /// This provides some boilerplate for types that are analysis passes. It
380 /// automatically mixes in \c PassInfoMixin.
381 template <typename DerivedT>
382 struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
383 /// Returns an opaque, unique ID for this analysis type.
385 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
386 /// suitable for use in sets, maps, and other data structures that use the low
387 /// bits of pointers.
389 /// Note that this requires the derived type provide a static \c AnalysisKey
390 /// member called \c Key.
392 /// FIXME: The only reason the mixin type itself can't declare the Key value
393 /// is that some compilers cannot correctly unique a templated static variable
394 /// so it has the same addresses in each instantiation. The only currently
395 /// known platform with this limitation is Windows DLL builds, specifically
396 /// building each part of LLVM as a DLL. If we ever remove that build
397 /// configuration, this mixin can provide the static key as well.
398 static AnalysisKey *ID() {
399 static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
400 "Must pass the derived type as the template argument!");
401 return &DerivedT::Key;
405 namespace detail {
407 /// Actual unpacker of extra arguments in getAnalysisResult,
408 /// passes only those tuple arguments that are mentioned in index_sequence.
409 template <typename PassT, typename IRUnitT, typename AnalysisManagerT,
410 typename... ArgTs, size_t... Ns>
411 typename PassT::Result
412 getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR,
413 std::tuple<ArgTs...> Args,
414 llvm::index_sequence<Ns...>) {
415 (void)Args;
416 return AM.template getResult<PassT>(IR, std::get<Ns>(Args)...);
419 /// Helper for *partial* unpacking of extra arguments in getAnalysisResult.
421 /// Arguments passed in tuple come from PassManager, so they might have extra
422 /// arguments after those AnalysisManager's ExtraArgTs ones that we need to
423 /// pass to getResult.
424 template <typename PassT, typename IRUnitT, typename... AnalysisArgTs,
425 typename... MainArgTs>
426 typename PassT::Result
427 getAnalysisResult(AnalysisManager<IRUnitT, AnalysisArgTs...> &AM, IRUnitT &IR,
428 std::tuple<MainArgTs...> Args) {
429 return (getAnalysisResultUnpackTuple<
430 PassT, IRUnitT>)(AM, IR, Args,
431 llvm::index_sequence_for<AnalysisArgTs...>{});
434 } // namespace detail
436 // Forward declare the pass instrumentation analysis explicitly queried in
437 // generic PassManager code.
438 // FIXME: figure out a way to move PassInstrumentationAnalysis into its own
439 // header.
440 class PassInstrumentationAnalysis;
442 /// Manages a sequence of passes over a particular unit of IR.
444 /// A pass manager contains a sequence of passes to run over a particular unit
445 /// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
446 /// IR, and when run over some given IR will run each of its contained passes in
447 /// sequence. Pass managers are the primary and most basic building block of a
448 /// pass pipeline.
450 /// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
451 /// argument. The pass manager will propagate that analysis manager to each
452 /// pass it runs, and will call the analysis manager's invalidation routine with
453 /// the PreservedAnalyses of each pass it runs.
454 template <typename IRUnitT,
455 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
456 typename... ExtraArgTs>
457 class PassManager : public PassInfoMixin<
458 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
459 public:
460 /// Construct a pass manager.
462 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
463 explicit PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
465 // FIXME: These are equivalent to the default move constructor/move
466 // assignment. However, using = default triggers linker errors due to the
467 // explicit instantiations below. Find away to use the default and remove the
468 // duplicated code here.
469 PassManager(PassManager &&Arg)
470 : Passes(std::move(Arg.Passes)),
471 DebugLogging(std::move(Arg.DebugLogging)) {}
473 PassManager &operator=(PassManager &&RHS) {
474 Passes = std::move(RHS.Passes);
475 DebugLogging = std::move(RHS.DebugLogging);
476 return *this;
479 /// Run all of the passes in this manager over the given unit of IR.
480 /// ExtraArgs are passed to each pass.
481 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
482 ExtraArgTs... ExtraArgs) {
483 PreservedAnalyses PA = PreservedAnalyses::all();
485 // Request PassInstrumentation from analysis manager, will use it to run
486 // instrumenting callbacks for the passes later.
487 // Here we use std::tuple wrapper over getResult which helps to extract
488 // AnalysisManager's arguments out of the whole ExtraArgs set.
489 PassInstrumentation PI =
490 detail::getAnalysisResult<PassInstrumentationAnalysis>(
491 AM, IR, std::tuple<ExtraArgTs...>(ExtraArgs...));
493 if (DebugLogging)
494 dbgs() << "Starting " << getTypeName<IRUnitT>() << " pass manager run.\n";
496 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
497 auto *P = Passes[Idx].get();
498 if (DebugLogging)
499 dbgs() << "Running pass: " << P->name() << " on " << IR.getName()
500 << "\n";
502 // Check the PassInstrumentation's BeforePass callbacks before running the
503 // pass, skip its execution completely if asked to (callback returns
504 // false).
505 if (!PI.runBeforePass<IRUnitT>(*P, IR))
506 continue;
508 PreservedAnalyses PassPA = P->run(IR, AM, ExtraArgs...);
510 // Call onto PassInstrumentation's AfterPass callbacks immediately after
511 // running the pass.
512 PI.runAfterPass<IRUnitT>(*P, IR);
514 // Update the analysis manager as each pass runs and potentially
515 // invalidates analyses.
516 AM.invalidate(IR, PassPA);
518 // Finally, intersect the preserved analyses to compute the aggregate
519 // preserved set for this pass manager.
520 PA.intersect(std::move(PassPA));
522 // FIXME: Historically, the pass managers all called the LLVM context's
523 // yield function here. We don't have a generic way to acquire the
524 // context and it isn't yet clear what the right pattern is for yielding
525 // in the new pass manager so it is currently omitted.
526 //IR.getContext().yield();
529 // Invalidation was handled after each pass in the above loop for the
530 // current unit of IR. Therefore, the remaining analysis results in the
531 // AnalysisManager are preserved. We mark this with a set so that we don't
532 // need to inspect each one individually.
533 PA.preserveSet<AllAnalysesOn<IRUnitT>>();
535 if (DebugLogging)
536 dbgs() << "Finished " << getTypeName<IRUnitT>() << " pass manager run.\n";
538 return PA;
541 template <typename PassT> void addPass(PassT Pass) {
542 using PassModelT =
543 detail::PassModel<IRUnitT, PassT, PreservedAnalyses, AnalysisManagerT,
544 ExtraArgTs...>;
546 Passes.emplace_back(new PassModelT(std::move(Pass)));
549 private:
550 using PassConceptT =
551 detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>;
553 std::vector<std::unique_ptr<PassConceptT>> Passes;
555 /// Flag indicating whether we should do debug logging.
556 bool DebugLogging;
559 extern template class PassManager<Module>;
561 /// Convenience typedef for a pass manager over modules.
562 using ModulePassManager = PassManager<Module>;
564 extern template class PassManager<Function>;
566 /// Convenience typedef for a pass manager over functions.
567 using FunctionPassManager = PassManager<Function>;
569 /// Pseudo-analysis pass that exposes the \c PassInstrumentation to pass
570 /// managers. Goes before AnalysisManager definition to provide its
571 /// internals (e.g PassInstrumentationAnalysis::ID) for use there if needed.
572 /// FIXME: figure out a way to move PassInstrumentationAnalysis into its own
573 /// header.
574 class PassInstrumentationAnalysis
575 : public AnalysisInfoMixin<PassInstrumentationAnalysis> {
576 friend AnalysisInfoMixin<PassInstrumentationAnalysis>;
577 static AnalysisKey Key;
579 PassInstrumentationCallbacks *Callbacks;
581 public:
582 /// PassInstrumentationCallbacks object is shared, owned by something else,
583 /// not this analysis.
584 PassInstrumentationAnalysis(PassInstrumentationCallbacks *Callbacks = nullptr)
585 : Callbacks(Callbacks) {}
587 using Result = PassInstrumentation;
589 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
590 Result run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
591 return PassInstrumentation(Callbacks);
595 /// A container for analyses that lazily runs them and caches their
596 /// results.
598 /// This class can manage analyses for any IR unit where the address of the IR
599 /// unit sufficies as its identity.
600 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
601 public:
602 class Invalidator;
604 private:
605 // Now that we've defined our invalidator, we can define the concept types.
606 using ResultConceptT =
607 detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>;
608 using PassConceptT =
609 detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator,
610 ExtraArgTs...>;
612 /// List of analysis pass IDs and associated concept pointers.
614 /// Requires iterators to be valid across appending new entries and arbitrary
615 /// erases. Provides the analysis ID to enable finding iterators to a given
616 /// entry in maps below, and provides the storage for the actual result
617 /// concept.
618 using AnalysisResultListT =
619 std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>;
621 /// Map type from IRUnitT pointer to our custom list type.
622 using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>;
624 /// Map type from a pair of analysis ID and IRUnitT pointer to an
625 /// iterator into a particular result list (which is where the actual analysis
626 /// result is stored).
627 using AnalysisResultMapT =
628 DenseMap<std::pair<AnalysisKey *, IRUnitT *>,
629 typename AnalysisResultListT::iterator>;
631 public:
632 /// API to communicate dependencies between analyses during invalidation.
634 /// When an analysis result embeds handles to other analysis results, it
635 /// needs to be invalidated both when its own information isn't preserved and
636 /// when any of its embedded analysis results end up invalidated. We pass an
637 /// \c Invalidator object as an argument to \c invalidate() in order to let
638 /// the analysis results themselves define the dependency graph on the fly.
639 /// This lets us avoid building building an explicit representation of the
640 /// dependencies between analysis results.
641 class Invalidator {
642 public:
643 /// Trigger the invalidation of some other analysis pass if not already
644 /// handled and return whether it was in fact invalidated.
646 /// This is expected to be called from within a given analysis result's \c
647 /// invalidate method to trigger a depth-first walk of all inter-analysis
648 /// dependencies. The same \p IR unit and \p PA passed to that result's \c
649 /// invalidate method should in turn be provided to this routine.
651 /// The first time this is called for a given analysis pass, it will call
652 /// the corresponding result's \c invalidate method. Subsequent calls will
653 /// use a cache of the results of that initial call. It is an error to form
654 /// cyclic dependencies between analysis results.
656 /// This returns true if the given analysis's result is invalid. Any
657 /// dependecies on it will become invalid as a result.
658 template <typename PassT>
659 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
660 using ResultModelT =
661 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
662 PreservedAnalyses, Invalidator>;
664 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
667 /// A type-erased variant of the above invalidate method with the same core
668 /// API other than passing an analysis ID rather than an analysis type
669 /// parameter.
671 /// This is sadly less efficient than the above routine, which leverages
672 /// the type parameter to avoid the type erasure overhead.
673 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
674 return invalidateImpl<>(ID, IR, PA);
677 private:
678 friend class AnalysisManager;
680 template <typename ResultT = ResultConceptT>
681 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
682 const PreservedAnalyses &PA) {
683 // If we've already visited this pass, return true if it was invalidated
684 // and false otherwise.
685 auto IMapI = IsResultInvalidated.find(ID);
686 if (IMapI != IsResultInvalidated.end())
687 return IMapI->second;
689 // Otherwise look up the result object.
690 auto RI = Results.find({ID, &IR});
691 assert(RI != Results.end() &&
692 "Trying to invalidate a dependent result that isn't in the "
693 "manager's cache is always an error, likely due to a stale result "
694 "handle!");
696 auto &Result = static_cast<ResultT &>(*RI->second->second);
698 // Insert into the map whether the result should be invalidated and return
699 // that. Note that we cannot reuse IMapI and must do a fresh insert here,
700 // as calling invalidate could (recursively) insert things into the map,
701 // making any iterator or reference invalid.
702 bool Inserted;
703 std::tie(IMapI, Inserted) =
704 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
705 (void)Inserted;
706 assert(Inserted && "Should not have already inserted this ID, likely "
707 "indicates a dependency cycle!");
708 return IMapI->second;
711 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
712 const AnalysisResultMapT &Results)
713 : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
715 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
716 const AnalysisResultMapT &Results;
719 /// Construct an empty analysis manager.
721 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
722 AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
723 AnalysisManager(AnalysisManager &&) = default;
724 AnalysisManager &operator=(AnalysisManager &&) = default;
726 /// Returns true if the analysis manager has an empty results cache.
727 bool empty() const {
728 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
729 "The storage and index of analysis results disagree on how many "
730 "there are!");
731 return AnalysisResults.empty();
734 /// Clear any cached analysis results for a single unit of IR.
736 /// This doesn't invalidate, but instead simply deletes, the relevant results.
737 /// It is useful when the IR is being removed and we want to clear out all the
738 /// memory pinned for it.
739 void clear(IRUnitT &IR, llvm::StringRef Name) {
740 if (DebugLogging)
741 dbgs() << "Clearing all analysis results for: " << Name << "\n";
743 auto ResultsListI = AnalysisResultLists.find(&IR);
744 if (ResultsListI == AnalysisResultLists.end())
745 return;
746 // Delete the map entries that point into the results list.
747 for (auto &IDAndResult : ResultsListI->second)
748 AnalysisResults.erase({IDAndResult.first, &IR});
750 // And actually destroy and erase the results associated with this IR.
751 AnalysisResultLists.erase(ResultsListI);
754 /// Clear all analysis results cached by this AnalysisManager.
756 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
757 /// deletes them. This lets you clean up the AnalysisManager when the set of
758 /// IR units itself has potentially changed, and thus we can't even look up a
759 /// a result and invalidate/clear it directly.
760 void clear() {
761 AnalysisResults.clear();
762 AnalysisResultLists.clear();
765 /// Get the result of an analysis pass for a given IR unit.
767 /// Runs the analysis if a cached result is not available.
768 template <typename PassT>
769 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
770 assert(AnalysisPasses.count(PassT::ID()) &&
771 "This analysis pass was not registered prior to being queried");
772 ResultConceptT &ResultConcept =
773 getResultImpl(PassT::ID(), IR, ExtraArgs...);
775 using ResultModelT =
776 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
777 PreservedAnalyses, Invalidator>;
779 return static_cast<ResultModelT &>(ResultConcept).Result;
782 /// Get the cached result of an analysis pass for a given IR unit.
784 /// This method never runs the analysis.
786 /// \returns null if there is no cached result.
787 template <typename PassT>
788 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
789 assert(AnalysisPasses.count(PassT::ID()) &&
790 "This analysis pass was not registered prior to being queried");
792 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
793 if (!ResultConcept)
794 return nullptr;
796 using ResultModelT =
797 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
798 PreservedAnalyses, Invalidator>;
800 return &static_cast<ResultModelT *>(ResultConcept)->Result;
803 /// Register an analysis pass with the manager.
805 /// The parameter is a callable whose result is an analysis pass. This allows
806 /// passing in a lambda to construct the analysis.
808 /// The analysis type to register is the type returned by calling the \c
809 /// PassBuilder argument. If that type has already been registered, then the
810 /// argument will not be called and this function will return false.
811 /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
812 /// and this function returns true.
814 /// (Note: Although the return value of this function indicates whether or not
815 /// an analysis was previously registered, there intentionally isn't a way to
816 /// query this directly. Instead, you should just register all the analyses
817 /// you might want and let this class run them lazily. This idiom lets us
818 /// minimize the number of times we have to look up analyses in our
819 /// hashtable.)
820 template <typename PassBuilderT>
821 bool registerPass(PassBuilderT &&PassBuilder) {
822 using PassT = decltype(PassBuilder());
823 using PassModelT =
824 detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses,
825 Invalidator, ExtraArgTs...>;
827 auto &PassPtr = AnalysisPasses[PassT::ID()];
828 if (PassPtr)
829 // Already registered this pass type!
830 return false;
832 // Construct a new model around the instance returned by the builder.
833 PassPtr.reset(new PassModelT(PassBuilder()));
834 return true;
837 /// Invalidate a specific analysis pass for an IR module.
839 /// Note that the analysis result can disregard invalidation, if it determines
840 /// it is in fact still valid.
841 template <typename PassT> void invalidate(IRUnitT &IR) {
842 assert(AnalysisPasses.count(PassT::ID()) &&
843 "This analysis pass was not registered prior to being invalidated");
844 invalidateImpl(PassT::ID(), IR);
847 /// Invalidate cached analyses for an IR unit.
849 /// Walk through all of the analyses pertaining to this unit of IR and
850 /// invalidate them, unless they are preserved by the PreservedAnalyses set.
851 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
852 // We're done if all analyses on this IR unit are preserved.
853 if (PA.allAnalysesInSetPreserved<AllAnalysesOn<IRUnitT>>())
854 return;
856 if (DebugLogging)
857 dbgs() << "Invalidating all non-preserved analyses for: " << IR.getName()
858 << "\n";
860 // Track whether each analysis's result is invalidated in
861 // IsResultInvalidated.
862 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
863 Invalidator Inv(IsResultInvalidated, AnalysisResults);
864 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
865 for (auto &AnalysisResultPair : ResultsList) {
866 // This is basically the same thing as Invalidator::invalidate, but we
867 // can't call it here because we're operating on the type-erased result.
868 // Moreover if we instead called invalidate() directly, it would do an
869 // unnecessary look up in ResultsList.
870 AnalysisKey *ID = AnalysisResultPair.first;
871 auto &Result = *AnalysisResultPair.second;
873 auto IMapI = IsResultInvalidated.find(ID);
874 if (IMapI != IsResultInvalidated.end())
875 // This result was already handled via the Invalidator.
876 continue;
878 // Try to invalidate the result, giving it the Invalidator so it can
879 // recursively query for any dependencies it has and record the result.
880 // Note that we cannot reuse 'IMapI' here or pre-insert the ID, as
881 // Result.invalidate may insert things into the map, invalidating our
882 // iterator.
883 bool Inserted =
884 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, Inv)})
885 .second;
886 (void)Inserted;
887 assert(Inserted && "Should never have already inserted this ID, likely "
888 "indicates a cycle!");
891 // Now erase the results that were marked above as invalidated.
892 if (!IsResultInvalidated.empty()) {
893 for (auto I = ResultsList.begin(), E = ResultsList.end(); I != E;) {
894 AnalysisKey *ID = I->first;
895 if (!IsResultInvalidated.lookup(ID)) {
896 ++I;
897 continue;
900 if (DebugLogging)
901 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
902 << " on " << IR.getName() << "\n";
904 I = ResultsList.erase(I);
905 AnalysisResults.erase({ID, &IR});
909 if (ResultsList.empty())
910 AnalysisResultLists.erase(&IR);
913 private:
914 /// Look up a registered analysis pass.
915 PassConceptT &lookUpPass(AnalysisKey *ID) {
916 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
917 assert(PI != AnalysisPasses.end() &&
918 "Analysis passes must be registered prior to being queried!");
919 return *PI->second;
922 /// Look up a registered analysis pass.
923 const PassConceptT &lookUpPass(AnalysisKey *ID) const {
924 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
925 assert(PI != AnalysisPasses.end() &&
926 "Analysis passes must be registered prior to being queried!");
927 return *PI->second;
930 /// Get an analysis result, running the pass if necessary.
931 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
932 ExtraArgTs... ExtraArgs) {
933 typename AnalysisResultMapT::iterator RI;
934 bool Inserted;
935 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
936 std::make_pair(ID, &IR), typename AnalysisResultListT::iterator()));
938 // If we don't have a cached result for this function, look up the pass and
939 // run it to produce a result, which we then add to the cache.
940 if (Inserted) {
941 auto &P = this->lookUpPass(ID);
942 if (DebugLogging)
943 dbgs() << "Running analysis: " << P.name() << " on " << IR.getName()
944 << "\n";
946 PassInstrumentation PI;
947 if (ID != PassInstrumentationAnalysis::ID()) {
948 PI = getResult<PassInstrumentationAnalysis>(IR, ExtraArgs...);
949 PI.runBeforeAnalysis(P, IR);
952 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
953 ResultList.emplace_back(ID, P.run(IR, *this, ExtraArgs...));
955 PI.runAfterAnalysis(P, IR);
957 // P.run may have inserted elements into AnalysisResults and invalidated
958 // RI.
959 RI = AnalysisResults.find({ID, &IR});
960 assert(RI != AnalysisResults.end() && "we just inserted it!");
962 RI->second = std::prev(ResultList.end());
965 return *RI->second->second;
968 /// Get a cached analysis result or return null.
969 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
970 typename AnalysisResultMapT::const_iterator RI =
971 AnalysisResults.find({ID, &IR});
972 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
975 /// Invalidate a function pass result.
976 void invalidateImpl(AnalysisKey *ID, IRUnitT &IR) {
977 typename AnalysisResultMapT::iterator RI =
978 AnalysisResults.find({ID, &IR});
979 if (RI == AnalysisResults.end())
980 return;
982 if (DebugLogging)
983 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
984 << " on " << IR.getName() << "\n";
985 AnalysisResultLists[&IR].erase(RI->second);
986 AnalysisResults.erase(RI);
989 /// Map type from module analysis pass ID to pass concept pointer.
990 using AnalysisPassMapT =
991 DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>;
993 /// Collection of module analysis passes, indexed by ID.
994 AnalysisPassMapT AnalysisPasses;
996 /// Map from function to a list of function analysis results.
998 /// Provides linear time removal of all analysis results for a function and
999 /// the ultimate storage for a particular cached analysis result.
1000 AnalysisResultListMapT AnalysisResultLists;
1002 /// Map from an analysis ID and function to a particular cached
1003 /// analysis result.
1004 AnalysisResultMapT AnalysisResults;
1006 /// Indicates whether we log to \c llvm::dbgs().
1007 bool DebugLogging;
1010 extern template class AnalysisManager<Module>;
1012 /// Convenience typedef for the Module analysis manager.
1013 using ModuleAnalysisManager = AnalysisManager<Module>;
1015 extern template class AnalysisManager<Function>;
1017 /// Convenience typedef for the Function analysis manager.
1018 using FunctionAnalysisManager = AnalysisManager<Function>;
1020 /// An analysis over an "outer" IR unit that provides access to an
1021 /// analysis manager over an "inner" IR unit. The inner unit must be contained
1022 /// in the outer unit.
1024 /// For example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
1025 /// an analysis over Modules (the "outer" unit) that provides access to a
1026 /// Function analysis manager. The FunctionAnalysisManager is the "inner"
1027 /// manager being proxied, and Functions are the "inner" unit. The inner/outer
1028 /// relationship is valid because each Function is contained in one Module.
1030 /// If you're (transitively) within a pass manager for an IR unit U that
1031 /// contains IR unit V, you should never use an analysis manager over V, except
1032 /// via one of these proxies.
1034 /// Note that the proxy's result is a move-only RAII object. The validity of
1035 /// the analyses in the inner analysis manager is tied to its lifetime.
1036 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1037 class InnerAnalysisManagerProxy
1038 : public AnalysisInfoMixin<
1039 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
1040 public:
1041 class Result {
1042 public:
1043 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
1045 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
1046 // We have to null out the analysis manager in the moved-from state
1047 // because we are taking ownership of the responsibilty to clear the
1048 // analysis state.
1049 Arg.InnerAM = nullptr;
1052 ~Result() {
1053 // InnerAM is cleared in a moved from state where there is nothing to do.
1054 if (!InnerAM)
1055 return;
1057 // Clear out the analysis manager if we're being destroyed -- it means we
1058 // didn't even see an invalidate call when we got invalidated.
1059 InnerAM->clear();
1062 Result &operator=(Result &&RHS) {
1063 InnerAM = RHS.InnerAM;
1064 // We have to null out the analysis manager in the moved-from state
1065 // because we are taking ownership of the responsibilty to clear the
1066 // analysis state.
1067 RHS.InnerAM = nullptr;
1068 return *this;
1071 /// Accessor for the analysis manager.
1072 AnalysisManagerT &getManager() { return *InnerAM; }
1074 /// Handler for invalidation of the outer IR unit, \c IRUnitT.
1076 /// If the proxy analysis itself is not preserved, we assume that the set of
1077 /// inner IR objects contained in IRUnit may have changed. In this case,
1078 /// we have to call \c clear() on the inner analysis manager, as it may now
1079 /// have stale pointers to its inner IR objects.
1081 /// Regardless of whether the proxy analysis is marked as preserved, all of
1082 /// the analyses in the inner analysis manager are potentially invalidated
1083 /// based on the set of preserved analyses.
1084 bool invalidate(
1085 IRUnitT &IR, const PreservedAnalyses &PA,
1086 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv);
1088 private:
1089 AnalysisManagerT *InnerAM;
1092 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
1093 : InnerAM(&InnerAM) {}
1095 /// Run the analysis pass and create our proxy result object.
1097 /// This doesn't do any interesting work; it is primarily used to insert our
1098 /// proxy result object into the outer analysis cache so that we can proxy
1099 /// invalidation to the inner analysis manager.
1100 Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM,
1101 ExtraArgTs...) {
1102 return Result(*InnerAM);
1105 private:
1106 friend AnalysisInfoMixin<
1107 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
1109 static AnalysisKey Key;
1111 AnalysisManagerT *InnerAM;
1114 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1115 AnalysisKey
1116 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1118 /// Provide the \c FunctionAnalysisManager to \c Module proxy.
1119 using FunctionAnalysisManagerModuleProxy =
1120 InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>;
1122 /// Specialization of the invalidate method for the \c
1123 /// FunctionAnalysisManagerModuleProxy's result.
1124 template <>
1125 bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
1126 Module &M, const PreservedAnalyses &PA,
1127 ModuleAnalysisManager::Invalidator &Inv);
1129 // Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
1130 // template.
1131 extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
1132 Module>;
1134 /// An analysis over an "inner" IR unit that provides access to an
1135 /// analysis manager over a "outer" IR unit. The inner unit must be contained
1136 /// in the outer unit.
1138 /// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
1139 /// analysis over Functions (the "inner" unit) which provides access to a Module
1140 /// analysis manager. The ModuleAnalysisManager is the "outer" manager being
1141 /// proxied, and Modules are the "outer" IR unit. The inner/outer relationship
1142 /// is valid because each Function is contained in one Module.
1144 /// This proxy only exposes the const interface of the outer analysis manager,
1145 /// to indicate that you cannot cause an outer analysis to run from within an
1146 /// inner pass. Instead, you must rely on the \c getCachedResult API.
1148 /// This proxy doesn't manage invalidation in any way -- that is handled by the
1149 /// recursive return path of each layer of the pass manager. A consequence of
1150 /// this is the outer analyses may be stale. We invalidate the outer analyses
1151 /// only when we're done running passes over the inner IR units.
1152 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1153 class OuterAnalysisManagerProxy
1154 : public AnalysisInfoMixin<
1155 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
1156 public:
1157 /// Result proxy object for \c OuterAnalysisManagerProxy.
1158 class Result {
1159 public:
1160 explicit Result(const AnalysisManagerT &AM) : AM(&AM) {}
1162 const AnalysisManagerT &getManager() const { return *AM; }
1164 /// When invalidation occurs, remove any registered invalidation events.
1165 bool invalidate(
1166 IRUnitT &IRUnit, const PreservedAnalyses &PA,
1167 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv) {
1168 // Loop over the set of registered outer invalidation mappings and if any
1169 // of them map to an analysis that is now invalid, clear it out.
1170 SmallVector<AnalysisKey *, 4> DeadKeys;
1171 for (auto &KeyValuePair : OuterAnalysisInvalidationMap) {
1172 AnalysisKey *OuterID = KeyValuePair.first;
1173 auto &InnerIDs = KeyValuePair.second;
1174 InnerIDs.erase(llvm::remove_if(InnerIDs, [&](AnalysisKey *InnerID) {
1175 return Inv.invalidate(InnerID, IRUnit, PA); }),
1176 InnerIDs.end());
1177 if (InnerIDs.empty())
1178 DeadKeys.push_back(OuterID);
1181 for (auto OuterID : DeadKeys)
1182 OuterAnalysisInvalidationMap.erase(OuterID);
1184 // The proxy itself remains valid regardless of anything else.
1185 return false;
1188 /// Register a deferred invalidation event for when the outer analysis
1189 /// manager processes its invalidations.
1190 template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
1191 void registerOuterAnalysisInvalidation() {
1192 AnalysisKey *OuterID = OuterAnalysisT::ID();
1193 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
1195 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
1196 // Note, this is a linear scan. If we end up with large numbers of
1197 // analyses that all trigger invalidation on the same outer analysis,
1198 // this entire system should be changed to some other deterministic
1199 // data structure such as a `SetVector` of a pair of pointers.
1200 auto InvalidatedIt = std::find(InvalidatedIDList.begin(),
1201 InvalidatedIDList.end(), InvalidatedID);
1202 if (InvalidatedIt == InvalidatedIDList.end())
1203 InvalidatedIDList.push_back(InvalidatedID);
1206 /// Access the map from outer analyses to deferred invalidation requiring
1207 /// analyses.
1208 const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> &
1209 getOuterInvalidations() const {
1210 return OuterAnalysisInvalidationMap;
1213 private:
1214 const AnalysisManagerT *AM;
1216 /// A map from an outer analysis ID to the set of this IR-unit's analyses
1217 /// which need to be invalidated.
1218 SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2>
1219 OuterAnalysisInvalidationMap;
1222 OuterAnalysisManagerProxy(const AnalysisManagerT &AM) : AM(&AM) {}
1224 /// Run the analysis pass and create our proxy result object.
1225 /// Nothing to see here, it just forwards the \c AM reference into the
1226 /// result.
1227 Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &,
1228 ExtraArgTs...) {
1229 return Result(*AM);
1232 private:
1233 friend AnalysisInfoMixin<
1234 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
1236 static AnalysisKey Key;
1238 const AnalysisManagerT *AM;
1241 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1242 AnalysisKey
1243 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1245 extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
1246 Function>;
1247 /// Provide the \c ModuleAnalysisManager to \c Function proxy.
1248 using ModuleAnalysisManagerFunctionProxy =
1249 OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>;
1251 /// Trivial adaptor that maps from a module to its functions.
1253 /// Designed to allow composition of a FunctionPass(Manager) and
1254 /// a ModulePassManager, by running the FunctionPass(Manager) over every
1255 /// function in the module.
1257 /// Function passes run within this adaptor can rely on having exclusive access
1258 /// to the function they are run over. They should not read or modify any other
1259 /// functions! Other threads or systems may be manipulating other functions in
1260 /// the module, and so their state should never be relied on.
1261 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1262 /// violate this principle.
1264 /// Function passes can also read the module containing the function, but they
1265 /// should not modify that module outside of the use lists of various globals.
1266 /// For example, a function pass is not permitted to add functions to the
1267 /// module.
1268 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1269 /// violate this principle.
1271 /// Note that although function passes can access module analyses, module
1272 /// analyses are not invalidated while the function passes are running, so they
1273 /// may be stale. Function analyses will not be stale.
1274 template <typename FunctionPassT>
1275 class ModuleToFunctionPassAdaptor
1276 : public PassInfoMixin<ModuleToFunctionPassAdaptor<FunctionPassT>> {
1277 public:
1278 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
1279 : Pass(std::move(Pass)) {}
1281 /// Runs the function pass across every function in the module.
1282 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) {
1283 FunctionAnalysisManager &FAM =
1284 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1286 // Request PassInstrumentation from analysis manager, will use it to run
1287 // instrumenting callbacks for the passes later.
1288 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(M);
1290 PreservedAnalyses PA = PreservedAnalyses::all();
1291 for (Function &F : M) {
1292 if (F.isDeclaration())
1293 continue;
1295 // Check the PassInstrumentation's BeforePass callbacks before running the
1296 // pass, skip its execution completely if asked to (callback returns
1297 // false).
1298 if (!PI.runBeforePass<Function>(Pass, F))
1299 continue;
1300 PreservedAnalyses PassPA = Pass.run(F, FAM);
1302 PI.runAfterPass(Pass, F);
1304 // We know that the function pass couldn't have invalidated any other
1305 // function's analyses (that's the contract of a function pass), so
1306 // directly handle the function analysis manager's invalidation here.
1307 FAM.invalidate(F, PassPA);
1309 // Then intersect the preserved set so that invalidation of module
1310 // analyses will eventually occur when the module pass completes.
1311 PA.intersect(std::move(PassPA));
1314 // The FunctionAnalysisManagerModuleProxy is preserved because (we assume)
1315 // the function passes we ran didn't add or remove any functions.
1317 // We also preserve all analyses on Functions, because we did all the
1318 // invalidation we needed to do above.
1319 PA.preserveSet<AllAnalysesOn<Function>>();
1320 PA.preserve<FunctionAnalysisManagerModuleProxy>();
1321 return PA;
1324 private:
1325 FunctionPassT Pass;
1328 /// A function to deduce a function pass type and wrap it in the
1329 /// templated adaptor.
1330 template <typename FunctionPassT>
1331 ModuleToFunctionPassAdaptor<FunctionPassT>
1332 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
1333 return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
1336 /// A utility pass template to force an analysis result to be available.
1338 /// If there are extra arguments at the pass's run level there may also be
1339 /// extra arguments to the analysis manager's \c getResult routine. We can't
1340 /// guess how to effectively map the arguments from one to the other, and so
1341 /// this specialization just ignores them.
1343 /// Specific patterns of run-method extra arguments and analysis manager extra
1344 /// arguments will have to be defined as appropriate specializations.
1345 template <typename AnalysisT, typename IRUnitT,
1346 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
1347 typename... ExtraArgTs>
1348 struct RequireAnalysisPass
1349 : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
1350 ExtraArgTs...>> {
1351 /// Run this pass over some unit of IR.
1353 /// This pass can be run over any unit of IR and use any analysis manager
1354 /// provided they satisfy the basic API requirements. When this pass is
1355 /// created, these methods can be instantiated to satisfy whatever the
1356 /// context requires.
1357 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
1358 ExtraArgTs &&... Args) {
1359 (void)AM.template getResult<AnalysisT>(Arg,
1360 std::forward<ExtraArgTs>(Args)...);
1362 return PreservedAnalyses::all();
1366 /// A no-op pass template which simply forces a specific analysis result
1367 /// to be invalidated.
1368 template <typename AnalysisT>
1369 struct InvalidateAnalysisPass
1370 : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
1371 /// Run this pass over some unit of IR.
1373 /// This pass can be run over any unit of IR and use any analysis manager,
1374 /// provided they satisfy the basic API requirements. When this pass is
1375 /// created, these methods can be instantiated to satisfy whatever the
1376 /// context requires.
1377 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1378 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
1379 auto PA = PreservedAnalyses::all();
1380 PA.abandon<AnalysisT>();
1381 return PA;
1385 /// A utility pass that does nothing, but preserves no analyses.
1387 /// Because this preserves no analyses, any analysis passes queried after this
1388 /// pass runs will recompute fresh results.
1389 struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
1390 /// Run this pass over some unit of IR.
1391 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1392 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
1393 return PreservedAnalyses::none();
1397 /// A utility pass template that simply runs another pass multiple times.
1399 /// This can be useful when debugging or testing passes. It also serves as an
1400 /// example of how to extend the pass manager in ways beyond composition.
1401 template <typename PassT>
1402 class RepeatedPass : public PassInfoMixin<RepeatedPass<PassT>> {
1403 public:
1404 RepeatedPass(int Count, PassT P) : Count(Count), P(std::move(P)) {}
1406 template <typename IRUnitT, typename AnalysisManagerT, typename... Ts>
1407 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, Ts &&... Args) {
1409 // Request PassInstrumentation from analysis manager, will use it to run
1410 // instrumenting callbacks for the passes later.
1411 // Here we use std::tuple wrapper over getResult which helps to extract
1412 // AnalysisManager's arguments out of the whole Args set.
1413 PassInstrumentation PI =
1414 detail::getAnalysisResult<PassInstrumentationAnalysis>(
1415 AM, IR, std::tuple<Ts...>(Args...));
1417 auto PA = PreservedAnalyses::all();
1418 for (int i = 0; i < Count; ++i) {
1419 // Check the PassInstrumentation's BeforePass callbacks before running the
1420 // pass, skip its execution completely if asked to (callback returns
1421 // false).
1422 if (!PI.runBeforePass<IRUnitT>(P, IR))
1423 continue;
1424 PA.intersect(P.run(IR, AM, std::forward<Ts>(Args)...));
1425 PI.runAfterPass(P, IR);
1427 return PA;
1430 private:
1431 int Count;
1432 PassT P;
1435 template <typename PassT>
1436 RepeatedPass<PassT> createRepeatedPass(int Count, PassT P) {
1437 return RepeatedPass<PassT>(Count, std::move(P));
1440 } // end namespace llvm
1442 #endif // LLVM_IR_PASSMANAGER_H