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