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