xref: /freebsd/contrib/llvm-project/llvm/include/llvm/CodeGen/TargetPassConfig.h (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
1 //===- TargetPassConfig.h - Code Generation pass options --------*- 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 /// \file
9 /// Target-Independent Code Generator Pass Configuration Options pass.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H
14 #define LLVM_CODEGEN_TARGETPASSCONFIG_H
15 
16 #include "llvm/Pass.h"
17 #include "llvm/Support/CodeGen.h"
18 #include <cassert>
19 #include <string>
20 
21 namespace llvm {
22 
23 class LLVMTargetMachine;
24 struct MachineSchedContext;
25 class PassConfigImpl;
26 class ScheduleDAGInstrs;
27 class CSEConfigBase;
28 class PassInstrumentationCallbacks;
29 
30 // The old pass manager infrastructure is hidden in a legacy namespace now.
31 namespace legacy {
32 
33 class PassManagerBase;
34 
35 } // end namespace legacy
36 
37 using legacy::PassManagerBase;
38 
39 /// Discriminated union of Pass ID types.
40 ///
41 /// The PassConfig API prefers dealing with IDs because they are safer and more
42 /// efficient. IDs decouple configuration from instantiation. This way, when a
43 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
44 /// refer to a Pass pointer after adding it to a pass manager, which deletes
45 /// redundant pass instances.
46 ///
47 /// However, it is convient to directly instantiate target passes with
48 /// non-default ctors. These often don't have a registered PassInfo. Rather than
49 /// force all target passes to implement the pass registry boilerplate, allow
50 /// the PassConfig API to handle either type.
51 ///
52 /// AnalysisID is sadly char*, so PointerIntPair won't work.
53 class IdentifyingPassPtr {
54   union {
55     AnalysisID ID;
56     Pass *P;
57   };
58   bool IsInstance = false;
59 
60 public:
61   IdentifyingPassPtr() : P(nullptr) {}
62   IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr) {}
63   IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
64 
65   bool isValid() const { return P; }
66   bool isInstance() const { return IsInstance; }
67 
68   AnalysisID getID() const {
69     assert(!IsInstance && "Not a Pass ID");
70     return ID;
71   }
72 
73   Pass *getInstance() const {
74     assert(IsInstance && "Not a Pass Instance");
75     return P;
76   }
77 };
78 
79 
80 /// Target-Independent Code Generator Pass Configuration Options.
81 ///
82 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
83 /// to the internals of other CodeGen passes.
84 class TargetPassConfig : public ImmutablePass {
85 private:
86   PassManagerBase *PM = nullptr;
87   AnalysisID StartBefore = nullptr;
88   AnalysisID StartAfter = nullptr;
89   AnalysisID StopBefore = nullptr;
90   AnalysisID StopAfter = nullptr;
91 
92   unsigned StartBeforeInstanceNum = 0;
93   unsigned StartBeforeCount = 0;
94 
95   unsigned StartAfterInstanceNum = 0;
96   unsigned StartAfterCount = 0;
97 
98   unsigned StopBeforeInstanceNum = 0;
99   unsigned StopBeforeCount = 0;
100 
101   unsigned StopAfterInstanceNum = 0;
102   unsigned StopAfterCount = 0;
103 
104   bool Started = true;
105   bool Stopped = false;
106   bool AddingMachinePasses = false;
107   bool DebugifyIsSafe = true;
108 
109   /// Set the StartAfter, StartBefore and StopAfter passes to allow running only
110   /// a portion of the normal code-gen pass sequence.
111   ///
112   /// If the StartAfter and StartBefore pass ID is zero, then compilation will
113   /// begin at the normal point; otherwise, clear the Started flag to indicate
114   /// that passes should not be added until the starting pass is seen.  If the
115   /// Stop pass ID is zero, then compilation will continue to the end.
116   ///
117   /// This function expects that at least one of the StartAfter or the
118   /// StartBefore pass IDs is null.
119   void setStartStopPasses();
120 
121 protected:
122   LLVMTargetMachine *TM;
123   PassConfigImpl *Impl = nullptr; // Internal data structures
124   bool Initialized = false; // Flagged after all passes are configured.
125 
126   // Target Pass Options
127   // Targets provide a default setting, user flags override.
128   bool DisableVerify = false;
129 
130   /// Default setting for -enable-tail-merge on this target.
131   bool EnableTailMerge = true;
132 
133   /// Enable sinking of instructions in MachineSink where a computation can be
134   /// folded into the addressing mode of a memory load/store instruction or
135   /// replace a copy.
136   bool EnableSinkAndFold = false;
137 
138   /// Require processing of functions such that callees are generated before
139   /// callers.
140   bool RequireCodeGenSCCOrder = false;
141 
142   /// Add the actual instruction selection passes. This does not include
143   /// preparation passes on IR.
144   bool addCoreISelPasses();
145 
146 public:
147   TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm);
148   // Dummy constructor.
149   TargetPassConfig();
150 
151   ~TargetPassConfig() override;
152 
153   static char ID;
154 
155   /// Get the right type of TargetMachine for this target.
156   template<typename TMC> TMC &getTM() const {
157     return *static_cast<TMC*>(TM);
158   }
159 
160   //
161   void setInitialized() { Initialized = true; }
162 
163   CodeGenOptLevel getOptLevel() const;
164 
165   /// Returns true if one of the `-start-after`, `-start-before`, `-stop-after`
166   /// or `-stop-before` options is set.
167   static bool hasLimitedCodeGenPipeline();
168 
169   /// Returns true if none of the `-stop-before` and `-stop-after` options is
170   /// set.
171   static bool willCompleteCodeGenPipeline();
172 
173   /// If hasLimitedCodeGenPipeline is true, this method
174   /// returns a string with the name of the options, separated
175   /// by \p Separator that caused this pipeline to be limited.
176   static std::string
177   getLimitedCodeGenPipelineReason(const char *Separator = "/");
178 
179   void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
180 
181   bool getEnableTailMerge() const { return EnableTailMerge; }
182   void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
183 
184   bool getEnableSinkAndFold() const { return EnableSinkAndFold; }
185   void setEnableSinkAndFold(bool Enable) { setOpt(EnableSinkAndFold, Enable); }
186 
187   bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder; }
188   void setRequiresCodeGenSCCOrder(bool Enable = true) {
189     setOpt(RequireCodeGenSCCOrder, Enable);
190   }
191 
192   /// Allow the target to override a specific pass without overriding the pass
193   /// pipeline. When passes are added to the standard pipeline at the
194   /// point where StandardID is expected, add TargetID in its place.
195   void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
196 
197   /// Insert InsertedPassID pass after TargetPassID pass.
198   void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
199 
200   /// Allow the target to enable a specific standard pass by default.
201   void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
202 
203   /// Allow the target to disable a specific standard pass by default.
204   void disablePass(AnalysisID PassID) {
205     substitutePass(PassID, IdentifyingPassPtr());
206   }
207 
208   /// Return the pass substituted for StandardID by the target.
209   /// If no substitution exists, return StandardID.
210   IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
211 
212   /// Return true if the pass has been substituted by the target or
213   /// overridden on the command line.
214   bool isPassSubstitutedOrOverridden(AnalysisID ID) const;
215 
216   /// Return true if the optimized regalloc pipeline is enabled.
217   bool getOptimizeRegAlloc() const;
218 
219   /// Return true if the default global register allocator is in use and
220   /// has not be overriden on the command line with '-regalloc=...'
221   bool usingDefaultRegAlloc() const;
222 
223   /// High level function that adds all passes necessary to go from llvm IR
224   /// representation to the MI representation.
225   /// Adds IR based lowering and target specific optimization passes and finally
226   /// the core instruction selection passes.
227   /// \returns true if an error occurred, false otherwise.
228   bool addISelPasses();
229 
230   /// Add common target configurable passes that perform LLVM IR to IR
231   /// transforms following machine independent optimization.
232   virtual void addIRPasses();
233 
234   /// Add passes to lower exception handling for the code generator.
235   void addPassesToHandleExceptions();
236 
237   /// Add pass to prepare the LLVM IR for code generation. This should be done
238   /// before exception handling preparation passes.
239   virtual void addCodeGenPrepare();
240 
241   /// Add common passes that perform LLVM IR to IR transforms in preparation for
242   /// instruction selection.
243   virtual void addISelPrepare();
244 
245   /// addInstSelector - This method should install an instruction selector pass,
246   /// which converts from LLVM code to machine instructions.
247   virtual bool addInstSelector() {
248     return true;
249   }
250 
251   /// This method should install an IR translator pass, which converts from
252   /// LLVM code to machine instructions with possibly generic opcodes.
253   virtual bool addIRTranslator() { return true; }
254 
255   /// This method may be implemented by targets that want to run passes
256   /// immediately before legalization.
257   virtual void addPreLegalizeMachineIR() {}
258 
259   /// This method should install a legalize pass, which converts the instruction
260   /// sequence into one that can be selected by the target.
261   virtual bool addLegalizeMachineIR() { return true; }
262 
263   /// This method may be implemented by targets that want to run passes
264   /// immediately before the register bank selection.
265   virtual void addPreRegBankSelect() {}
266 
267   /// This method should install a register bank selector pass, which
268   /// assigns register banks to virtual registers without a register
269   /// class or register banks.
270   virtual bool addRegBankSelect() { return true; }
271 
272   /// This method may be implemented by targets that want to run passes
273   /// immediately before the (global) instruction selection.
274   virtual void addPreGlobalInstructionSelect() {}
275 
276   /// This method should install a (global) instruction selector pass, which
277   /// converts possibly generic instructions to fully target-specific
278   /// instructions, thereby constraining all generic virtual registers to
279   /// register classes.
280   virtual bool addGlobalInstructionSelect() { return true; }
281 
282   /// Add the complete, standard set of LLVM CodeGen passes.
283   /// Fully developed targets will not generally override this.
284   virtual void addMachinePasses();
285 
286   /// Create an instance of ScheduleDAGInstrs to be run within the standard
287   /// MachineScheduler pass for this function and target at the current
288   /// optimization level.
289   ///
290   /// This can also be used to plug a new MachineSchedStrategy into an instance
291   /// of the standard ScheduleDAGMI:
292   ///   return new ScheduleDAGMI(C, std::make_unique<MyStrategy>(C), /*RemoveKillFlags=*/false)
293   ///
294   /// Return NULL to select the default (generic) machine scheduler.
295   virtual ScheduleDAGInstrs *
296   createMachineScheduler(MachineSchedContext *C) const {
297     return nullptr;
298   }
299 
300   /// Similar to createMachineScheduler but used when postRA machine scheduling
301   /// is enabled.
302   virtual ScheduleDAGInstrs *
303   createPostMachineScheduler(MachineSchedContext *C) const {
304     return nullptr;
305   }
306 
307   /// printAndVerify - Add a pass to dump then verify the machine function, if
308   /// those steps are enabled.
309   void printAndVerify(const std::string &Banner);
310 
311   /// Add a pass to print the machine function if printing is enabled.
312   void addPrintPass(const std::string &Banner);
313 
314   /// Add a pass to perform basic verification of the machine function if
315   /// verification is enabled.
316   void addVerifyPass(const std::string &Banner);
317 
318   /// Add a pass to add synthesized debug info to the MIR.
319   void addDebugifyPass();
320 
321   /// Add a pass to remove debug info from the MIR.
322   void addStripDebugPass();
323 
324   /// Add a pass to check synthesized debug info for MIR.
325   void addCheckDebugPass();
326 
327   /// Add standard passes before a pass that's about to be added. For example,
328   /// the DebugifyMachineModulePass if it is enabled.
329   void addMachinePrePasses(bool AllowDebugify = true);
330 
331   /// Add standard passes after a pass that has just been added. For example,
332   /// the MachineVerifier if it is enabled.
333   void addMachinePostPasses(const std::string &Banner);
334 
335   /// Check whether or not GlobalISel should abort on error.
336   /// When this is disabled, GlobalISel will fall back on SDISel instead of
337   /// erroring out.
338   bool isGlobalISelAbortEnabled() const;
339 
340   /// Check whether or not a diagnostic should be emitted when GlobalISel
341   /// uses the fallback path. In other words, it will emit a diagnostic
342   /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
343   virtual bool reportDiagnosticWhenGlobalISelFallback() const;
344 
345   /// Check whether continuous CSE should be enabled in GISel passes.
346   /// By default, it's enabled for non O0 levels.
347   virtual bool isGISelCSEEnabled() const;
348 
349   /// Returns the CSEConfig object to use for the current optimization level.
350   virtual std::unique_ptr<CSEConfigBase> getCSEConfig() const;
351 
352 protected:
353   // Helper to verify the analysis is really immutable.
354   void setOpt(bool &Opt, bool Val);
355 
356   /// Return true if register allocator is specified by -regalloc=override.
357   bool isCustomizedRegAlloc();
358 
359   /// Methods with trivial inline returns are convenient points in the common
360   /// codegen pass pipeline where targets may insert passes. Methods with
361   /// out-of-line standard implementations are major CodeGen stages called by
362   /// addMachinePasses. Some targets may override major stages when inserting
363   /// passes is insufficient, but maintaining overriden stages is more work.
364   ///
365 
366   /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
367   /// passes (which are run just before instruction selector).
368   virtual bool addPreISel() {
369     return true;
370   }
371 
372   /// addMachineSSAOptimization - Add standard passes that optimize machine
373   /// instructions in SSA form.
374   virtual void addMachineSSAOptimization();
375 
376   /// Add passes that optimize instruction level parallelism for out-of-order
377   /// targets. These passes are run while the machine code is still in SSA
378   /// form, so they can use MachineTraceMetrics to control their heuristics.
379   ///
380   /// All passes added here should preserve the MachineDominatorTree,
381   /// MachineLoopInfo, and MachineTraceMetrics analyses.
382   virtual bool addILPOpts() {
383     return false;
384   }
385 
386   /// This method may be implemented by targets that want to run passes
387   /// immediately before register allocation.
388   virtual void addPreRegAlloc() { }
389 
390   /// createTargetRegisterAllocator - Create the register allocator pass for
391   /// this target at the current optimization level.
392   virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
393 
394   /// addFastRegAlloc - Add the minimum set of target-independent passes that
395   /// are required for fast register allocation.
396   virtual void addFastRegAlloc();
397 
398   /// addOptimizedRegAlloc - Add passes related to register allocation.
399   /// LLVMTargetMachine provides standard regalloc passes for most targets.
400   virtual void addOptimizedRegAlloc();
401 
402   /// addPreRewrite - Add passes to the optimized register allocation pipeline
403   /// after register allocation is complete, but before virtual registers are
404   /// rewritten to physical registers.
405   ///
406   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
407   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
408   /// When these passes run, VirtRegMap contains legal physreg assignments for
409   /// all virtual registers.
410   ///
411   /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
412   /// be honored. This is also not generally used for the fast variant,
413   /// where the allocation and rewriting are done in one pass.
414   virtual bool addPreRewrite() {
415     return false;
416   }
417 
418   /// addPostFastRegAllocRewrite - Add passes to the optimized register
419   /// allocation pipeline after fast register allocation is complete.
420   virtual bool addPostFastRegAllocRewrite() { return false; }
421 
422   /// Add passes to be run immediately after virtual registers are rewritten
423   /// to physical registers.
424   virtual void addPostRewrite() { }
425 
426   /// This method may be implemented by targets that want to run passes after
427   /// register allocation pass pipeline but before prolog-epilog insertion.
428   virtual void addPostRegAlloc() { }
429 
430   /// Add passes that optimize machine instructions after register allocation.
431   virtual void addMachineLateOptimization();
432 
433   /// This method may be implemented by targets that want to run passes after
434   /// prolog-epilog insertion and before the second instruction scheduling pass.
435   virtual void addPreSched2() { }
436 
437   /// addGCPasses - Add late codegen passes that analyze code for garbage
438   /// collection. This should return true if GC info should be printed after
439   /// these passes.
440   virtual bool addGCPasses();
441 
442   /// Add standard basic block placement passes.
443   virtual void addBlockPlacement();
444 
445   /// This pass may be implemented by targets that want to run passes
446   /// immediately before machine code is emitted.
447   virtual void addPreEmitPass() { }
448 
449   /// This pass may be implemented by targets that want to run passes
450   /// immediately after basic block sections are assigned.
451   virtual void addPostBBSections() {}
452 
453   /// Targets may add passes immediately before machine code is emitted in this
454   /// callback. This is called even later than `addPreEmitPass`.
455   // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
456   // position and remove the `2` suffix here as this callback is what
457   // `addPreEmitPass` *should* be but in reality isn't.
458   virtual void addPreEmitPass2() {}
459 
460   /// Utilities for targets to add passes to the pass manager.
461   ///
462 
463   /// Add a CodeGen pass at this point in the pipeline after checking overrides.
464   /// Return the pass that was added, or zero if no pass was added.
465   AnalysisID addPass(AnalysisID PassID);
466 
467   /// Add a pass to the PassManager if that pass is supposed to be run, as
468   /// determined by the StartAfter and StopAfter options. Takes ownership of the
469   /// pass.
470   void addPass(Pass *P);
471 
472   /// addMachinePasses helper to create the target-selected or overriden
473   /// regalloc pass.
474   virtual FunctionPass *createRegAllocPass(bool Optimized);
475 
476   /// Add core register allocator passes which do the actual register assignment
477   /// and rewriting. \returns true if any passes were added.
478   virtual bool addRegAssignAndRewriteFast();
479   virtual bool addRegAssignAndRewriteOptimized();
480 };
481 
482 void registerCodeGenCallback(PassInstrumentationCallbacks &PIC,
483                              LLVMTargetMachine &);
484 
485 } // end namespace llvm
486 
487 #endif // LLVM_CODEGEN_TARGETPASSCONFIG_H
488