1 //===- llvm/Pass.h - Base class for Passes ----------------------*- 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 defines a base class that indicates that a specified class is a
10 // transformation pass implementation.
11 //
12 // Passes are designed this way so that it is possible to run passes in a cache
13 // and organizationally optimal order without having to specify it at the front
14 // end.  This allows arbitrary passes to be strung together and have them
15 // executed as efficiently as possible.
16 //
17 // Passes should extend one of the classes below, depending on the guarantees
18 // that it can make about what will be modified as it is run.  For example, most
19 // global optimizations should derive from FunctionPass, because they do not add
20 // or delete functions, they operate on the internals of the function.
21 //
22 // Note that this file #includes PassSupport.h and PassAnalysisSupport.h (at the
23 // bottom), so the APIs exposed by these files are also automatically available
24 // to all users of this file.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #ifndef LLVM_PASS_H
29 #define LLVM_PASS_H
30 
31 #include <string>
32 
33 namespace llvm {
34 
35 class AnalysisResolver;
36 class AnalysisUsage;
37 class Function;
38 class ImmutablePass;
39 class Module;
40 class PassInfo;
41 class PMDataManager;
42 class PMStack;
43 class raw_ostream;
44 class StringRef;
45 
46 // AnalysisID - Use the PassInfo to identify a pass...
47 using AnalysisID = const void *;
48 
49 /// Different types of internal pass managers. External pass managers
50 /// (PassManager and FunctionPassManager) are not represented here.
51 /// Ordering of pass manager types is important here.
52 enum PassManagerType {
53   PMT_Unknown = 0,
54   PMT_ModulePassManager = 1, ///< MPPassManager
55   PMT_CallGraphPassManager,  ///< CGPassManager
56   PMT_FunctionPassManager,   ///< FPPassManager
57   PMT_LoopPassManager,       ///< LPPassManager
58   PMT_RegionPassManager,     ///< RGPassManager
59   PMT_Last
60 };
61 
62 // Different types of passes.
63 enum PassKind {
64   PT_Region,
65   PT_Loop,
66   PT_Function,
67   PT_CallGraphSCC,
68   PT_Module,
69   PT_PassManager
70 };
71 
72 /// This enumerates the LLVM full LTO or ThinLTO optimization phases.
73 enum class ThinOrFullLTOPhase {
74   /// No LTO/ThinLTO behavior needed.
75   None,
76   /// ThinLTO prelink (summary) phase.
77   ThinLTOPreLink,
78   /// ThinLTO postlink (backend compile) phase.
79   ThinLTOPostLink,
80   /// Full LTO prelink phase.
81   FullLTOPreLink,
82   /// Full LTO postlink (backend compile) phase.
83   FullLTOPostLink
84 };
85 
86 //===----------------------------------------------------------------------===//
87 /// Pass interface - Implemented by all 'passes'.  Subclass this if you are an
88 /// interprocedural optimization or you do not fit into any of the more
89 /// constrained passes described below.
90 ///
91 class Pass {
92   AnalysisResolver *Resolver = nullptr;  // Used to resolve analysis
93   const void *PassID;
94   PassKind Kind;
95 
96 public:
Pass(PassKind K,char & pid)97   explicit Pass(PassKind K, char &pid) : PassID(&pid), Kind(K) {}
98   Pass(const Pass &) = delete;
99   Pass &operator=(const Pass &) = delete;
100   virtual ~Pass();
101 
getPassKind()102   PassKind getPassKind() const { return Kind; }
103 
104   /// getPassName - Return a nice clean name for a pass.  This usually
105   /// implemented in terms of the name that is registered by one of the
106   /// Registration templates, but can be overloaded directly.
107   virtual StringRef getPassName() const;
108 
109   /// getPassID - Return the PassID number that corresponds to this pass.
getPassID()110   AnalysisID getPassID() const {
111     return PassID;
112   }
113 
114   /// doInitialization - Virtual method overridden by subclasses to do
115   /// any necessary initialization before any pass is run.
doInitialization(Module &)116   virtual bool doInitialization(Module &)  { return false; }
117 
118   /// doFinalization - Virtual method overriden by subclasses to do any
119   /// necessary clean up after all passes have run.
doFinalization(Module &)120   virtual bool doFinalization(Module &) { return false; }
121 
122   /// print - Print out the internal state of the pass.  This is called by
123   /// Analyze to print out the contents of an analysis.  Otherwise it is not
124   /// necessary to implement this method.  Beware that the module pointer MAY be
125   /// null.  This automatically forwards to a virtual function that does not
126   /// provide the Module* in case the analysis doesn't need it it can just be
127   /// ignored.
128   virtual void print(raw_ostream &OS, const Module *M) const;
129 
130   void dump() const; // dump - Print to stderr.
131 
132   /// createPrinterPass - Get a Pass appropriate to print the IR this
133   /// pass operates on (Module, Function or MachineFunction).
134   virtual Pass *createPrinterPass(raw_ostream &OS,
135                                   const std::string &Banner) const = 0;
136 
137   /// Each pass is responsible for assigning a pass manager to itself.
138   /// PMS is the stack of available pass manager.
assignPassManager(PMStack &,PassManagerType)139   virtual void assignPassManager(PMStack &,
140                                  PassManagerType) {}
141 
142   /// Check if available pass managers are suitable for this pass or not.
143   virtual void preparePassManager(PMStack &);
144 
145   ///  Return what kind of Pass Manager can manage this pass.
146   virtual PassManagerType getPotentialPassManagerType() const;
147 
148   // Access AnalysisResolver
149   void setResolver(AnalysisResolver *AR);
getResolver()150   AnalysisResolver *getResolver() const { return Resolver; }
151 
152   /// getAnalysisUsage - This function should be overriden by passes that need
153   /// analysis information to do their job.  If a pass specifies that it uses a
154   /// particular analysis result to this function, it can then use the
155   /// getAnalysis<AnalysisType>() function, below.
156   virtual void getAnalysisUsage(AnalysisUsage &) const;
157 
158   /// releaseMemory() - This member can be implemented by a pass if it wants to
159   /// be able to release its memory when it is no longer needed.  The default
160   /// behavior of passes is to hold onto memory for the entire duration of their
161   /// lifetime (which is the entire compile time).  For pipelined passes, this
162   /// is not a big deal because that memory gets recycled every time the pass is
163   /// invoked on another program unit.  For IP passes, it is more important to
164   /// free memory when it is unused.
165   ///
166   /// Optionally implement this function to release pass memory when it is no
167   /// longer used.
168   virtual void releaseMemory();
169 
170   /// getAdjustedAnalysisPointer - This method is used when a pass implements
171   /// an analysis interface through multiple inheritance.  If needed, it should
172   /// override this to adjust the this pointer as needed for the specified pass
173   /// info.
174   virtual void *getAdjustedAnalysisPointer(AnalysisID ID);
175   virtual ImmutablePass *getAsImmutablePass();
176   virtual PMDataManager *getAsPMDataManager();
177 
178   /// verifyAnalysis() - This member can be implemented by a analysis pass to
179   /// check state of analysis information.
180   virtual void verifyAnalysis() const;
181 
182   // dumpPassStructure - Implement the -debug-passes=PassStructure option
183   virtual void dumpPassStructure(unsigned Offset = 0);
184 
185   // lookupPassInfo - Return the pass info object for the specified pass class,
186   // or null if it is not known.
187   static const PassInfo *lookupPassInfo(const void *TI);
188 
189   // lookupPassInfo - Return the pass info object for the pass with the given
190   // argument string, or null if it is not known.
191   static const PassInfo *lookupPassInfo(StringRef Arg);
192 
193   // createPass - Create a object for the specified pass class,
194   // or null if it is not known.
195   static Pass *createPass(AnalysisID ID);
196 
197   /// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to
198   /// get analysis information that might be around, for example to update it.
199   /// This is different than getAnalysis in that it can fail (if the analysis
200   /// results haven't been computed), so should only be used if you can handle
201   /// the case when the analysis is not available.  This method is often used by
202   /// transformation APIs to update analysis results for a pass automatically as
203   /// the transform is performed.
204   template<typename AnalysisType> AnalysisType *
205     getAnalysisIfAvailable() const; // Defined in PassAnalysisSupport.h
206 
207   /// mustPreserveAnalysisID - This method serves the same function as
208   /// getAnalysisIfAvailable, but works if you just have an AnalysisID.  This
209   /// obviously cannot give you a properly typed instance of the class if you
210   /// don't have the class name available (use getAnalysisIfAvailable if you
211   /// do), but it can tell you if you need to preserve the pass at least.
212   bool mustPreserveAnalysisID(char &AID) const;
213 
214   /// getAnalysis<AnalysisType>() - This function is used by subclasses to get
215   /// to the analysis information that they claim to use by overriding the
216   /// getAnalysisUsage function.
217   template<typename AnalysisType>
218   AnalysisType &getAnalysis() const; // Defined in PassAnalysisSupport.h
219 
220   template <typename AnalysisType>
221   AnalysisType &
222   getAnalysis(Function &F,
223               bool *Changed = nullptr); // Defined in PassAnalysisSupport.h
224 
225   template<typename AnalysisType>
226   AnalysisType &getAnalysisID(AnalysisID PI) const;
227 
228   template <typename AnalysisType>
229   AnalysisType &getAnalysisID(AnalysisID PI, Function &F,
230                               bool *Changed = nullptr);
231 };
232 
233 //===----------------------------------------------------------------------===//
234 /// ModulePass class - This class is used to implement unstructured
235 /// interprocedural optimizations and analyses.  ModulePasses may do anything
236 /// they want to the program.
237 ///
238 class ModulePass : public Pass {
239 public:
ModulePass(char & pid)240   explicit ModulePass(char &pid) : Pass(PT_Module, pid) {}
241 
242   // Force out-of-line virtual method.
243   ~ModulePass() override;
244 
245   /// createPrinterPass - Get a module printer pass.
246   Pass *createPrinterPass(raw_ostream &OS,
247                           const std::string &Banner) const override;
248 
249   /// runOnModule - Virtual method overriden by subclasses to process the module
250   /// being operated on.
251   virtual bool runOnModule(Module &M) = 0;
252 
253   void assignPassManager(PMStack &PMS, PassManagerType T) override;
254 
255   ///  Return what kind of Pass Manager can manage this pass.
256   PassManagerType getPotentialPassManagerType() const override;
257 
258 protected:
259   /// Optional passes call this function to check whether the pass should be
260   /// skipped. This is the case when optimization bisect is over the limit.
261   bool skipModule(Module &M) const;
262 };
263 
264 //===----------------------------------------------------------------------===//
265 /// ImmutablePass class - This class is used to provide information that does
266 /// not need to be run.  This is useful for things like target information and
267 /// "basic" versions of AnalysisGroups.
268 ///
269 class ImmutablePass : public ModulePass {
270 public:
ImmutablePass(char & pid)271   explicit ImmutablePass(char &pid) : ModulePass(pid) {}
272 
273   // Force out-of-line virtual method.
274   ~ImmutablePass() override;
275 
276   /// initializePass - This method may be overriden by immutable passes to allow
277   /// them to perform various initialization actions they require.  This is
278   /// primarily because an ImmutablePass can "require" another ImmutablePass,
279   /// and if it does, the overloaded version of initializePass may get access to
280   /// these passes with getAnalysis<>.
281   virtual void initializePass();
282 
getAsImmutablePass()283   ImmutablePass *getAsImmutablePass() override { return this; }
284 
285   /// ImmutablePasses are never run.
runOnModule(Module &)286   bool runOnModule(Module &) override { return false; }
287 };
288 
289 //===----------------------------------------------------------------------===//
290 /// FunctionPass class - This class is used to implement most global
291 /// optimizations.  Optimizations should subclass this class if they meet the
292 /// following constraints:
293 ///
294 ///  1. Optimizations are organized globally, i.e., a function at a time
295 ///  2. Optimizing a function does not cause the addition or removal of any
296 ///     functions in the module
297 ///
298 class FunctionPass : public Pass {
299 public:
FunctionPass(char & pid)300   explicit FunctionPass(char &pid) : Pass(PT_Function, pid) {}
301 
302   /// createPrinterPass - Get a function printer pass.
303   Pass *createPrinterPass(raw_ostream &OS,
304                           const std::string &Banner) const override;
305 
306   /// runOnFunction - Virtual method overriden by subclasses to do the
307   /// per-function processing of the pass.
308   virtual bool runOnFunction(Function &F) = 0;
309 
310   void assignPassManager(PMStack &PMS, PassManagerType T) override;
311 
312   ///  Return what kind of Pass Manager can manage this pass.
313   PassManagerType getPotentialPassManagerType() const override;
314 
315 protected:
316   /// Optional passes call this function to check whether the pass should be
317   /// skipped. This is the case when Attribute::OptimizeNone is set or when
318   /// optimization bisect is over the limit.
319   bool skipFunction(const Function &F) const;
320 };
321 
322 /// If the user specifies the -time-passes argument on an LLVM tool command line
323 /// then the value of this boolean will be true, otherwise false.
324 /// This is the storage for the -time-passes option.
325 extern bool TimePassesIsEnabled;
326 /// If TimePassesPerRun is true, there would be one line of report for
327 /// each pass invocation.
328 /// If TimePassesPerRun is false, there would be only one line of
329 /// report for each pass (even there are more than one pass objects).
330 /// (For new pass manager only)
331 extern bool TimePassesPerRun;
332 
333 } // end namespace llvm
334 
335 // Include support files that contain important APIs commonly used by Passes,
336 // but that we want to separate out to make it easier to read the header files.
337 #include "llvm/PassAnalysisSupport.h"
338 #include "llvm/PassSupport.h"
339 
340 #endif // LLVM_PASS_H
341