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/STLExtras.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/StringRef.h"
44#include "llvm/ADT/TinyPtrVector.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/Module.h"
47#include "llvm/IR/PassInstrumentation.h"
48#include "llvm/IR/PassManagerInternal.h"
49#include "llvm/Support/TimeProfiler.h"
50#include "llvm/Support/TypeName.h"
51#include <cassert>
52#include <cstring>
53#include <iterator>
54#include <list>
55#include <memory>
56#include <tuple>
57#include <type_traits>
58#include <utility>
59#include <vector>
60
61namespace llvm {
62
63/// A special type used by analysis passes to provide an address that
64/// identifies that particular analysis pass type.
65///
66/// Analysis passes should have a static data member of this type and derive
67/// from the \c AnalysisInfoMixin to get a static ID method used to identify
68/// the analysis in the pass management infrastructure.
69struct alignas(8) AnalysisKey {};
70
71/// A special type used to provide an address that identifies a set of related
72/// analyses. These sets are primarily used below to mark sets of analyses as
73/// preserved.
74///
75/// For example, a transformation can indicate that it preserves the CFG of a
76/// function by preserving the appropriate AnalysisSetKey. An analysis that
77/// depends only on the CFG can then check if that AnalysisSetKey is preserved;
78/// if it is, the analysis knows that it itself is preserved.
79struct alignas(8) AnalysisSetKey {};
80
81/// This templated class represents "all analyses that operate over \<a
82/// particular IR unit\>" (e.g. a Function or a Module) in instances of
83/// PreservedAnalysis.
84///
85/// This lets a transformation say e.g. "I preserved all function analyses".
86///
87/// Note that you must provide an explicit instantiation declaration and
88/// definition for this template in order to get the correct behavior on
89/// Windows. Otherwise, the address of SetKey will not be stable.
90template <typename IRUnitT> class AllAnalysesOn {
91public:
92 static AnalysisSetKey *ID() { return &SetKey; }
93
94private:
95 static AnalysisSetKey SetKey;
96};
97
98template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;
99
100extern template class AllAnalysesOn<Module>;
101extern template class AllAnalysesOn<Function>;
102
103/// Represents analyses that only rely on functions' control flow.
104///
105/// This can be used with \c PreservedAnalyses to mark the CFG as preserved and
106/// to query whether it has been preserved.
107///
108/// The CFG of a function is defined as the set of basic blocks and the edges
109/// between them. Changing the set of basic blocks in a function is enough to
110/// mutate the CFG. Mutating the condition of a branch or argument of an
111/// invoked function does not mutate the CFG, but changing the successor labels
112/// of those instructions does.
113class CFGAnalyses {
114public:
115 static AnalysisSetKey *ID() { return &SetKey; }
116
117private:
118 static AnalysisSetKey SetKey;
119};
120
121/// A set of analyses that are preserved following a run of a transformation
122/// pass.
123///
124/// Transformation passes build and return these objects to communicate which
125/// analyses are still valid after the transformation. For most passes this is
126/// fairly simple: if they don't change anything all analyses are preserved,
127/// otherwise only a short list of analyses that have been explicitly updated
128/// are preserved.
129///
130/// This class also lets transformation passes mark abstract *sets* of analyses
131/// as preserved. A transformation that (say) does not alter the CFG can
132/// indicate such by marking a particular AnalysisSetKey as preserved, and
133/// then analyses can query whether that AnalysisSetKey is preserved.
134///
135/// Finally, this class can represent an "abandoned" analysis, which is
136/// not preserved even if it would be covered by some abstract set of analyses.
137///
138/// Given a `PreservedAnalyses` object, an analysis will typically want to
139/// figure out whether it is preserved. In the example below, MyAnalysisType is
140/// preserved if it's not abandoned, and (a) it's explicitly marked as
141/// preserved, (b), the set AllAnalysesOn<MyIRUnit> is preserved, or (c) both
142/// AnalysisSetA and AnalysisSetB are preserved.
143///
144/// ```
145/// auto PAC = PA.getChecker<MyAnalysisType>();
146/// if (PAC.preserved() || PAC.preservedSet<AllAnalysesOn<MyIRUnit>>() ||
147/// (PAC.preservedSet<AnalysisSetA>() &&
148/// PAC.preservedSet<AnalysisSetB>())) {
149/// // The analysis has been successfully preserved ...
150/// }
151/// ```
152class PreservedAnalyses {
153public:
154 /// Convenience factory function for the empty preserved set.
155 static PreservedAnalyses none() { return PreservedAnalyses(); }
156
157 /// Construct a special preserved set that preserves all passes.
158 static PreservedAnalyses all() {
159 PreservedAnalyses PA;
160 PA.PreservedIDs.insert(&AllAnalysesKey);
161 return PA;
162 }
163
164 /// Construct a preserved analyses object with a single preserved set.
165 template <typename AnalysisSetT>
166 static PreservedAnalyses allInSet() {
167 PreservedAnalyses PA;
168 PA.preserveSet<AnalysisSetT>();
169 return PA;
170 }
171
172 /// Mark an analysis as preserved.
173 template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); }
174
175 /// Given an analysis's ID, mark the analysis as preserved, adding it
176 /// to the set.
177 void preserve(AnalysisKey *ID) {
178 // Clear this ID from the explicit not-preserved set if present.
179 NotPreservedAnalysisIDs.erase(ID);
180
181 // If we're not already preserving all analyses (other than those in
182 // NotPreservedAnalysisIDs).
183 if (!areAllPreserved())
184 PreservedIDs.insert(ID);
185 }
186
187 /// Mark an analysis set as preserved.
188 template <typename AnalysisSetT> void preserveSet() {
189 preserveSet(AnalysisSetT::ID());
190 }
191
192 /// Mark an analysis set as preserved using its ID.
193 void preserveSet(AnalysisSetKey *ID) {
194 // If we're not already in the saturated 'all' state, add this set.
195 if (!areAllPreserved())
196 PreservedIDs.insert(ID);
197 }
198
199 /// Mark an analysis as abandoned.
200 ///
201 /// An abandoned analysis is not preserved, even if it is nominally covered
202 /// by some other set or was previously explicitly marked as preserved.
203 ///
204 /// Note that you can only abandon a specific analysis, not a *set* of
205 /// analyses.
206 template <typename AnalysisT> void abandon() { abandon(AnalysisT::ID()); }
207
208 /// Mark an analysis as abandoned using its ID.
209 ///
210 /// An abandoned analysis is not preserved, even if it is nominally covered
211 /// by some other set or was previously explicitly marked as preserved.
212 ///
213 /// Note that you can only abandon a specific analysis, not a *set* of
214 /// analyses.
215 void abandon(AnalysisKey *ID) {
216 PreservedIDs.erase(ID);
217 NotPreservedAnalysisIDs.insert(ID);
218 }
219
220 /// Intersect this set with another in place.
221 ///
222 /// This is a mutating operation on this preserved set, removing all
223 /// preserved passes which are not also preserved in the argument.
224 void intersect(const PreservedAnalyses &Arg) {
225 if (Arg.areAllPreserved())
226 return;
227 if (areAllPreserved()) {
228 *this = Arg;
229 return;
230 }
231 // The intersection requires the *union* of the explicitly not-preserved
232 // IDs and the *intersection* of the preserved IDs.
233 for (auto *ID : Arg.NotPreservedAnalysisIDs) {
234 PreservedIDs.erase(ID);
235 NotPreservedAnalysisIDs.insert(ID);
236 }
237 for (auto *ID : PreservedIDs)
238 if (!Arg.PreservedIDs.count(ID))
239 PreservedIDs.erase(ID);
240 }
241
242 /// Intersect this set with a temporary other set in place.
243 ///
244 /// This is a mutating operation on this preserved set, removing all
245 /// preserved passes which are not also preserved in the argument.
246 void intersect(PreservedAnalyses &&Arg) {
247 if (Arg.areAllPreserved())
248 return;
249 if (areAllPreserved()) {
250 *this = std::move(Arg);
251 return;
252 }
253 // The intersection requires the *union* of the explicitly not-preserved
254 // IDs and the *intersection* of the preserved IDs.
255 for (auto *ID : Arg.NotPreservedAnalysisIDs) {
256 PreservedIDs.erase(ID);
257 NotPreservedAnalysisIDs.insert(ID);
258 }
259 for (auto *ID : PreservedIDs)
260 if (!Arg.PreservedIDs.count(ID))
261 PreservedIDs.erase(ID);
262 }
263
264 /// A checker object that makes it easy to query for whether an analysis or
265 /// some set covering it is preserved.
266 class PreservedAnalysisChecker {
267 friend class PreservedAnalyses;
268
269 const PreservedAnalyses &PA;
270 AnalysisKey *const ID;
271 const bool IsAbandoned;
272
273 /// A PreservedAnalysisChecker is tied to a particular Analysis because
274 /// `preserved()` and `preservedSet()` both return false if the Analysis
275 /// was abandoned.
276 PreservedAnalysisChecker(const PreservedAnalyses &PA, AnalysisKey *ID)
277 : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {}
278
279 public:
280 /// Returns true if the checker's analysis was not abandoned and either
281 /// - the analysis is explicitly preserved or
282 /// - all analyses are preserved.
283 bool preserved() {
284 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
285 PA.PreservedIDs.count(ID));
286 }
287
288 /// Return true if the checker's analysis was not abandoned, i.e. it was not
289 /// explicitly invalidated. Even if the analysis is not explicitly
290 /// preserved, if the analysis is known stateless, then it is preserved.
291 bool preservedWhenStateless() {
292 return !IsAbandoned;
293 }
294
295 /// Returns true if the checker's analysis was not abandoned and either
296 /// - \p AnalysisSetT is explicitly preserved or
297 /// - all analyses are preserved.
298 template <typename AnalysisSetT> bool preservedSet() {
299 AnalysisSetKey *SetID = AnalysisSetT::ID();
300 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
301 PA.PreservedIDs.count(SetID));
302 }
303 };
304
305 /// Build a checker for this `PreservedAnalyses` and the specified analysis
306 /// type.
307 ///
308 /// You can use the returned object to query whether an analysis was
309 /// preserved. See the example in the comment on `PreservedAnalysis`.
310 template <typename AnalysisT> PreservedAnalysisChecker getChecker() const {
311 return PreservedAnalysisChecker(*this, AnalysisT::ID());
312 }
313
314 /// Build a checker for this `PreservedAnalyses` and the specified analysis
315 /// ID.
316 ///
317 /// You can use the returned object to query whether an analysis was
318 /// preserved. See the example in the comment on `PreservedAnalysis`.
319 PreservedAnalysisChecker getChecker(AnalysisKey *ID) const {
320 return PreservedAnalysisChecker(*this, ID);
321 }
322
323 /// Test whether all analyses are preserved (and none are abandoned).
324 ///
325 /// This is used primarily to optimize for the common case of a transformation
326 /// which makes no changes to the IR.
327 bool areAllPreserved() const {
328 return NotPreservedAnalysisIDs.empty() &&
329 PreservedIDs.count(&AllAnalysesKey);
330 }
331
332 /// Directly test whether a set of analyses is preserved.
333 ///
334 /// This is only true when no analyses have been explicitly abandoned.
335 template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const {
336 return allAnalysesInSetPreserved(AnalysisSetT::ID());
337 }
338
339 /// Directly test whether a set of analyses is preserved.
340 ///
341 /// This is only true when no analyses have been explicitly abandoned.
342 bool allAnalysesInSetPreserved(AnalysisSetKey *SetID) const {
343 return NotPreservedAnalysisIDs.empty() &&
344 (PreservedIDs.count(&AllAnalysesKey) || PreservedIDs.count(SetID));
345 }
346
347private:
348 /// A special key used to indicate all analyses.
349 static AnalysisSetKey AllAnalysesKey;
350
351 /// The IDs of analyses and analysis sets that are preserved.
352 SmallPtrSet<void *, 2> PreservedIDs;
353
354 /// The IDs of explicitly not-preserved analyses.
355 ///
356 /// If an analysis in this set is covered by a set in `PreservedIDs`, we
357 /// consider it not-preserved. That is, `NotPreservedAnalysisIDs` always
358 /// "wins" over analysis sets in `PreservedIDs`.
359 ///
360 /// Also, a given ID should never occur both here and in `PreservedIDs`.
361 SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs;
362};
363
364// Forward declare the analysis manager template.
365template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
366
367/// A CRTP mix-in to automatically provide informational APIs needed for
368/// passes.
369///
370/// This provides some boilerplate for types that are passes.
371template <typename DerivedT> struct PassInfoMixin {
372 /// Gets the name of the pass we are mixed into.
373 static StringRef name() {
374 static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value,
375 "Must pass the derived type as the template argument!");
376 StringRef Name = getTypeName<DerivedT>();
377 Name.consume_front("llvm::");
378 return Name;
379 }
380
381 void printPipeline(raw_ostream &OS,
382 function_ref<StringRef(StringRef)> MapClassName2PassName) {
383 StringRef ClassName = DerivedT::name();
384 auto PassName = MapClassName2PassName(ClassName);
385 OS << PassName;
386 }
387};
388
389/// A CRTP mix-in that provides informational APIs needed for analysis passes.
390///
391/// This provides some boilerplate for types that are analysis passes. It
392/// automatically mixes in \c PassInfoMixin.
393template <typename DerivedT>
394struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
395 /// Returns an opaque, unique ID for this analysis type.
396 ///
397 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
398 /// suitable for use in sets, maps, and other data structures that use the low
399 /// bits of pointers.
400 ///
401 /// Note that this requires the derived type provide a static \c AnalysisKey
402 /// member called \c Key.
403 ///
404 /// FIXME: The only reason the mixin type itself can't declare the Key value
405 /// is that some compilers cannot correctly unique a templated static variable
406 /// so it has the same addresses in each instantiation. The only currently
407 /// known platform with this limitation is Windows DLL builds, specifically
408 /// building each part of LLVM as a DLL. If we ever remove that build
409 /// configuration, this mixin can provide the static key as well.
410 static AnalysisKey *ID() {
411 static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
412 "Must pass the derived type as the template argument!");
413 return &DerivedT::Key;
414 }
415};
416
417namespace detail {
418
419/// Actual unpacker of extra arguments in getAnalysisResult,
420/// passes only those tuple arguments that are mentioned in index_sequence.
421template <typename PassT, typename IRUnitT, typename AnalysisManagerT,
422 typename... ArgTs, size_t... Ns>
423typename PassT::Result
424getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR,
425 std::tuple<ArgTs...> Args,
426 std::index_sequence<Ns...>) {
427 (void)Args;
428 return AM.template getResult<PassT>(IR, std::get<Ns>(Args)...);
429}
430
431/// Helper for *partial* unpacking of extra arguments in getAnalysisResult.
432///
433/// Arguments passed in tuple come from PassManager, so they might have extra
434/// arguments after those AnalysisManager's ExtraArgTs ones that we need to
435/// pass to getResult.
436template <typename PassT, typename IRUnitT, typename... AnalysisArgTs,
437 typename... MainArgTs>
438typename PassT::Result
439getAnalysisResult(AnalysisManager<IRUnitT, AnalysisArgTs...> &AM, IRUnitT &IR,
440 std::tuple<MainArgTs...> Args) {
441 return (getAnalysisResultUnpackTuple<
442 PassT, IRUnitT>)(AM, IR, Args,
443 std::index_sequence_for<AnalysisArgTs...>{});
444}
445
446} // namespace detail
447
448// Forward declare the pass instrumentation analysis explicitly queried in
449// generic PassManager code.
450// FIXME: figure out a way to move PassInstrumentationAnalysis into its own
451// header.
452class PassInstrumentationAnalysis;
453
454/// Manages a sequence of passes over a particular unit of IR.
455///
456/// A pass manager contains a sequence of passes to run over a particular unit
457/// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
458/// IR, and when run over some given IR will run each of its contained passes in
459/// sequence. Pass managers are the primary and most basic building block of a
460/// pass pipeline.
461///
462/// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
463/// argument. The pass manager will propagate that analysis manager to each
464/// pass it runs, and will call the analysis manager's invalidation routine with
465/// the PreservedAnalyses of each pass it runs.
466template <typename IRUnitT,
467 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
468 typename... ExtraArgTs>
469class PassManager : public PassInfoMixin<
470 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
471public:
472 /// Construct a pass manager.
473 explicit PassManager() = default;
474
475 // FIXME: These are equivalent to the default move constructor/move
476 // assignment. However, using = default triggers linker errors due to the
477 // explicit instantiations below. Find away to use the default and remove the
478 // duplicated code here.
479 PassManager(PassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
480
481 PassManager &operator=(PassManager &&RHS) {
482 Passes = std::move(RHS.Passes);
483 return *this;
484 }
485
486 void printPipeline(raw_ostream &OS,
487 function_ref<StringRef(StringRef)> MapClassName2PassName) {
488 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
489 auto *P = Passes[Idx].get();
490 P->printPipeline(OS, MapClassName2PassName);
491 if (Idx + 1 < Size)
492 OS << ",";
493 }
494 }
495
496 /// Run all of the passes in this manager over the given unit of IR.
497 /// ExtraArgs are passed to each pass.
498 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
499 ExtraArgTs... ExtraArgs) {
500 PreservedAnalyses PA = PreservedAnalyses::all();
501
502 // Request PassInstrumentation from analysis manager, will use it to run
503 // instrumenting callbacks for the passes later.
504 // Here we use std::tuple wrapper over getResult which helps to extract
505 // AnalysisManager's arguments out of the whole ExtraArgs set.
506 PassInstrumentation PI =
507 detail::getAnalysisResult<PassInstrumentationAnalysis>(
508 AM, IR, std::tuple<ExtraArgTs...>(ExtraArgs...));
509
510 for (auto &Pass : Passes) {
511 // Check the PassInstrumentation's BeforePass callbacks before running the
512 // pass, skip its execution completely if asked to (callback returns
513 // false).
514 if (!PI.runBeforePass<IRUnitT>(*Pass, IR))
515 continue;
516
517 PreservedAnalyses PassPA;
518 {
519 TimeTraceScope TimeScope(Pass->name(), IR.getName());
520 PassPA = Pass->run(IR, AM, ExtraArgs...);
521 }
522
523 // Call onto PassInstrumentation's AfterPass callbacks immediately after
524 // running the pass.
525 PI.runAfterPass<IRUnitT>(*Pass, IR, PassPA);
526
527 // Update the analysis manager as each pass runs and potentially
528 // invalidates analyses.
529 AM.invalidate(IR, PassPA);
530
531 // Finally, intersect the preserved analyses to compute the aggregate
532 // preserved set for this pass manager.
533 PA.intersect(std::move(PassPA));
534 }
535
536 // Invalidation was handled after each pass in the above loop for the
537 // current unit of IR. Therefore, the remaining analysis results in the
538 // AnalysisManager are preserved. We mark this with a set so that we don't
539 // need to inspect each one individually.
540 PA.preserveSet<AllAnalysesOn<IRUnitT>>();
541
542 return PA;
543 }
544
545 template <typename PassT>
546 LLVM_ATTRIBUTE_MINSIZE
547 std::enable_if_t<!std::is_same<PassT, PassManager>::value>
548 addPass(PassT &&Pass) {
549 using PassModelT =
550 detail::PassModel<IRUnitT, PassT, PreservedAnalyses, AnalysisManagerT,
551 ExtraArgTs...>;
552 // Do not use make_unique or emplace_back, they cause too many template
553 // instantiations, causing terrible compile times.
554 Passes.push_back(std::unique_ptr<PassConceptT>(
555 new PassModelT(std::forward<PassT>(Pass))));
556 }
557
558 /// When adding a pass manager pass that has the same type as this pass
559 /// manager, simply move the passes over. This is because we don't have use
560 /// cases rely on executing nested pass managers. Doing this could reduce
561 /// implementation complexity and avoid potential invalidation issues that may
562 /// happen with nested pass managers of the same type.
563 template <typename PassT>
564 LLVM_ATTRIBUTE_MINSIZE
565 std::enable_if_t<std::is_same<PassT, PassManager>::value>
566 addPass(PassT &&Pass) {
567 for (auto &P : Pass.Passes)
568 Passes.push_back(std::move(P));
569 }
570
571 /// Returns if the pass manager contains any passes.
572 bool isEmpty() const { return Passes.empty(); }
573
574 static bool isRequired() { return true; }
575
576protected:
577 using PassConceptT =
578 detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>;
579
580 std::vector<std::unique_ptr<PassConceptT>> Passes;
581};
582
583extern template class PassManager<Module>;
584
585/// Convenience typedef for a pass manager over modules.
586using ModulePassManager = PassManager<Module>;
587
588extern template class PassManager<Function>;
589
590/// Convenience typedef for a pass manager over functions.
591using FunctionPassManager = PassManager<Function>;
592
593/// Pseudo-analysis pass that exposes the \c PassInstrumentation to pass
594/// managers. Goes before AnalysisManager definition to provide its
595/// internals (e.g PassInstrumentationAnalysis::ID) for use there if needed.
596/// FIXME: figure out a way to move PassInstrumentationAnalysis into its own
597/// header.
598class PassInstrumentationAnalysis
599 : public AnalysisInfoMixin<PassInstrumentationAnalysis> {
600 friend AnalysisInfoMixin<PassInstrumentationAnalysis>;
601 static AnalysisKey Key;
602
603 PassInstrumentationCallbacks *Callbacks;
604
605public:
606 /// PassInstrumentationCallbacks object is shared, owned by something else,
607 /// not this analysis.
608 PassInstrumentationAnalysis(PassInstrumentationCallbacks *Callbacks = nullptr)
609 : Callbacks(Callbacks) {}
610
611 using Result = PassInstrumentation;
612
613 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
614 Result run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
615 return PassInstrumentation(Callbacks);
616 }
617};
618
619/// A container for analyses that lazily runs them and caches their
620/// results.
621///
622/// This class can manage analyses for any IR unit where the address of the IR
623/// unit sufficies as its identity.
624template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
625public:
626 class Invalidator;
627
628private:
629 // Now that we've defined our invalidator, we can define the concept types.
630 using ResultConceptT =
631 detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>;
632 using PassConceptT =
633 detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator,
634 ExtraArgTs...>;
635
636 /// List of analysis pass IDs and associated concept pointers.
637 ///
638 /// Requires iterators to be valid across appending new entries and arbitrary
639 /// erases. Provides the analysis ID to enable finding iterators to a given
640 /// entry in maps below, and provides the storage for the actual result
641 /// concept.
642 using AnalysisResultListT =
643 std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>;
644
645 /// Map type from IRUnitT pointer to our custom list type.
646 using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>;
647
648 /// Map type from a pair of analysis ID and IRUnitT pointer to an
649 /// iterator into a particular result list (which is where the actual analysis
650 /// result is stored).
651 using AnalysisResultMapT =
652 DenseMap<std::pair<AnalysisKey *, IRUnitT *>,
653 typename AnalysisResultListT::iterator>;
654
655public:
656 /// API to communicate dependencies between analyses during invalidation.
657 ///
658 /// When an analysis result embeds handles to other analysis results, it
659 /// needs to be invalidated both when its own information isn't preserved and
660 /// when any of its embedded analysis results end up invalidated. We pass an
661 /// \c Invalidator object as an argument to \c invalidate() in order to let
662 /// the analysis results themselves define the dependency graph on the fly.
663 /// This lets us avoid building an explicit representation of the
664 /// dependencies between analysis results.
665 class Invalidator {
666 public:
667 /// Trigger the invalidation of some other analysis pass if not already
668 /// handled and return whether it was in fact invalidated.
669 ///
670 /// This is expected to be called from within a given analysis result's \c
671 /// invalidate method to trigger a depth-first walk of all inter-analysis
672 /// dependencies. The same \p IR unit and \p PA passed to that result's \c
673 /// invalidate method should in turn be provided to this routine.
674 ///
675 /// The first time this is called for a given analysis pass, it will call
676 /// the corresponding result's \c invalidate method. Subsequent calls will
677 /// use a cache of the results of that initial call. It is an error to form
678 /// cyclic dependencies between analysis results.
679 ///
680 /// This returns true if the given analysis's result is invalid. Any
681 /// dependecies on it will become invalid as a result.
682 template <typename PassT>
683 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
684 using ResultModelT =
685 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
686 PreservedAnalyses, Invalidator>;
687
688 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
689 }
690
691 /// A type-erased variant of the above invalidate method with the same core
692 /// API other than passing an analysis ID rather than an analysis type
693 /// parameter.
694 ///
695 /// This is sadly less efficient than the above routine, which leverages
696 /// the type parameter to avoid the type erasure overhead.
697 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
698 return invalidateImpl<>(ID, IR, PA);
699 }
700
701 private:
702 friend class AnalysisManager;
703
704 template <typename ResultT = ResultConceptT>
705 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
706 const PreservedAnalyses &PA) {
707 // If we've already visited this pass, return true if it was invalidated
708 // and false otherwise.
709 auto IMapI = IsResultInvalidated.find(ID);
710 if (IMapI != IsResultInvalidated.end())
711 return IMapI->second;
712
713 // Otherwise look up the result object.
714 auto RI = Results.find({ID, &IR});
715 assert(RI != Results.end() &&
716 "Trying to invalidate a dependent result that isn't in the "
717 "manager's cache is always an error, likely due to a stale result "
718 "handle!");
719
720 auto &Result = static_cast<ResultT &>(*RI->second->second);
721
722 // Insert into the map whether the result should be invalidated and return
723 // that. Note that we cannot reuse IMapI and must do a fresh insert here,
724 // as calling invalidate could (recursively) insert things into the map,
725 // making any iterator or reference invalid.
726 bool Inserted;
727 std::tie(IMapI, Inserted) =
728 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
729 (void)Inserted;
730 assert(Inserted && "Should not have already inserted this ID, likely "
731 "indicates a dependency cycle!");
732 return IMapI->second;
733 }
734
735 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
736 const AnalysisResultMapT &Results)
737 : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
738
739 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
740 const AnalysisResultMapT &Results;
741 };
742
743 /// Construct an empty analysis manager.
744 AnalysisManager();
745 AnalysisManager(AnalysisManager &&);
746 AnalysisManager &operator=(AnalysisManager &&);
747
748 /// Returns true if the analysis manager has an empty results cache.
749 bool empty() const {
750 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
751 "The storage and index of analysis results disagree on how many "
752 "there are!");
753 return AnalysisResults.empty();
754 }
755
756 /// Clear any cached analysis results for a single unit of IR.
757 ///
758 /// This doesn't invalidate, but instead simply deletes, the relevant results.
759 /// It is useful when the IR is being removed and we want to clear out all the
760 /// memory pinned for it.
761 void clear(IRUnitT &IR, llvm::StringRef Name);
762
763 /// Clear all analysis results cached by this AnalysisManager.
764 ///
765 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
766 /// deletes them. This lets you clean up the AnalysisManager when the set of
767 /// IR units itself has potentially changed, and thus we can't even look up a
768 /// a result and invalidate/clear it directly.
769 void clear() {
770 AnalysisResults.clear();
771 AnalysisResultLists.clear();
772 }
773
774 /// Get the result of an analysis pass for a given IR unit.
775 ///
776 /// Runs the analysis if a cached result is not available.
777 template <typename PassT>
778 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
779 assert(AnalysisPasses.count(PassT::ID()) &&
780 "This analysis pass was not registered prior to being queried");
781 ResultConceptT &ResultConcept =
782 getResultImpl(PassT::ID(), IR, ExtraArgs...);
783
784 using ResultModelT =
785 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
786 PreservedAnalyses, Invalidator>;
787
788 return static_cast<ResultModelT &>(ResultConcept).Result;
789 }
790
791 /// Get the cached result of an analysis pass for a given IR unit.
792 ///
793 /// This method never runs the analysis.
794 ///
795 /// \returns null if there is no cached result.
796 template <typename PassT>
797 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
798 assert(AnalysisPasses.count(PassT::ID()) &&
799 "This analysis pass was not registered prior to being queried");
800
801 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
802 if (!ResultConcept)
803 return nullptr;
804
805 using ResultModelT =
806 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
807 PreservedAnalyses, Invalidator>;
808
809 return &static_cast<ResultModelT *>(ResultConcept)->Result;
810 }
811
812 /// Verify that the given Result cannot be invalidated, assert otherwise.
813 template <typename PassT>
814 void verifyNotInvalidated(IRUnitT &IR, typename PassT::Result *Result) const {
815 PreservedAnalyses PA = PreservedAnalyses::none();
816 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
817 Invalidator Inv(IsResultInvalidated, AnalysisResults);
818 assert(!Result->invalidate(IR, PA, Inv) &&
819 "Cached result cannot be invalidated");
820 }
821
822 /// Register an analysis pass with the manager.
823 ///
824 /// The parameter is a callable whose result is an analysis pass. This allows
825 /// passing in a lambda to construct the analysis.
826 ///
827 /// The analysis type to register is the type returned by calling the \c
828 /// PassBuilder argument. If that type has already been registered, then the
829 /// argument will not be called and this function will return false.
830 /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
831 /// and this function returns true.
832 ///
833 /// (Note: Although the return value of this function indicates whether or not
834 /// an analysis was previously registered, there intentionally isn't a way to
835 /// query this directly. Instead, you should just register all the analyses
836 /// you might want and let this class run them lazily. This idiom lets us
837 /// minimize the number of times we have to look up analyses in our
838 /// hashtable.)
839 template <typename PassBuilderT>
840 bool registerPass(PassBuilderT &&PassBuilder) {
841 using PassT = decltype(PassBuilder());
842 using PassModelT =
843 detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses,
844 Invalidator, ExtraArgTs...>;
845
846 auto &PassPtr = AnalysisPasses[PassT::ID()];
847 if (PassPtr)
848 // Already registered this pass type!
849 return false;
850
851 // Construct a new model around the instance returned by the builder.
852 PassPtr.reset(new PassModelT(PassBuilder()));
853 return true;
854 }
855
856 /// Invalidate cached analyses for an IR unit.
857 ///
858 /// Walk through all of the analyses pertaining to this unit of IR and
859 /// invalidate them, unless they are preserved by the PreservedAnalyses set.
860 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA);
861
862private:
863 /// Look up a registered analysis pass.
864 PassConceptT &lookUpPass(AnalysisKey *ID) {
865 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
866 assert(PI != AnalysisPasses.end() &&
867 "Analysis passes must be registered prior to being queried!");
868 return *PI->second;
869 }
870
871 /// Look up a registered analysis pass.
872 const PassConceptT &lookUpPass(AnalysisKey *ID) const {
873 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
874 assert(PI != AnalysisPasses.end() &&
875 "Analysis passes must be registered prior to being queried!");
876 return *PI->second;
877 }
878
879 /// Get an analysis result, running the pass if necessary.
880 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
881 ExtraArgTs... ExtraArgs);
882
883 /// Get a cached analysis result or return null.
884 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
885 typename AnalysisResultMapT::const_iterator RI =
886 AnalysisResults.find({ID, &IR});
887 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
888 }
889
890 /// Map type from analysis pass ID to pass concept pointer.
891 using AnalysisPassMapT =
892 DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>;
893
894 /// Collection of analysis passes, indexed by ID.
895 AnalysisPassMapT AnalysisPasses;
896
897 /// Map from IR unit to a list of analysis results.
898 ///
899 /// Provides linear time removal of all analysis results for a IR unit and
900 /// the ultimate storage for a particular cached analysis result.
901 AnalysisResultListMapT AnalysisResultLists;
902
903 /// Map from an analysis ID and IR unit to a particular cached
904 /// analysis result.
905 AnalysisResultMapT AnalysisResults;
906};
907
908extern template class AnalysisManager<Module>;
909
910/// Convenience typedef for the Module analysis manager.
911using ModuleAnalysisManager = AnalysisManager<Module>;
912
913extern template class AnalysisManager<Function>;
914
915/// Convenience typedef for the Function analysis manager.
916using FunctionAnalysisManager = AnalysisManager<Function>;
917
918/// An analysis over an "outer" IR unit that provides access to an
919/// analysis manager over an "inner" IR unit. The inner unit must be contained
920/// in the outer unit.
921///
922/// For example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
923/// an analysis over Modules (the "outer" unit) that provides access to a
924/// Function analysis manager. The FunctionAnalysisManager is the "inner"
925/// manager being proxied, and Functions are the "inner" unit. The inner/outer
926/// relationship is valid because each Function is contained in one Module.
927///
928/// If you're (transitively) within a pass manager for an IR unit U that
929/// contains IR unit V, you should never use an analysis manager over V, except
930/// via one of these proxies.
931///
932/// Note that the proxy's result is a move-only RAII object. The validity of
933/// the analyses in the inner analysis manager is tied to its lifetime.
934template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
935class InnerAnalysisManagerProxy
936 : public AnalysisInfoMixin<
937 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
938public:
939 class Result {
940 public:
941 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
942
943 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
944 // We have to null out the analysis manager in the moved-from state
945 // because we are taking ownership of the responsibilty to clear the
946 // analysis state.
947 Arg.InnerAM = nullptr;
948 }
949
950 ~Result() {
951 // InnerAM is cleared in a moved from state where there is nothing to do.
952 if (!InnerAM)
953 return;
954
955 // Clear out the analysis manager if we're being destroyed -- it means we
956 // didn't even see an invalidate call when we got invalidated.
957 InnerAM->clear();
958 }
959
960 Result &operator=(Result &&RHS) {
961 InnerAM = RHS.InnerAM;
962 // We have to null out the analysis manager in the moved-from state
963 // because we are taking ownership of the responsibilty to clear the
964 // analysis state.
965 RHS.InnerAM = nullptr;
966 return *this;
967 }
968
969 /// Accessor for the analysis manager.
970 AnalysisManagerT &getManager() { return *InnerAM; }
971
972 /// Handler for invalidation of the outer IR unit, \c IRUnitT.
973 ///
974 /// If the proxy analysis itself is not preserved, we assume that the set of
975 /// inner IR objects contained in IRUnit may have changed. In this case,
976 /// we have to call \c clear() on the inner analysis manager, as it may now
977 /// have stale pointers to its inner IR objects.
978 ///
979 /// Regardless of whether the proxy analysis is marked as preserved, all of
980 /// the analyses in the inner analysis manager are potentially invalidated
981 /// based on the set of preserved analyses.
982 bool invalidate(
983 IRUnitT &IR, const PreservedAnalyses &PA,
984 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv);
985
986 private:
987 AnalysisManagerT *InnerAM;
988 };
989
990 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
991 : InnerAM(&InnerAM) {}
992
993 /// Run the analysis pass and create our proxy result object.
994 ///
995 /// This doesn't do any interesting work; it is primarily used to insert our
996 /// proxy result object into the outer analysis cache so that we can proxy
997 /// invalidation to the inner analysis manager.
998 Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM,
999 ExtraArgTs...) {
1000 return Result(*InnerAM);
1001 }
1002
1003private:
1004 friend AnalysisInfoMixin<
1005 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
1006
1007 static AnalysisKey Key;
1008
1009 AnalysisManagerT *InnerAM;
1010};
1011
1012template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1013AnalysisKey
1014 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1015
1016/// Provide the \c FunctionAnalysisManager to \c Module proxy.
1017using FunctionAnalysisManagerModuleProxy =
1018 InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>;
1019
1020/// Specialization of the invalidate method for the \c
1021/// FunctionAnalysisManagerModuleProxy's result.
1022template <>
1023bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
1024 Module &M, const PreservedAnalyses &PA,
1025 ModuleAnalysisManager::Invalidator &Inv);
1026
1027// Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
1028// template.
1029extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
1030 Module>;
1031
1032/// An analysis over an "inner" IR unit that provides access to an
1033/// analysis manager over a "outer" IR unit. The inner unit must be contained
1034/// in the outer unit.
1035///
1036/// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
1037/// analysis over Functions (the "inner" unit) which provides access to a Module
1038/// analysis manager. The ModuleAnalysisManager is the "outer" manager being
1039/// proxied, and Modules are the "outer" IR unit. The inner/outer relationship
1040/// is valid because each Function is contained in one Module.
1041///
1042/// This proxy only exposes the const interface of the outer analysis manager,
1043/// to indicate that you cannot cause an outer analysis to run from within an
1044/// inner pass. Instead, you must rely on the \c getCachedResult API. This is
1045/// due to keeping potential future concurrency in mind. To give an example,
1046/// running a module analysis before any function passes may give a different
1047/// result than running it in a function pass. Both may be valid, but it would
1048/// produce non-deterministic results. GlobalsAA is a good analysis example,
1049/// because the cached information has the mod/ref info for all memory for each
1050/// function at the time the analysis was computed. The information is still
1051/// valid after a function transformation, but it may be *different* if
1052/// recomputed after that transform. GlobalsAA is never invalidated.
1053
1054///
1055/// This proxy doesn't manage invalidation in any way -- that is handled by the
1056/// recursive return path of each layer of the pass manager. A consequence of
1057/// this is the outer analyses may be stale. We invalidate the outer analyses
1058/// only when we're done running passes over the inner IR units.
1059template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1060class OuterAnalysisManagerProxy
1061 : public AnalysisInfoMixin<
1062 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
1063public:
1064 /// Result proxy object for \c OuterAnalysisManagerProxy.
1065 class Result {
1066 public:
1067 explicit Result(const AnalysisManagerT &OuterAM) : OuterAM(&OuterAM) {}
1068
1069 /// Get a cached analysis. If the analysis can be invalidated, this will
1070 /// assert.
1071 template <typename PassT, typename IRUnitTParam>
1072 typename PassT::Result *getCachedResult(IRUnitTParam &IR) const {
1073 typename PassT::Result *Res =
1074 OuterAM->template getCachedResult<PassT>(IR);
1075 if (Res)
1076 OuterAM->template verifyNotInvalidated<PassT>(IR, Res);
1077 return Res;
1078 }
1079
1080 /// Method provided for unit testing, not intended for general use.
1081 template <typename PassT, typename IRUnitTParam>
1082 bool cachedResultExists(IRUnitTParam &IR) const {
1083 typename PassT::Result *Res =
1084 OuterAM->template getCachedResult<PassT>(IR);
1085 return Res != nullptr;
1086 }
1087
1088 /// When invalidation occurs, remove any registered invalidation events.
1089 bool invalidate(
1090 IRUnitT &IRUnit, const PreservedAnalyses &PA,
1091 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv) {
1092 // Loop over the set of registered outer invalidation mappings and if any
1093 // of them map to an analysis that is now invalid, clear it out.
1094 SmallVector<AnalysisKey *, 4> DeadKeys;
1095 for (auto &KeyValuePair : OuterAnalysisInvalidationMap) {
1096 AnalysisKey *OuterID = KeyValuePair.first;
1097 auto &InnerIDs = KeyValuePair.second;
1098 llvm::erase_if(InnerIDs, [&](AnalysisKey *InnerID) {
1099 return Inv.invalidate(InnerID, IRUnit, PA);
1100 });
1101 if (InnerIDs.empty())
1102 DeadKeys.push_back(OuterID);
1103 }
1104
1105 for (auto *OuterID : DeadKeys)
1106 OuterAnalysisInvalidationMap.erase(OuterID);
1107
1108 // The proxy itself remains valid regardless of anything else.
1109 return false;
1110 }
1111
1112 /// Register a deferred invalidation event for when the outer analysis
1113 /// manager processes its invalidations.
1114 template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
1115 void registerOuterAnalysisInvalidation() {
1116 AnalysisKey *OuterID = OuterAnalysisT::ID();
1117 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
1118
1119 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
1120 // Note, this is a linear scan. If we end up with large numbers of
1121 // analyses that all trigger invalidation on the same outer analysis,
1122 // this entire system should be changed to some other deterministic
1123 // data structure such as a `SetVector` of a pair of pointers.
1124 if (!llvm::is_contained(InvalidatedIDList, InvalidatedID))
1125 InvalidatedIDList.push_back(InvalidatedID);
1126 }
1127
1128 /// Access the map from outer analyses to deferred invalidation requiring
1129 /// analyses.
1130 const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> &
1131 getOuterInvalidations() const {
1132 return OuterAnalysisInvalidationMap;
1133 }
1134
1135 private:
1136 const AnalysisManagerT *OuterAM;
1137
1138 /// A map from an outer analysis ID to the set of this IR-unit's analyses
1139 /// which need to be invalidated.
1140 SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2>
1141 OuterAnalysisInvalidationMap;
1142 };
1143
1144 OuterAnalysisManagerProxy(const AnalysisManagerT &OuterAM)
1145 : OuterAM(&OuterAM) {}
1146
1147 /// Run the analysis pass and create our proxy result object.
1148 /// Nothing to see here, it just forwards the \c OuterAM reference into the
1149 /// result.
1150 Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &,
1151 ExtraArgTs...) {
1152 return Result(*OuterAM);
1153 }
1154
1155private:
1156 friend AnalysisInfoMixin<
1157 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
1158
1159 static AnalysisKey Key;
1160
1161 const AnalysisManagerT *OuterAM;
1162};
1163
1164template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1165AnalysisKey
1166 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1167
1168extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
1169 Function>;
1170/// Provide the \c ModuleAnalysisManager to \c Function proxy.
1171using ModuleAnalysisManagerFunctionProxy =
1172 OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>;
1173
1174/// Trivial adaptor that maps from a module to its functions.
1175///
1176/// Designed to allow composition of a FunctionPass(Manager) and
1177/// a ModulePassManager, by running the FunctionPass(Manager) over every
1178/// function in the module.
1179///
1180/// Function passes run within this adaptor can rely on having exclusive access
1181/// to the function they are run over. They should not read or modify any other
1182/// functions! Other threads or systems may be manipulating other functions in
1183/// the module, and so their state should never be relied on.
1184/// FIXME: Make the above true for all of LLVM's actual passes, some still
1185/// violate this principle.
1186///
1187/// Function passes can also read the module containing the function, but they
1188/// should not modify that module outside of the use lists of various globals.
1189/// For example, a function pass is not permitted to add functions to the
1190/// module.
1191/// FIXME: Make the above true for all of LLVM's actual passes, some still
1192/// violate this principle.
1193///
1194/// Note that although function passes can access module analyses, module
1195/// analyses are not invalidated while the function passes are running, so they
1196/// may be stale. Function analyses will not be stale.
1197class ModuleToFunctionPassAdaptor
1198 : public PassInfoMixin<ModuleToFunctionPassAdaptor> {
1199public:
1200 using PassConceptT = detail::PassConcept<Function, FunctionAnalysisManager>;
1201
1202 explicit ModuleToFunctionPassAdaptor(std::unique_ptr<PassConceptT> Pass,
1203 bool EagerlyInvalidate)
1204 : Pass(std::move(Pass)), EagerlyInvalidate(EagerlyInvalidate) {}
1205
1206 /// Runs the function pass across every function in the module.
1207 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
1208 void printPipeline(raw_ostream &OS,
1209 function_ref<StringRef(StringRef)> MapClassName2PassName);
1210
1211 static bool isRequired() { return true; }
1212
1213private:
1214 std::unique_ptr<PassConceptT> Pass;
1215 bool EagerlyInvalidate;
1216};
1217
1218/// A function to deduce a function pass type and wrap it in the
1219/// templated adaptor.
1220template <typename FunctionPassT>
1221ModuleToFunctionPassAdaptor
1222createModuleToFunctionPassAdaptor(FunctionPassT &&Pass,
1223 bool EagerlyInvalidate = false) {
1224 using PassModelT =
1225 detail::PassModel<Function, FunctionPassT, PreservedAnalyses,
1226 FunctionAnalysisManager>;
1227 // Do not use make_unique, it causes too many template instantiations,
1228 // causing terrible compile times.
1229 return ModuleToFunctionPassAdaptor(
1230 std::unique_ptr<ModuleToFunctionPassAdaptor::PassConceptT>(
1231 new PassModelT(std::forward<FunctionPassT>(Pass))),
1232 EagerlyInvalidate);
1233}
1234
1235/// A utility pass template to force an analysis result to be available.
1236///
1237/// If there are extra arguments at the pass's run level there may also be
1238/// extra arguments to the analysis manager's \c getResult routine. We can't
1239/// guess how to effectively map the arguments from one to the other, and so
1240/// this specialization just ignores them.
1241///
1242/// Specific patterns of run-method extra arguments and analysis manager extra
1243/// arguments will have to be defined as appropriate specializations.
1244template <typename AnalysisT, typename IRUnitT,
1245 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
1246 typename... ExtraArgTs>
1247struct RequireAnalysisPass
1248 : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
1249 ExtraArgTs...>> {
1250 /// Run this pass over some unit of IR.
1251 ///
1252 /// This pass can be run over any unit of IR and use any analysis manager
1253 /// provided they satisfy the basic API requirements. When this pass is
1254 /// created, these methods can be instantiated to satisfy whatever the
1255 /// context requires.
1256 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
1257 ExtraArgTs &&... Args) {
1258 (void)AM.template getResult<AnalysisT>(Arg,
1259 std::forward<ExtraArgTs>(Args)...);
1260
1261 return PreservedAnalyses::all();
1262 }
1263 void printPipeline(raw_ostream &OS,
1264 function_ref<StringRef(StringRef)> MapClassName2PassName) {
1265 auto ClassName = AnalysisT::name();
1266 auto PassName = MapClassName2PassName(ClassName);
1267 OS << "require<" << PassName << ">";
1268 }
1269 static bool isRequired() { return true; }
1270};
1271
1272/// A no-op pass template which simply forces a specific analysis result
1273/// to be invalidated.
1274template <typename AnalysisT>
1275struct InvalidateAnalysisPass
1276 : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
1277 /// Run this pass over some unit of IR.
1278 ///
1279 /// This pass can be run over any unit of IR and use any analysis manager,
1280 /// provided they satisfy the basic API requirements. When this pass is
1281 /// created, these methods can be instantiated to satisfy whatever the
1282 /// context requires.
1283 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1284 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
1285 auto PA = PreservedAnalyses::all();
1286 PA.abandon<AnalysisT>();
1287 return PA;
1288 }
1289 void printPipeline(raw_ostream &OS,
1290 function_ref<StringRef(StringRef)> MapClassName2PassName) {
1291 auto ClassName = AnalysisT::name();
1292 auto PassName = MapClassName2PassName(ClassName);
1293 OS << "invalidate<" << PassName << ">";
1294 }
1295};
1296
1297/// A utility pass that does nothing, but preserves no analyses.
1298///
1299/// Because this preserves no analyses, any analysis passes queried after this
1300/// pass runs will recompute fresh results.
1301struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
1302 /// Run this pass over some unit of IR.
1303 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1304 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
1305 return PreservedAnalyses::none();
1306 }
1307};
1308
1309/// A utility pass template that simply runs another pass multiple times.
1310///
1311/// This can be useful when debugging or testing passes. It also serves as an
1312/// example of how to extend the pass manager in ways beyond composition.
1313template <typename PassT>
1314class RepeatedPass : public PassInfoMixin<RepeatedPass<PassT>> {
1315public:
1316 RepeatedPass(int Count, PassT &&P)
1317 : Count(Count), P(std::forward<PassT>(P)) {}
1318
1319 template <typename IRUnitT, typename AnalysisManagerT, typename... Ts>
1320 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, Ts &&... Args) {
1321
1322 // Request PassInstrumentation from analysis manager, will use it to run
1323 // instrumenting callbacks for the passes later.
1324 // Here we use std::tuple wrapper over getResult which helps to extract
1325 // AnalysisManager's arguments out of the whole Args set.
1326 PassInstrumentation PI =
1327 detail::getAnalysisResult<PassInstrumentationAnalysis>(
1328 AM, IR, std::tuple<Ts...>(Args...));
1329
1330 auto PA = PreservedAnalyses::all();
1331 for (int i = 0; i < Count; ++i) {
1332 // Check the PassInstrumentation's BeforePass callbacks before running the
1333 // pass, skip its execution completely if asked to (callback returns
1334 // false).
1335 if (!PI.runBeforePass<IRUnitT>(P, IR))
1336 continue;
1337 PreservedAnalyses IterPA = P.run(IR, AM, std::forward<Ts>(Args)...);
1338 PA.intersect(IterPA);
1339 PI.runAfterPass(P, IR, IterPA);
1340 }
1341 return PA;
1342 }
1343
1344 void printPipeline(raw_ostream &OS,
1345 function_ref<StringRef(StringRef)> MapClassName2PassName) {
1346 OS << "repeat<" << Count << ">(";
1347 P.printPipeline(OS, MapClassName2PassName);
1348 OS << ")";
1349 }
1350
1351private:
1352 int Count;
1353 PassT P;
1354};
1355
1356template <typename PassT>
1357RepeatedPass<PassT> createRepeatedPass(int Count, PassT &&P) {
1358 return RepeatedPass<PassT>(Count, std::forward<PassT>(P));
1359}
1360
1361} // end namespace llvm
1362
1363#endif // LLVM_IR_PASSMANAGER_H
1364

source code of llvm/include/llvm/IR/PassManager.h