1 //===- LegacyPassManagers.h - Legacy Pass 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 // 9 // This file declares the LLVM Pass Manager infrastructure. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_IR_LEGACYPASSMANAGERS_H 14 #define LLVM_IR_LEGACYPASSMANAGERS_H 15 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/FoldingSet.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/Pass.h" 21 #include <vector> 22 23 //===----------------------------------------------------------------------===// 24 // Overview: 25 // The Pass Manager Infrastructure manages passes. It's responsibilities are: 26 // 27 // o Manage optimization pass execution order 28 // o Make required Analysis information available before pass P is run 29 // o Release memory occupied by dead passes 30 // o If Analysis information is dirtied by a pass then regenerate Analysis 31 // information before it is consumed by another pass. 32 // 33 // Pass Manager Infrastructure uses multiple pass managers. They are 34 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager. 35 // This class hierarchy uses multiple inheritance but pass managers do not 36 // derive from another pass manager. 37 // 38 // PassManager and FunctionPassManager are two top-level pass manager that 39 // represents the external interface of this entire pass manager infrastucture. 40 // 41 // Important classes : 42 // 43 // [o] class PMTopLevelManager; 44 // 45 // Two top level managers, PassManager and FunctionPassManager, derive from 46 // PMTopLevelManager. PMTopLevelManager manages information used by top level 47 // managers such as last user info. 48 // 49 // [o] class PMDataManager; 50 // 51 // PMDataManager manages information, e.g. list of available analysis info, 52 // used by a pass manager to manage execution order of passes. It also provides 53 // a place to implement common pass manager APIs. All pass managers derive from 54 // PMDataManager. 55 // 56 // [o] class BBPassManager : public FunctionPass, public PMDataManager; 57 // 58 // BBPassManager manages BasicBlockPasses. 59 // 60 // [o] class FunctionPassManager; 61 // 62 // This is a external interface used to manage FunctionPasses. This 63 // interface relies on FunctionPassManagerImpl to do all the tasks. 64 // 65 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager, 66 // public PMTopLevelManager; 67 // 68 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers 69 // 70 // [o] class FPPassManager : public ModulePass, public PMDataManager; 71 // 72 // FPPassManager manages FunctionPasses and BBPassManagers 73 // 74 // [o] class MPPassManager : public Pass, public PMDataManager; 75 // 76 // MPPassManager manages ModulePasses and FPPassManagers 77 // 78 // [o] class PassManager; 79 // 80 // This is a external interface used by various tools to manages passes. It 81 // relies on PassManagerImpl to do all the tasks. 82 // 83 // [o] class PassManagerImpl : public Pass, public PMDataManager, 84 // public PMTopLevelManager 85 // 86 // PassManagerImpl is a top level pass manager responsible for managing 87 // MPPassManagers. 88 //===----------------------------------------------------------------------===// 89 90 #include "llvm/Support/PrettyStackTrace.h" 91 92 namespace llvm { 93 template <typename T> class ArrayRef; 94 class Module; 95 class Pass; 96 class StringRef; 97 class Value; 98 class Timer; 99 class PMDataManager; 100 101 // enums for debugging strings 102 enum PassDebuggingString { 103 EXECUTION_MSG, // "Executing Pass '" + PassName 104 MODIFICATION_MSG, // "Made Modification '" + PassName 105 FREEING_MSG, // " Freeing Pass '" + PassName 106 ON_BASICBLOCK_MSG, // "' on BasicBlock '" + InstructionName + "'...\n" 107 ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n" 108 ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n" 109 ON_REGION_MSG, // "' on Region '" + Msg + "'...\n'" 110 ON_LOOP_MSG, // "' on Loop '" + Msg + "'...\n'" 111 ON_CG_MSG // "' on Call Graph Nodes '" + Msg + "'...\n'" 112 }; 113 114 /// PassManagerPrettyStackEntry - This is used to print informative information 115 /// about what pass is running when/if a stack trace is generated. 116 class PassManagerPrettyStackEntry : public PrettyStackTraceEntry { 117 Pass *P; 118 Value *V; 119 Module *M; 120 121 public: 122 explicit PassManagerPrettyStackEntry(Pass *p) 123 : P(p), V(nullptr), M(nullptr) {} // When P is releaseMemory'd. 124 PassManagerPrettyStackEntry(Pass *p, Value &v) 125 : P(p), V(&v), M(nullptr) {} // When P is run on V 126 PassManagerPrettyStackEntry(Pass *p, Module &m) 127 : P(p), V(nullptr), M(&m) {} // When P is run on M 128 129 /// print - Emit information about this stack frame to OS. 130 void print(raw_ostream &OS) const override; 131 }; 132 133 //===----------------------------------------------------------------------===// 134 // PMStack 135 // 136 /// PMStack - This class implements a stack data structure of PMDataManager 137 /// pointers. 138 /// 139 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers 140 /// using PMStack. Each Pass implements assignPassManager() to connect itself 141 /// with appropriate manager. assignPassManager() walks PMStack to find 142 /// suitable manager. 143 class PMStack { 144 public: 145 typedef std::vector<PMDataManager *>::const_reverse_iterator iterator; 146 iterator begin() const { return S.rbegin(); } 147 iterator end() const { return S.rend(); } 148 149 void pop(); 150 PMDataManager *top() const { return S.back(); } 151 void push(PMDataManager *PM); 152 bool empty() const { return S.empty(); } 153 154 void dump() const; 155 156 private: 157 std::vector<PMDataManager *> S; 158 }; 159 160 //===----------------------------------------------------------------------===// 161 // PMTopLevelManager 162 // 163 /// PMTopLevelManager manages LastUser info and collects common APIs used by 164 /// top level pass managers. 165 class PMTopLevelManager { 166 protected: 167 explicit PMTopLevelManager(PMDataManager *PMDM); 168 169 unsigned getNumContainedManagers() const { 170 return (unsigned)PassManagers.size(); 171 } 172 173 void initializeAllAnalysisInfo(); 174 175 private: 176 virtual PMDataManager *getAsPMDataManager() = 0; 177 virtual PassManagerType getTopLevelPassManagerType() = 0; 178 179 public: 180 /// Schedule pass P for execution. Make sure that passes required by 181 /// P are run before P is run. Update analysis info maintained by 182 /// the manager. Remove dead passes. This is a recursive function. 183 void schedulePass(Pass *P); 184 185 /// Set pass P as the last user of the given analysis passes. 186 void setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P); 187 188 /// Collect passes whose last user is P 189 void collectLastUses(SmallVectorImpl<Pass *> &LastUses, Pass *P); 190 191 /// Find the pass that implements Analysis AID. Search immutable 192 /// passes and all pass managers. If desired pass is not found 193 /// then return NULL. 194 Pass *findAnalysisPass(AnalysisID AID); 195 196 /// Retrieve the PassInfo for an analysis. 197 const PassInfo *findAnalysisPassInfo(AnalysisID AID) const; 198 199 /// Find analysis usage information for the pass P. 200 AnalysisUsage *findAnalysisUsage(Pass *P); 201 202 virtual ~PMTopLevelManager(); 203 204 /// Add immutable pass and initialize it. 205 void addImmutablePass(ImmutablePass *P); 206 207 inline SmallVectorImpl<ImmutablePass *>& getImmutablePasses() { 208 return ImmutablePasses; 209 } 210 211 void addPassManager(PMDataManager *Manager) { 212 PassManagers.push_back(Manager); 213 } 214 215 // Add Manager into the list of managers that are not directly 216 // maintained by this top level pass manager 217 inline void addIndirectPassManager(PMDataManager *Manager) { 218 IndirectPassManagers.push_back(Manager); 219 } 220 221 // Print passes managed by this top level manager. 222 void dumpPasses() const; 223 void dumpArguments() const; 224 225 // Active Pass Managers 226 PMStack activeStack; 227 228 protected: 229 /// Collection of pass managers 230 SmallVector<PMDataManager *, 8> PassManagers; 231 232 private: 233 /// Collection of pass managers that are not directly maintained 234 /// by this pass manager 235 SmallVector<PMDataManager *, 8> IndirectPassManagers; 236 237 // Map to keep track of last user of the analysis pass. 238 // LastUser->second is the last user of Lastuser->first. 239 DenseMap<Pass *, Pass *> LastUser; 240 241 // Map to keep track of passes that are last used by a pass. 242 // This inverse map is initialized at PM->run() based on 243 // LastUser map. 244 DenseMap<Pass *, SmallPtrSet<Pass *, 8> > InversedLastUser; 245 246 /// Immutable passes are managed by top level manager. 247 SmallVector<ImmutablePass *, 16> ImmutablePasses; 248 249 /// Map from ID to immutable passes. 250 SmallDenseMap<AnalysisID, ImmutablePass *, 8> ImmutablePassMap; 251 252 253 /// A wrapper around AnalysisUsage for the purpose of uniqueing. The wrapper 254 /// is used to avoid needing to make AnalysisUsage itself a folding set node. 255 struct AUFoldingSetNode : public FoldingSetNode { 256 AnalysisUsage AU; 257 AUFoldingSetNode(const AnalysisUsage &AU) : AU(AU) {} 258 void Profile(FoldingSetNodeID &ID) const { 259 Profile(ID, AU); 260 } 261 static void Profile(FoldingSetNodeID &ID, const AnalysisUsage &AU) { 262 // TODO: We could consider sorting the dependency arrays within the 263 // AnalysisUsage (since they are conceptually unordered). 264 ID.AddBoolean(AU.getPreservesAll()); 265 auto ProfileVec = [&](const SmallVectorImpl<AnalysisID>& Vec) { 266 ID.AddInteger(Vec.size()); 267 for(AnalysisID AID : Vec) 268 ID.AddPointer(AID); 269 }; 270 ProfileVec(AU.getRequiredSet()); 271 ProfileVec(AU.getRequiredTransitiveSet()); 272 ProfileVec(AU.getPreservedSet()); 273 ProfileVec(AU.getUsedSet()); 274 } 275 }; 276 277 // Contains all of the unique combinations of AnalysisUsage. This is helpful 278 // when we have multiple instances of the same pass since they'll usually 279 // have the same analysis usage and can share storage. 280 FoldingSet<AUFoldingSetNode> UniqueAnalysisUsages; 281 282 // Allocator used for allocating UAFoldingSetNodes. This handles deletion of 283 // all allocated nodes in one fell swoop. 284 SpecificBumpPtrAllocator<AUFoldingSetNode> AUFoldingSetNodeAllocator; 285 286 // Maps from a pass to it's associated entry in UniqueAnalysisUsages. Does 287 // not own the storage associated with either key or value.. 288 DenseMap<Pass *, AnalysisUsage*> AnUsageMap; 289 290 /// Collection of PassInfo objects found via analysis IDs and in this top 291 /// level manager. This is used to memoize queries to the pass registry. 292 /// FIXME: This is an egregious hack because querying the pass registry is 293 /// either slow or racy. 294 mutable DenseMap<AnalysisID, const PassInfo *> AnalysisPassInfos; 295 }; 296 297 //===----------------------------------------------------------------------===// 298 // PMDataManager 299 300 /// PMDataManager provides the common place to manage the analysis data 301 /// used by pass managers. 302 class PMDataManager { 303 public: 304 explicit PMDataManager() : TPM(nullptr), Depth(0) { 305 initializeAnalysisInfo(); 306 } 307 308 virtual ~PMDataManager(); 309 310 virtual Pass *getAsPass() = 0; 311 312 /// Augment AvailableAnalysis by adding analysis made available by pass P. 313 void recordAvailableAnalysis(Pass *P); 314 315 /// verifyPreservedAnalysis -- Verify analysis presreved by pass P. 316 void verifyPreservedAnalysis(Pass *P); 317 318 /// Remove Analysis that is not preserved by the pass 319 void removeNotPreservedAnalysis(Pass *P); 320 321 /// Remove dead passes used by P. 322 void removeDeadPasses(Pass *P, StringRef Msg, 323 enum PassDebuggingString); 324 325 /// Remove P. 326 void freePass(Pass *P, StringRef Msg, 327 enum PassDebuggingString); 328 329 /// Add pass P into the PassVector. Update 330 /// AvailableAnalysis appropriately if ProcessAnalysis is true. 331 void add(Pass *P, bool ProcessAnalysis = true); 332 333 /// Add RequiredPass into list of lower level passes required by pass P. 334 /// RequiredPass is run on the fly by Pass Manager when P requests it 335 /// through getAnalysis interface. 336 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass); 337 338 virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F); 339 340 /// Initialize available analysis information. 341 void initializeAnalysisInfo() { 342 AvailableAnalysis.clear(); 343 for (unsigned i = 0; i < PMT_Last; ++i) 344 InheritedAnalysis[i] = nullptr; 345 } 346 347 // Return true if P preserves high level analysis used by other 348 // passes that are managed by this manager. 349 bool preserveHigherLevelAnalysis(Pass *P); 350 351 /// Populate UsedPasses with analysis pass that are used or required by pass 352 /// P and are available. Populate ReqPassNotAvailable with analysis pass that 353 /// are required by pass P but are not available. 354 void collectRequiredAndUsedAnalyses( 355 SmallVectorImpl<Pass *> &UsedPasses, 356 SmallVectorImpl<AnalysisID> &ReqPassNotAvailable, Pass *P); 357 358 /// All Required analyses should be available to the pass as it runs! Here 359 /// we fill in the AnalysisImpls member of the pass so that it can 360 /// successfully use the getAnalysis() method to retrieve the 361 /// implementations it needs. 362 void initializeAnalysisImpl(Pass *P); 363 364 /// Find the pass that implements Analysis AID. If desired pass is not found 365 /// then return NULL. 366 Pass *findAnalysisPass(AnalysisID AID, bool Direction); 367 368 // Access toplevel manager 369 PMTopLevelManager *getTopLevelManager() { return TPM; } 370 void setTopLevelManager(PMTopLevelManager *T) { TPM = T; } 371 372 unsigned getDepth() const { return Depth; } 373 void setDepth(unsigned newDepth) { Depth = newDepth; } 374 375 // Print routines used by debug-pass 376 void dumpLastUses(Pass *P, unsigned Offset) const; 377 void dumpPassArguments() const; 378 void dumpPassInfo(Pass *P, enum PassDebuggingString S1, 379 enum PassDebuggingString S2, StringRef Msg); 380 void dumpRequiredSet(const Pass *P) const; 381 void dumpPreservedSet(const Pass *P) const; 382 void dumpUsedSet(const Pass *P) const; 383 384 unsigned getNumContainedPasses() const { 385 return (unsigned)PassVector.size(); 386 } 387 388 virtual PassManagerType getPassManagerType() const { 389 assert ( 0 && "Invalid use of getPassManagerType"); 390 return PMT_Unknown; 391 } 392 393 DenseMap<AnalysisID, Pass*> *getAvailableAnalysis() { 394 return &AvailableAnalysis; 395 } 396 397 // Collect AvailableAnalysis from all the active Pass Managers. 398 void populateInheritedAnalysis(PMStack &PMS) { 399 unsigned Index = 0; 400 for (PMStack::iterator I = PMS.begin(), E = PMS.end(); 401 I != E; ++I) 402 InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis(); 403 } 404 405 /// Set the initial size of the module if the user has specified that they 406 /// want remarks for size. 407 /// Returns 0 if the remark was not requested. 408 unsigned initSizeRemarkInfo( 409 Module &M, 410 StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount); 411 412 /// Emit a remark signifying that the number of IR instructions in the module 413 /// changed. 414 /// \p F is optionally passed by passes which run on Functions, and thus 415 /// always know whether or not a non-empty function is available. 416 /// 417 /// \p FunctionToInstrCount maps the name of a \p Function to a pair. The 418 /// first member of the pair is the IR count of the \p Function before running 419 /// \p P, and the second member is the IR count of the \p Function after 420 /// running \p P. 421 void emitInstrCountChangedRemark( 422 Pass *P, Module &M, int64_t Delta, unsigned CountBefore, 423 StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount, 424 Function *F = nullptr); 425 426 protected: 427 // Top level manager. 428 PMTopLevelManager *TPM; 429 430 // Collection of pass that are managed by this manager 431 SmallVector<Pass *, 16> PassVector; 432 433 // Collection of Analysis provided by Parent pass manager and 434 // used by current pass manager. At at time there can not be more 435 // then PMT_Last active pass mangers. 436 DenseMap<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last]; 437 438 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions 439 /// or higher is specified. 440 bool isPassDebuggingExecutionsOrMore() const; 441 442 private: 443 void dumpAnalysisUsage(StringRef Msg, const Pass *P, 444 const AnalysisUsage::VectorType &Set) const; 445 446 // Set of available Analysis. This information is used while scheduling 447 // pass. If a pass requires an analysis which is not available then 448 // the required analysis pass is scheduled to run before the pass itself is 449 // scheduled to run. 450 DenseMap<AnalysisID, Pass*> AvailableAnalysis; 451 452 // Collection of higher level analysis used by the pass managed by 453 // this manager. 454 SmallVector<Pass *, 16> HigherLevelAnalysis; 455 456 unsigned Depth; 457 }; 458 459 //===----------------------------------------------------------------------===// 460 // FPPassManager 461 // 462 /// FPPassManager manages BBPassManagers and FunctionPasses. 463 /// It batches all function passes and basic block pass managers together and 464 /// sequence them to process one function at a time before processing next 465 /// function. 466 class FPPassManager : public ModulePass, public PMDataManager { 467 public: 468 static char ID; 469 explicit FPPassManager() 470 : ModulePass(ID), PMDataManager() { } 471 472 /// run - Execute all of the passes scheduled for execution. Keep track of 473 /// whether any of the passes modifies the module, and if so, return true. 474 bool runOnFunction(Function &F); 475 bool runOnModule(Module &M) override; 476 477 /// cleanup - After running all passes, clean up pass manager cache. 478 void cleanup(); 479 480 /// doInitialization - Overrides ModulePass doInitialization for global 481 /// initialization tasks 482 /// 483 using ModulePass::doInitialization; 484 485 /// doInitialization - Run all of the initializers for the function passes. 486 /// 487 bool doInitialization(Module &M) override; 488 489 /// doFinalization - Overrides ModulePass doFinalization for global 490 /// finalization tasks 491 /// 492 using ModulePass::doFinalization; 493 494 /// doFinalization - Run all of the finalizers for the function passes. 495 /// 496 bool doFinalization(Module &M) override; 497 498 PMDataManager *getAsPMDataManager() override { return this; } 499 Pass *getAsPass() override { return this; } 500 501 /// Pass Manager itself does not invalidate any analysis info. 502 void getAnalysisUsage(AnalysisUsage &Info) const override { 503 Info.setPreservesAll(); 504 } 505 506 // Print passes managed by this manager 507 void dumpPassStructure(unsigned Offset) override; 508 509 StringRef getPassName() const override { return "Function Pass Manager"; } 510 511 FunctionPass *getContainedPass(unsigned N) { 512 assert ( N < PassVector.size() && "Pass number out of range!"); 513 FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]); 514 return FP; 515 } 516 517 PassManagerType getPassManagerType() const override { 518 return PMT_FunctionPassManager; 519 } 520 }; 521 522 } 523 524 #endif 525