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