LLVM  9.0.0svn
PassManager.h
Go to the documentation of this file.
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 //===----------------------------------------------------------------------===//
36 
37 #ifndef LLVM_IR_PASSMANAGER_H
38 #define LLVM_IR_PASSMANAGER_H
39 
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"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/TypeName.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>
61 
62 namespace llvm {
63 
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 {};
71 
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 {};
81 
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; }
94 
95 private:
96  static AnalysisSetKey SetKey;
97 };
98 
99 template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;
100 
101 extern template class AllAnalysesOn<Module>;
102 extern template class AllAnalysesOn<Function>;
103 
104 /// Represents analyses that only rely on functions' control flow.
105 ///
106 /// This can be used with \c PreservedAnalyses to mark the CFG as preserved and
107 /// to query whether it has been preserved.
108 ///
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; }
117 
118 private:
119  static AnalysisSetKey SetKey;
120 };
121 
122 /// A set of analyses that are preserved following a run of a transformation
123 /// pass.
124 ///
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.
130 ///
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.
135 ///
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.
138 ///
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.
144 ///
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 /// ```
154 public:
155  /// Convenience factory function for the empty preserved set.
156  static PreservedAnalyses none() { return PreservedAnalyses(); }
157 
158  /// Construct a special preserved set that preserves all passes.
161  PA.PreservedIDs.insert(&AllAnalysesKey);
162  return PA;
163  }
164 
165  /// Construct a preserved analyses object with a single preserved set.
166  template <typename AnalysisSetT>
169  PA.preserveSet<AnalysisSetT>();
170  return PA;
171  }
172 
173  /// Mark an analysis as preserved.
174  template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); }
175 
176  /// Given an analysis's ID, mark the analysis as preserved, adding it
177  /// to the set.
179  // Clear this ID from the explicit not-preserved set if present.
180  NotPreservedAnalysisIDs.erase(ID);
181 
182  // If we're not already preserving all analyses (other than those in
183  // NotPreservedAnalysisIDs).
184  if (!areAllPreserved())
185  PreservedIDs.insert(ID);
186  }
187 
188  /// Mark an analysis set as preserved.
189  template <typename AnalysisSetT> void preserveSet() {
190  preserveSet(AnalysisSetT::ID());
191  }
192 
193  /// Mark an analysis set as preserved using its ID.
195  // If we're not already in the saturated 'all' state, add this set.
196  if (!areAllPreserved())
197  PreservedIDs.insert(ID);
198  }
199 
200  /// Mark an analysis as abandoned.
201  ///
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.
204  ///
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()); }
208 
209  /// Mark an analysis as abandoned using its ID.
210  ///
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.
213  ///
214  /// Note that you can only abandon a specific analysis, not a *set* of
215  /// analyses.
217  PreservedIDs.erase(ID);
218  NotPreservedAnalysisIDs.insert(ID);
219  }
220 
221  /// Intersect this set with another in place.
222  ///
223  /// This is a mutating operation on this preserved set, removing all
224  /// preserved passes which are not also preserved in the argument.
226  if (Arg.areAllPreserved())
227  return;
228  if (areAllPreserved()) {
229  *this = Arg;
230  return;
231  }
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);
237  }
238  for (auto ID : PreservedIDs)
239  if (!Arg.PreservedIDs.count(ID))
240  PreservedIDs.erase(ID);
241  }
242 
243  /// Intersect this set with a temporary other set in place.
244  ///
245  /// This is a mutating operation on this preserved set, removing all
246  /// preserved passes which are not also preserved in the argument.
248  if (Arg.areAllPreserved())
249  return;
250  if (areAllPreserved()) {
251  *this = std::move(Arg);
252  return;
253  }
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);
259  }
260  for (auto ID : PreservedIDs)
261  if (!Arg.PreservedIDs.count(ID))
262  PreservedIDs.erase(ID);
263  }
264 
265  /// A checker object that makes it easy to query for whether an analysis or
266  /// some set covering it is preserved.
268  friend class PreservedAnalyses;
269 
270  const PreservedAnalyses &PA;
271  AnalysisKey *const ID;
272  const bool IsAbandoned;
273 
274  /// A PreservedAnalysisChecker is tied to a particular Analysis because
275  /// `preserved()` and `preservedSet()` both return false if the Analysis
276  /// was abandoned.
278  : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {}
279 
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));
287  }
288 
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));
296  }
297  };
298 
299  /// Build a checker for this `PreservedAnalyses` and the specified analysis
300  /// type.
301  ///
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());
306  }
307 
308  /// Build a checker for this `PreservedAnalyses` and the specified analysis
309  /// ID.
310  ///
311  /// You can use the returned object to query whether an analysis was
312  /// preserved. See the example in the comment on `PreservedAnalysis`.
314  return PreservedAnalysisChecker(*this, ID);
315  }
316 
317  /// Test whether all analyses are preserved (and none are abandoned).
318  ///
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);
324  }
325 
326  /// Directly test whether a set of analyses is preserved.
327  ///
328  /// This is only true when no analyses have been explicitly abandoned.
329  template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const {
330  return allAnalysesInSetPreserved(AnalysisSetT::ID());
331  }
332 
333  /// Directly test whether a set of analyses is preserved.
334  ///
335  /// This is only true when no analyses have been explicitly abandoned.
337  return NotPreservedAnalysisIDs.empty() &&
338  (PreservedIDs.count(&AllAnalysesKey) || PreservedIDs.count(SetID));
339  }
340 
341 private:
342  /// A special key used to indicate all analyses.
343  static AnalysisSetKey AllAnalysesKey;
344 
345  /// The IDs of analyses and analysis sets that are preserved.
346  SmallPtrSet<void *, 2> PreservedIDs;
347 
348  /// The IDs of explicitly not-preserved analyses.
349  ///
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`.
353  ///
354  /// Also, a given ID should never occur both here and in `PreservedIDs`.
355  SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs;
356 };
357 
358 // Forward declare the analysis manager template.
359 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
360 
361 /// A CRTP mix-in to automatically provide informational APIs needed for
362 /// passes.
363 ///
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;
374  }
375 };
376 
377 /// A CRTP mix-in that provides informational APIs needed for analysis passes.
378 ///
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.
384  ///
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.
388  ///
389  /// Note that this requires the derived type provide a static \c AnalysisKey
390  /// member called \c Key.
391  ///
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;
402  }
403 };
404 
405 namespace detail {
406 
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,
415  (void)Args;
416  return AM.template getResult<PassT>(IR, std::get<Ns>(Args)...);
417 }
418 
419 /// Helper for *partial* unpacking of extra arguments in getAnalysisResult.
420 ///
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
428  std::tuple<MainArgTs...> Args) {
430  PassT, IRUnitT>)(AM, IR, Args,
431  llvm::index_sequence_for<AnalysisArgTs...>{});
432 }
433 
434 } // namespace detail
435 
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.
441 
442 /// Manages a sequence of passes over a particular unit of IR.
443 ///
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.
449 ///
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.
461  ///
462  /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
463  explicit PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
464 
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.
470  : Passes(std::move(Arg.Passes)),
471  DebugLogging(std::move(Arg.DebugLogging)) {}
472 
474  Passes = std::move(RHS.Passes);
475  DebugLogging = std::move(RHS.DebugLogging);
476  return *this;
477  }
478 
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) {
484 
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.
490  detail::getAnalysisResult<PassInstrumentationAnalysis>(
491  AM, IR, std::tuple<ExtraArgTs...>(ExtraArgs...));
492 
493  if (DebugLogging)
494  dbgs() << "Starting " << getTypeName<IRUnitT>() << " pass manager run.\n";
495 
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";
501 
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;
507 
508  PreservedAnalyses PassPA = P->run(IR, AM, ExtraArgs...);
509 
510  // Call onto PassInstrumentation's AfterPass callbacks immediately after
511  // running the pass.
512  PI.runAfterPass<IRUnitT>(*P, IR);
513 
514  // Update the analysis manager as each pass runs and potentially
515  // invalidates analyses.
516  AM.invalidate(IR, PassPA);
517 
518  // Finally, intersect the preserved analyses to compute the aggregate
519  // preserved set for this pass manager.
520  PA.intersect(std::move(PassPA));
521 
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();
527  }
528 
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.
534 
535  if (DebugLogging)
536  dbgs() << "Finished " << getTypeName<IRUnitT>() << " pass manager run.\n";
537 
538  return PA;
539  }
540 
541  template <typename PassT> void addPass(PassT Pass) {
542  using PassModelT =
543  detail::PassModel<IRUnitT, PassT, PreservedAnalyses, AnalysisManagerT,
544  ExtraArgTs...>;
545 
546  Passes.emplace_back(new PassModelT(std::move(Pass)));
547  }
548 
549 private:
550  using PassConceptT =
551  detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>;
552 
553  std::vector<std::unique_ptr<PassConceptT>> Passes;
554 
555  /// Flag indicating whether we should do debug logging.
556  bool DebugLogging;
557 };
558 
559 extern template class PassManager<Module>;
560 
561 /// Convenience typedef for a pass manager over modules.
563 
564 extern template class PassManager<Function>;
565 
566 /// Convenience typedef for a pass manager over functions.
568 
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.
577  static AnalysisKey Key;
578 
579  PassInstrumentationCallbacks *Callbacks;
580 
581 public:
582  /// PassInstrumentationCallbacks object is shared, owned by something else,
583  /// not this analysis.
585  : Callbacks(Callbacks) {}
586 
588 
589  template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
590  Result run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
591  return PassInstrumentation(Callbacks);
592  }
593 };
594 
595 /// A container for analyses that lazily runs them and caches their
596 /// results.
597 ///
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;
603 
604 private:
605  // Now that we've defined our invalidator, we can define the concept types.
606  using ResultConceptT =
608  using PassConceptT =
609  detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator,
610  ExtraArgTs...>;
611 
612  /// List of analysis pass IDs and associated concept pointers.
613  ///
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>>>;
620 
621  /// Map type from IRUnitT pointer to our custom list type.
622  using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>;
623 
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 =
629  typename AnalysisResultListT::iterator>;
630 
631 public:
632  /// API to communicate dependencies between analyses during invalidation.
633  ///
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.
645  ///
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.
650  ///
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.
655  ///
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>;
663 
664  return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
665  }
666 
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.
670  ///
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);
675  }
676 
677  private:
678  friend class AnalysisManager;
679 
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;
688 
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!");
695 
696  auto &Result = static_cast<ResultT &>(*RI->second->second);
697 
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;
709  }
710 
711  Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
712  const AnalysisResultMapT &Results)
713  : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
714 
715  SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
716  const AnalysisResultMapT &Results;
717  };
718 
719  /// Construct an empty analysis manager.
720  ///
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;
725 
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();
732  }
733 
734  /// Clear any cached analysis results for a single unit of IR.
735  ///
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";
742 
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});
749 
750  // And actually destroy and erase the results associated with this IR.
751  AnalysisResultLists.erase(ResultsListI);
752  }
753 
754  /// Clear all analysis results cached by this AnalysisManager.
755  ///
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();
763  }
764 
765  /// Get the result of an analysis pass for a given IR unit.
766  ///
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...);
774 
775  using ResultModelT =
776  detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
777  PreservedAnalyses, Invalidator>;
778 
779  return static_cast<ResultModelT &>(ResultConcept).Result;
780  }
781 
782  /// Get the cached result of an analysis pass for a given IR unit.
783  ///
784  /// This method never runs the analysis.
785  ///
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");
791 
792  ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
793  if (!ResultConcept)
794  return nullptr;
795 
796  using ResultModelT =
797  detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
798  PreservedAnalyses, Invalidator>;
799 
800  return &static_cast<ResultModelT *>(ResultConcept)->Result;
801  }
802 
803  /// Register an analysis pass with the manager.
804  ///
805  /// The parameter is a callable whose result is an analysis pass. This allows
806  /// passing in a lambda to construct the analysis.
807  ///
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.
813  ///
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...>;
826 
827  auto &PassPtr = AnalysisPasses[PassT::ID()];
828  if (PassPtr)
829  // Already registered this pass type!
830  return false;
831 
832  // Construct a new model around the instance returned by the builder.
833  PassPtr.reset(new PassModelT(PassBuilder()));
834  return true;
835  }
836 
837  /// Invalidate a specific analysis pass for an IR module.
838  ///
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);
845  }
846 
847  /// Invalidate cached analyses for an IR unit.
848  ///
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.
854  return;
855 
856  if (DebugLogging)
857  dbgs() << "Invalidating all non-preserved analyses for: " << IR.getName()
858  << "\n";
859 
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;
872 
873  auto IMapI = IsResultInvalidated.find(ID);
874  if (IMapI != IsResultInvalidated.end())
875  // This result was already handled via the Invalidator.
876  continue;
877 
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!");
889  }
890 
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;
898  }
899 
900  if (DebugLogging)
901  dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
902  << " on " << IR.getName() << "\n";
903 
904  I = ResultsList.erase(I);
905  AnalysisResults.erase({ID, &IR});
906  }
907  }
908 
909  if (ResultsList.empty())
910  AnalysisResultLists.erase(&IR);
911  }
912 
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;
920  }
921 
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;
928  }
929 
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()));
937 
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";
945 
947  if (ID != PassInstrumentationAnalysis::ID()) {
948  PI = getResult<PassInstrumentationAnalysis>(IR, ExtraArgs...);
949  PI.runBeforeAnalysis(P, IR);
950  }
951 
952  AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
953  ResultList.emplace_back(ID, P.run(IR, *this, ExtraArgs...));
954 
955  PI.runAfterAnalysis(P, IR);
956 
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!");
961 
962  RI->second = std::prev(ResultList.end());
963  }
964 
965  return *RI->second->second;
966  }
967 
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;
973  }
974 
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;
981 
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);
987  }
988 
989  /// Map type from module analysis pass ID to pass concept pointer.
990  using AnalysisPassMapT =
992 
993  /// Collection of module analysis passes, indexed by ID.
994  AnalysisPassMapT AnalysisPasses;
995 
996  /// Map from function to a list of function analysis results.
997  ///
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;
1001 
1002  /// Map from an analysis ID and function to a particular cached
1003  /// analysis result.
1004  AnalysisResultMapT AnalysisResults;
1005 
1006  /// Indicates whether we log to \c llvm::dbgs().
1007  bool DebugLogging;
1008 };
1009 
1010 extern template class AnalysisManager<Module>;
1011 
1012 /// Convenience typedef for the Module analysis manager.
1014 
1015 extern template class AnalysisManager<Function>;
1016 
1017 /// Convenience typedef for the Function analysis manager.
1019 
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.
1023 ///
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.
1029 ///
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.
1033 ///
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>
1038  : public AnalysisInfoMixin<
1039  InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
1040 public:
1041  class Result {
1042  public:
1043  explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
1044 
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;
1050  }
1051 
1053  // InnerAM is cleared in a moved from state where there is nothing to do.
1054  if (!InnerAM)
1055  return;
1056 
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();
1060  }
1061 
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;
1069  }
1070 
1071  /// Accessor for the analysis manager.
1072  AnalysisManagerT &getManager() { return *InnerAM; }
1073 
1074  /// Handler for invalidation of the outer IR unit, \c IRUnitT.
1075  ///
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.
1080  ///
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,
1087 
1088  private:
1089  AnalysisManagerT *InnerAM;
1090  };
1091 
1092  explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
1093  : InnerAM(&InnerAM) {}
1094 
1095  /// Run the analysis pass and create our proxy result object.
1096  ///
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.
1101  ExtraArgTs...) {
1102  return Result(*InnerAM);
1103  }
1104 
1105 private:
1106  friend AnalysisInfoMixin<
1108 
1109  static AnalysisKey Key;
1110 
1111  AnalysisManagerT *InnerAM;
1112 };
1113 
1114 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1116  InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1117 
1118 /// Provide the \c FunctionAnalysisManager to \c Module proxy.
1121 
1122 /// Specialization of the invalidate method for the \c
1123 /// FunctionAnalysisManagerModuleProxy's result.
1124 template <>
1126  Module &M, const PreservedAnalyses &PA,
1128 
1129 // Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
1130 // template.
1132  Module>;
1133 
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.
1137 ///
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.
1143 ///
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.
1147 ///
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>
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) {}
1161 
1162  const AnalysisManagerT &getManager() const { return *AM; }
1163 
1164  /// When invalidation occurs, remove any registered invalidation events.
1166  IRUnitT &IRUnit, const PreservedAnalyses &PA,
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.
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);
1179  }
1180 
1181  for (auto OuterID : DeadKeys)
1182  OuterAnalysisInvalidationMap.erase(OuterID);
1183 
1184  // The proxy itself remains valid regardless of anything else.
1185  return false;
1186  }
1187 
1188  /// Register a deferred invalidation event for when the outer analysis
1189  /// manager processes its invalidations.
1190  template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
1192  AnalysisKey *OuterID = OuterAnalysisT::ID();
1193  AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
1194 
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);
1204  }
1205 
1206  /// Access the map from outer analyses to deferred invalidation requiring
1207  /// analyses.
1210  return OuterAnalysisInvalidationMap;
1211  }
1212 
1213  private:
1214  const AnalysisManagerT *AM;
1215 
1216  /// A map from an outer analysis ID to the set of this IR-unit's analyses
1217  /// which need to be invalidated.
1219  OuterAnalysisInvalidationMap;
1220  };
1221 
1222  OuterAnalysisManagerProxy(const AnalysisManagerT &AM) : AM(&AM) {}
1223 
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.
1228  ExtraArgTs...) {
1229  return Result(*AM);
1230  }
1231 
1232 private:
1233  friend AnalysisInfoMixin<
1234  OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
1235 
1236  static AnalysisKey Key;
1237 
1238  const AnalysisManagerT *AM;
1239 };
1240 
1241 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1243  OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1244 
1245 extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
1246  Function>;
1247 /// Provide the \c ModuleAnalysisManager to \c Function proxy.
1250 
1251 /// Trivial adaptor that maps from a module to its functions.
1252 ///
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.
1256 ///
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.
1263 ///
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.
1270 ///
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>
1276  : public PassInfoMixin<ModuleToFunctionPassAdaptor<FunctionPassT>> {
1277 public:
1278  explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
1279  : Pass(std::move(Pass)) {}
1280 
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();
1285 
1286  // Request PassInstrumentation from analysis manager, will use it to run
1287  // instrumenting callbacks for the passes later.
1289 
1290  PreservedAnalyses PA = PreservedAnalyses::all();
1291  for (Function &F : M) {
1292  if (F.isDeclaration())
1293  continue;
1294 
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);
1301 
1302  PI.runAfterPass(Pass, F);
1303 
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);
1308 
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));
1312  }
1313 
1314  // The FunctionAnalysisManagerModuleProxy is preserved because (we assume)
1315  // the function passes we ran didn't add or remove any functions.
1316  //
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;
1322  }
1323 
1324 private:
1325  FunctionPassT Pass;
1326 };
1327 
1328 /// A function to deduce a function pass type and wrap it in the
1329 /// templated adaptor.
1330 template <typename FunctionPassT>
1333  return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
1334 }
1335 
1336 /// A utility pass template to force an analysis result to be available.
1337 ///
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.
1342 ///
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>
1349  : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
1350  ExtraArgTs...>> {
1351  /// Run this pass over some unit of IR.
1352  ///
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)...);
1361 
1362  return PreservedAnalyses::all();
1363  }
1364 };
1365 
1366 /// A no-op pass template which simply forces a specific analysis result
1367 /// to be invalidated.
1368 template <typename AnalysisT>
1370  : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
1371  /// Run this pass over some unit of IR.
1372  ///
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;
1382  }
1383 };
1384 
1385 /// A utility pass that does nothing, but preserves no analyses.
1386 ///
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();
1394  }
1395 };
1396 
1397 /// A utility pass template that simply runs another pass multiple times.
1398 ///
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)) {}
1405 
1406  template <typename IRUnitT, typename AnalysisManagerT, typename... Ts>
1407  PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, Ts &&... Args) {
1408 
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...));
1416 
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);
1426  }
1427  return PA;
1428  }
1429 
1430 private:
1431  int Count;
1432  PassT P;
1433 };
1434 
1435 template <typename PassT>
1437  return RepeatedPass<PassT>(Count, std::move(P));
1438 }
1439 
1440 } // end namespace llvm
1441 
1442 #endif // LLVM_IR_PASSMANAGER_H
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:80
void abandon()
Mark an analysis as abandoned.
Definition: PassManager.h:207
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
Definition: PassManager.h:659
Wrapper to model the analysis pass concept.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:769
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void intersect(const PreservedAnalyses &Arg)
Intersect this set with another in place.
Definition: PassManager.h:225
Trivial adaptor that maps from a module to its functions.
Definition: PassManager.h:1275
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
bool invalidate(IRUnitT &IRUnit, const PreservedAnalyses &PA, typename AnalysisManager< IRUnitT, ExtraArgTs... >::Invalidator &Inv)
When invalidation occurs, remove any registered invalidation events.
Definition: PassManager.h:1165
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
void clear(IRUnitT &IR, llvm::StringRef Name)
Clear any cached analysis results for a single unit of IR.
Definition: PassManager.h:739
PassManager(bool DebugLogging=false)
Construct a pass manager.
Definition: PassManager.h:463
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA, typename AnalysisManager< IRUnitT, ExtraArgTs... >::Invalidator &Inv)
Handler for invalidation of the outer IR unit, IRUnitT.
RepeatedPass< PassT > createRepeatedPass(int Count, PassT P)
Definition: PassManager.h:1436
RepeatedPass(int Count, PassT P)
Definition: PassManager.h:1404
Function Alias Analysis Results
Template for the abstract base class used to dispatch polymorphically over pass objects.
unsigned second
F(f)
A utility pass template that simply runs another pass multiple times.
Definition: PassManager.h:1402
PassT::Result getAnalysisResult(AnalysisManager< IRUnitT, AnalysisArgTs... > &AM, IRUnitT &IR, std::tuple< MainArgTs... > Args)
Helper for partial unpacking of extra arguments in getAnalysisResult.
Definition: PassManager.h:427
A utility pass template to force an analysis result to be available.
Definition: PassManager.h:1348
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
Definition: PassManager.h:481
Abstract concept of an analysis pass.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: PassManager.h:304
OuterAnalysisManagerProxy(const AnalysisManagerT &AM)
Definition: PassManager.h:1222
Definition: BitVector.h:937
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:620
static AnalysisKey * ID()
Returns an opaque, unique ID for this analysis type.
Definition: PassManager.h:398
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:821
This class provides access to building LLVM&#39;s passes.
Definition: PassBuilder.h:75
Alias for the common case of a sequence of size_ts.
Definition: STLExtras.h:526
AnalysisManagerT & getManager()
Accessor for the analysis manager.
Definition: PassManager.h:1072
bool empty() const
Returns true if the analysis manager has an empty results cache.
Definition: PassManager.h:727
Key
PAL metadata keys.
PassManager(PassManager &&Arg)
Definition: PassManager.h:469
AnalysisManager(bool DebugLogging=false)
Construct an empty analysis manager.
Definition: PassManager.h:722
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:365
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
bool runBeforePass(const PassT &Pass, const IRUnitT &IR) const
BeforePass instrumentation point - takes Pass instance to be executed and constant reference to IR it...
void registerOuterAnalysisInvalidation()
Register a deferred invalidation event for when the outer analysis manager processes its invalidation...
Definition: PassManager.h:1191
static PreservedAnalyses allInSet()
Construct a preserved analyses object with a single preserved set.
Definition: PassManager.h:167
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1251
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
A checker object that makes it easy to query for whether an analysis or some set covering it is prese...
Definition: PassManager.h:267
Result run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...)
Definition: PassManager.h:590
#define P(N)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
bool areAllPreserved() const
Test whether all analyses are preserved (and none are abandoned).
Definition: PassManager.h:321
InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
Definition: PassManager.h:1092
ModuleToFunctionPassAdaptor< FunctionPassT > createModuleToFunctionPassAdaptor(FunctionPassT Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
Definition: PassManager.h:1332
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
PassT::Result getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR, std::tuple< ArgTs... > Args, llvm::index_sequence< Ns... >)
Actual unpacker of extra arguments in getAnalysisResult, passes only those tuple arguments that are m...
Definition: PassManager.h:412
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:382
Wrapper to model the analysis result concept.
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:285
bool preservedSet()
Returns true if the checker&#39;s analysis was not abandoned and either.
Definition: PassManager.h:292
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, Ts &&... Args)
Definition: PassManager.h:1407
void clear()
Clear all analysis results cached by this AnalysisManager.
Definition: PassManager.h:760
PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...)
Run this pass over some unit of IR.
Definition: PassManager.h:1392
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Definition: PassManager.h:1018
static StringRef name()
Gets the name of the pass we are mixed into.
Definition: PassManager.h:367
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1225
PreservedAnalysisChecker getChecker(AnalysisKey *ID) const
Build a checker for this PreservedAnalyses and the specified analysis ID.
Definition: PassManager.h:313
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
void intersect(PreservedAnalyses &&Arg)
Intersect this set with a temporary other set in place.
Definition: PassManager.h:247
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
PassManager & operator=(PassManager &&RHS)
Definition: PassManager.h:473
Result proxy object for OuterAnalysisManagerProxy.
Definition: PassManager.h:1158
ModuleToFunctionPassAdaptor(FunctionPassT Pass)
Definition: PassManager.h:1278
Pseudo-analysis pass that exposes the PassInstrumentation to pass managers.
Definition: PassManager.h:574
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition: PassManager.h:1013
print lazy value Lazy Value Info Printer Pass
static AnalysisSetKey * ID()
Definition: PassManager.h:116
void runAfterPass(const PassT &Pass, const IRUnitT &IR) const
AfterPass instrumentation point - takes Pass instance that has just been executed and constant refere...
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:1153
A template wrapper used to implement the polymorphic API.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
Module.h This file contains the declarations for the Module class.
Result run(IRUnitT &IR, AnalysisManager< IRUnitT, ExtraArgTs... > &AM, ExtraArgTs...)
Run the analysis pass and create our proxy result object.
Definition: PassManager.h:1100
Creates a compile-time integer sequence for a parameter pack.
Definition: STLExtras.h:528
void invalidate(IRUnitT &IR)
Invalidate a specific analysis pass for an IR module.
Definition: PassManager.h:841
Abstract concept of an analysis result.
A utility pass that does nothing, but preserves no analyses.
Definition: PassManager.h:1389
Result run(IRUnitT &, AnalysisManager< IRUnitT, ExtraArgTs... > &, ExtraArgTs...)
Run the analysis pass and create our proxy result object.
Definition: PassManager.h:1227
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Result(AnalysisManagerT &InnerAM)
Definition: PassManager.h:1043
static AnalysisSetKey * ID()
Definition: PassManager.h:93
This header provides internal APIs and implementation details used by the pass management interfaces ...
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:114
bool allAnalysesInSetPreserved(AnalysisSetKey *SetID) const
Directly test whether a set of analyses is preserved.
Definition: PassManager.h:336
void abandon(AnalysisKey *ID)
Mark an analysis as abandoned using its ID.
Definition: PassManager.h:216
void preserveSet(AnalysisSetKey *ID)
Mark an analysis set as preserved using its ID.
Definition: PassManager.h:194
A special type used to provide an address that identifies a set of related analyses.
Definition: PassManager.h:80
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:457
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Runs the function pass across every function in the module.
Definition: PassManager.h:1282
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:189
#define I(x, y, z)
Definition: MD5.cpp:58
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:788
uint32_t Size
Definition: Profile.cpp:46
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:174
PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&... Args)
Run this pass over some unit of IR.
Definition: PassManager.h:1357
A no-op pass template which simply forces a specific analysis result to be invalidated.
Definition: PassManager.h:1369
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:211
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:641
bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA)
A type-erased variant of the above invalidate method with the same core API other than passing an ana...
Definition: PassManager.h:673
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over <a particular IR unit>" (e...
Definition: PassManager.h:91
void runBeforeAnalysis(const PassT &Analysis, const IRUnitT &IR) const
BeforeAnalysis instrumentation point - takes Analysis instance to be executed and constant reference ...
PassInstrumentationAnalysis(PassInstrumentationCallbacks *Callbacks=nullptr)
PassInstrumentationCallbacks object is shared, owned by something else, not this analysis.
Definition: PassManager.h:584
void preserve(AnalysisKey *ID)
Given an analysis&#39;s ID, mark the analysis as preserved, adding it to the set.
Definition: PassManager.h:178
bool preserved()
Returns true if the checker&#39;s analysis was not abandoned and either.
Definition: PassManager.h:284
Result(const AnalysisManagerT &AM)
Definition: PassManager.h:1160
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A container for analyses that lazily runs them and caches their results.
This class provides instrumentation entry points for the Pass Manager, doing calls to callbacks regis...
void addPass(PassT Pass)
Definition: PassManager.h:541
const SmallDenseMap< AnalysisKey *, TinyPtrVector< AnalysisKey * >, 2 > & getOuterInvalidations() const
Access the map from outer analyses to deferred invalidation requiring analyses.
Definition: PassManager.h:1209
PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...)
Run this pass over some unit of IR.
Definition: PassManager.h:1378
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
Definition: PassManager.h:851
const AnalysisManagerT & getManager() const
Definition: PassManager.h:1162
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
Statically lint checks LLVM IR
Definition: Lint.cpp:192
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool allAnalysesInSetPreserved() const
Directly test whether a set of analyses is preserved.
Definition: PassManager.h:329
void runAfterAnalysis(const PassT &Analysis, const IRUnitT &IR) const
AfterAnalysis instrumentation point - takes Analysis instance that has just been executed and constan...
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:1037