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