LLVM 24.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_LOOP_MSG, // "' on Loop '" + Msg + "'...\n'"
104 ON_CG_MSG // "' on Call Graph Nodes '" + Msg + "'...\n'"
105};
106
107/// PassManagerPrettyStackEntry - This is used to print informative information
108/// about what pass is running when/if a stack trace is generated.
109class LLVM_ABI PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
110 Pass *P;
111 Value *V;
112 Module *M;
113
114public:
116 : P(p), V(nullptr), M(nullptr) {} // When P is releaseMemory'd.
118 : P(p), V(&v), M(nullptr) {} // When P is run on V
120 : P(p), V(nullptr), M(&m) {} // When P is run on M
121
122 /// print - Emit information about this stack frame to OS.
123 void print(raw_ostream &OS) const override;
124};
125
126//===----------------------------------------------------------------------===//
127// PMStack
128//
129/// PMStack - This class implements a stack data structure of PMDataManager
130/// pointers.
131///
132/// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
133/// using PMStack. Each Pass implements assignPassManager() to connect itself
134/// with appropriate manager. assignPassManager() walks PMStack to find
135/// suitable manager.
136class PMStack {
137public:
138 typedef std::vector<PMDataManager *>::const_reverse_iterator iterator;
139 iterator begin() const { return S.rbegin(); }
140 iterator end() const { return S.rend(); }
141
142 LLVM_ABI void pop();
143 PMDataManager *top() const { return S.back(); }
144 LLVM_ABI void push(PMDataManager *PM);
145 bool empty() const { return S.empty(); }
146
147 LLVM_ABI void dump() const;
148
149private:
150 std::vector<PMDataManager *> S;
151};
152
153//===----------------------------------------------------------------------===//
154// PMTopLevelManager
155//
156/// PMTopLevelManager manages LastUser info and collects common APIs used by
157/// top level pass managers.
159protected:
160 explicit PMTopLevelManager(PMDataManager *PMDM);
161
162 unsigned getNumContainedManagers() const {
163 return (unsigned)PassManagers.size();
164 }
165
166 void initializeAllAnalysisInfo();
167
168private:
169 virtual PMDataManager *getAsPMDataManager() = 0;
170 virtual PassManagerType getTopLevelPassManagerType() = 0;
171
172public:
173 /// Schedule pass P for execution. Make sure that passes required by
174 /// P are run before P is run. Update analysis info maintained by
175 /// the manager. Remove dead passes. This is a recursive function.
176 void schedulePass(Pass *P);
177
178 /// Set pass P as the last user of the given analysis passes.
179 void setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P);
180
181 /// Collect passes whose last user is P
182 void collectLastUses(SmallVectorImpl<Pass *> &LastUses, Pass *P);
183
184 /// Find the pass that implements Analysis AID. Search immutable
185 /// passes and all pass managers. If desired pass is not found
186 /// then return NULL.
187 Pass *findAnalysisPass(AnalysisID AID);
188
189 /// Retrieve the PassInfo for an analysis.
190 const PassInfo *findAnalysisPassInfo(AnalysisID AID) const;
191
192 /// Find analysis usage information for the pass P.
193 AnalysisUsage *findAnalysisUsage(Pass *P);
194
195 virtual ~PMTopLevelManager();
196
197 /// Add immutable pass and initialize it.
198 void addImmutablePass(ImmutablePass *P);
199
201 return ImmutablePasses;
202 }
203
205 PassManagers.push_back(Manager);
206 }
207
208 // Add Manager into the list of managers that are not directly
209 // maintained by this top level pass manager
210 inline void addIndirectPassManager(PMDataManager *Manager) {
211 IndirectPassManagers.push_back(Manager);
212 }
213
214 // Print passes managed by this top level manager.
215 void dumpPasses() const;
216 void dumpArguments() const;
217
218 // Active Pass Managers
220
221protected:
222 /// Collection of pass managers
224
225private:
226 /// Collection of pass managers that are not directly maintained
227 /// by this pass manager
228 SmallVector<PMDataManager *, 8> IndirectPassManagers;
229
230 // Map to keep track of last user of the analysis pass.
231 // LastUser->second is the last user of Lastuser->first.
232 // This is kept in sync with InversedLastUser.
234
235 // Map to keep track of passes that are last used by a pass.
236 // This is kept in sync with LastUser.
238
239 /// Immutable passes are managed by top level manager.
240 SmallVector<ImmutablePass *, 16> ImmutablePasses;
241
242 /// Map from ID to immutable passes.
244
245
246 /// A wrapper around AnalysisUsage for the purpose of uniqueing. The wrapper
247 /// is used to avoid needing to make AnalysisUsage itself a folding set node.
248 struct AUFoldingSetNode : public FoldingSetNode {
249 AnalysisUsage AU;
250 AUFoldingSetNode(const AnalysisUsage &AU) : AU(AU) {}
251 void Profile(FoldingSetNodeID &ID) const {
252 Profile(ID, AU);
253 }
254 static void Profile(FoldingSetNodeID &ID, const AnalysisUsage &AU) {
255 // TODO: We could consider sorting the dependency arrays within the
256 // AnalysisUsage (since they are conceptually unordered).
257 ID.AddBoolean(AU.getPreservesAll());
258 auto ProfileVec = [&](const SmallVectorImpl<AnalysisID>& Vec) {
259 ID.AddInteger(Vec.size());
260 for(AnalysisID AID : Vec)
261 ID.AddPointer(AID);
262 };
263 ProfileVec(AU.getRequiredSet());
264 ProfileVec(AU.getRequiredTransitiveSet());
265 ProfileVec(AU.getPreservedSet());
266 ProfileVec(AU.getUsedSet());
267 }
268 };
269
270 // Contains all of the unique combinations of AnalysisUsage. This is helpful
271 // when we have multiple instances of the same pass since they'll usually
272 // have the same analysis usage and can share storage.
273 FoldingSet<AUFoldingSetNode> UniqueAnalysisUsages;
274
275 // Allocator used for allocating UAFoldingSetNodes. This handles deletion of
276 // all allocated nodes in one fell swoop.
277 SpecificBumpPtrAllocator<AUFoldingSetNode> AUFoldingSetNodeAllocator;
278
279 // Maps from a pass to it's associated entry in UniqueAnalysisUsages. Does
280 // not own the storage associated with either key or value..
282
283 /// Collection of PassInfo objects found via analysis IDs and in this top
284 /// level manager. This is used to memoize queries to the pass registry.
285 /// FIXME: This is an egregious hack because querying the pass registry is
286 /// either slow or racy.
287 mutable DenseMap<AnalysisID, const PassInfo *> AnalysisPassInfos;
288};
289
290//===----------------------------------------------------------------------===//
291// PMDataManager
292
293/// PMDataManager provides the common place to manage the analysis data
294/// used by pass managers.
296public:
298
299 virtual ~PMDataManager();
300
301 virtual Pass *getAsPass() = 0;
302
303 /// Augment AvailableAnalysis by adding analysis made available by pass P.
305
306 /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
308
309 /// Remove Analysis that is not preserved by the pass
311
312 /// Remove dead passes used by P.
315
316 /// Remove P.
317 void freePass(Pass *P, StringRef Msg,
319
320 /// Add pass P into the PassVector. Update
321 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
322 void add(Pass *P, bool ProcessAnalysis = true);
323
324 /// Add RequiredPass into list of lower level passes required by pass P.
325 /// RequiredPass is run on the fly by Pass Manager when P requests it
326 /// through getAnalysis interface.
327 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
328
329 virtual std::tuple<Pass *, bool> getOnTheFlyPass(Pass *P, AnalysisID PI,
330 Function &F);
331
332 /// Initialize available analysis information.
334 AvailableAnalysis.clear();
336 }
337
338 // Return true if P preserves high level analysis used by other
339 // passes that are managed by this manager.
340 bool preserveHigherLevelAnalysis(Pass *P);
341
342 /// Populate UsedPasses with analysis pass that are used or required by pass
343 /// P and are available. Populate ReqPassNotAvailable with analysis pass that
344 /// are required by pass P but are not available.
345 void collectRequiredAndUsedAnalyses(
346 SmallVectorImpl<Pass *> &UsedPasses,
347 SmallVectorImpl<AnalysisID> &ReqPassNotAvailable, Pass *P);
348
349 /// All Required analyses should be available to the pass as it runs! Here
350 /// we fill in the AnalysisImpls member of the pass so that it can
351 /// successfully use the getAnalysis() method to retrieve the
352 /// implementations it needs.
353 void initializeAnalysisImpl(Pass *P);
354
355 /// Find the pass that implements Analysis AID. If desired pass is not found
356 /// then return NULL.
357 Pass *findAnalysisPass(AnalysisID AID, bool Direction);
358
359 // Access toplevel manager
362
363 unsigned getDepth() const { return Depth; }
364 void setDepth(unsigned newDepth) { Depth = newDepth; }
365
366 // Print routines used by debug-pass
367 void dumpLastUses(Pass *P, unsigned Offset) const;
368 void dumpPassArguments() const;
369 void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
371 void dumpRequiredSet(const Pass *P) const;
372 void dumpPreservedSet(const Pass *P) const;
373 void dumpUsedSet(const Pass *P) const;
374
375 unsigned getNumContainedPasses() const {
376 return (unsigned)PassVector.size();
377 }
378
380 assert ( 0 && "Invalid use of getPassManagerType");
381 return PMT_Unknown;
382 }
383
385 return &AvailableAnalysis;
386 }
387
388 // Collect AvailableAnalysis from all the active Pass Managers.
390 unsigned Index = 0;
391 for (PMDataManager *PMDM : PMS)
392 InheritedAnalysis[Index++] = PMDM->getAvailableAnalysis();
393 }
394
395 /// Set the initial size of the module if the user has specified that they
396 /// want remarks for size.
397 /// Returns 0 if the remark was not requested.
398 unsigned initSizeRemarkInfo(
399 Module &M,
400 StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount);
401
402 /// Emit a remark signifying that the number of IR instructions in the module
403 /// changed.
404 /// \p F is optionally passed by passes which run on Functions, and thus
405 /// always know whether or not a non-empty function is available.
406 ///
407 /// \p FunctionToInstrCount maps the name of a \p Function to a pair. The
408 /// first member of the pair is the IR count of the \p Function before running
409 /// \p P, and the second member is the IR count of the \p Function after
410 /// running \p P.
411 void emitInstrCountChangedRemark(
412 Pass *P, Module &M, int64_t Delta, unsigned CountBefore,
413 StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,
414 Function *F = nullptr);
415
416protected:
417 // Top level manager.
419
420 // Collection of pass that are managed by this manager
422
423 // Collection of Analysis provided by Parent pass manager and
424 // used by current pass manager. At any time there can not be more
425 // then PMT_Last active pass managers.
427
428 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
429 /// or higher is specified.
431
432private:
433 void dumpAnalysisUsage(StringRef Msg, const Pass *P,
434 const AnalysisUsage::VectorType &Set) const;
435
436 // Set of available Analysis. This information is used while scheduling
437 // pass. If a pass requires an analysis which is not available then
438 // the required analysis pass is scheduled to run before the pass itself is
439 // scheduled to run.
440 DenseMap<AnalysisID, Pass*> AvailableAnalysis;
441
442 // Collection of higher level analysis used by the pass managed by
443 // this manager.
444 SmallVector<Pass *, 16> HigherLevelAnalysis;
445
446 unsigned Depth = 0;
447};
448
449//===----------------------------------------------------------------------===//
450// FPPassManager
451//
452/// FPPassManager manages BBPassManagers and FunctionPasses.
453/// It batches all function passes and basic block pass managers together and
454/// sequence them to process one function at a time before processing next
455/// function.
457public:
458 static char ID;
459 explicit FPPassManager() : ModulePass(ID) {}
460
461 /// run - Execute all of the passes scheduled for execution. Keep track of
462 /// whether any of the passes modifies the module, and if so, return true.
463 bool runOnFunction(Function &F);
464 bool runOnModule(Module &M) override;
465
466 /// cleanup - After running all passes, clean up pass manager cache.
467 void cleanup();
468
469 /// doInitialization - Overrides ModulePass doInitialization for global
470 /// initialization tasks
471 ///
473
474 /// doInitialization - Run all of the initializers for the function passes.
475 ///
476 bool doInitialization(Module &M) override;
477
478 /// doFinalization - Overrides ModulePass doFinalization for global
479 /// finalization tasks
480 ///
482
483 /// doFinalization - Run all of the finalizers for the function passes.
484 ///
485 bool doFinalization(Module &M) override;
486
487 PMDataManager *getAsPMDataManager() override { return this; }
488 Pass *getAsPass() override { return this; }
489
490 /// Pass Manager itself does not invalidate any analysis info.
491 void getAnalysisUsage(AnalysisUsage &Info) const override {
492 Info.setPreservesAll();
493 }
494
495 // Print passes managed by this manager
496 void dumpPassStructure(unsigned Offset) override;
497
498 StringRef getPassName() const override { return "Function Pass Manager"; }
499
501 assert ( N < PassVector.size() && "Pass number out of range!");
502 FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
503 return FP;
504 }
505
508 }
509};
510}
511
512#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.
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseMap class.
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:254
#define F(x, y, z)
Definition MD5.cpp:54
Load MIR Sample Profile
#define T
#define P(N)
const char * Msg
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
SmallVectorImpl< AnalysisID > VectorType
const VectorType & getUsedSet() const
bool getPreservesAll() const
Determine whether a pass said it does not transform its input at all.
const VectorType & getPreservedSet() const
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
This class is used to maintain node state in a folding set.
Definition FoldingSet.h:309
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:283
ModulePass(char &pid)
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PMDataManager provides the common place to manage the analysis data used by pass managers.
void removeDeadPasses(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove dead passes used by P.
virtual Pass * getAsPass()=0
virtual std::tuple< Pass *, bool > getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F)
void setDepth(unsigned newDepth)
void recordAvailableAnalysis(Pass *P)
Augment AvailableAnalysis by adding analysis made available by pass P.
bool isPassDebuggingExecutionsOrMore() const
isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions or higher is specified.
unsigned getDepth() const
SmallVector< Pass *, 16 > PassVector
DenseMap< AnalysisID, Pass * > * InheritedAnalysis[PMT_Last]
virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass)
Add RequiredPass into list of lower level passes required by pass P.
PMTopLevelManager * getTopLevelManager()
void setTopLevelManager(PMTopLevelManager *T)
void verifyPreservedAnalysis(Pass *P)
verifyPreservedAnalysis – Verify analysis presreved by pass P.
void initializeAnalysisInfo()
Initialize available analysis information.
void freePass(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove P.
unsigned getNumContainedPasses() const
virtual PassManagerType getPassManagerType() const
PMTopLevelManager * TPM
void add(Pass *P, bool ProcessAnalysis=true)
Add pass P into the PassVector.
DenseMap< AnalysisID, Pass * > * getAvailableAnalysis()
void populateInheritedAnalysis(PMStack &PMS)
void removeNotPreservedAnalysis(Pass *P)
Remove Analysis that is not preserved by the pass.
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
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()
PMTopLevelManager(PMDataManager *PMDM)
Initialize top level manager. Create first pass manager.
PassInfo class - An instance of this class exists for every pass known by the system,...
Definition PassInfo.h:29
PassManagerPrettyStackEntry(Pass *p, Module &m)
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition Pass.h:126
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Definition Pass.h:130
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition Allocator.h:398
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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.
@ Offset
Definition DWP.cpp:577
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:1775
PassManagerType
Different types of internal pass managers.
Definition Pass.h:56
@ PMT_Unknown
Definition Pass.h:57
@ PMT_Last
Definition Pass.h:62
@ PMT_FunctionPassManager
FPPassManager.
Definition Pass.h:60
const void * AnalysisID
Definition Pass.h:51
FoldingSetImpl< T, Trait > FoldingSet
This template class is used to instantiate a specialized implementation of the folding set to the nod...
Definition FoldingSet.h:558
#define N