LegacyPassManagers.h 18 KB

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