1 //===- TargetPassConfig.h - Code Generation pass options --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// Target-Independent Code Generator Pass Configuration Options pass.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H
15 #define LLVM_CODEGEN_TARGETPASSCONFIG_H
17 #include "llvm/Pass.h"
18 #include "llvm/Support/CodeGen.h"
24 class LLVMTargetMachine;
25 struct MachineSchedContext;
27 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");
78 template <> struct isPodLike<IdentifyingPassPtr> {
79 static const bool value = true;
82 /// Target-Independent Code Generator Pass Configuration Options.
84 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
85 /// to the internals of other CodeGen passes.
86 class TargetPassConfig : public ImmutablePass {
88 /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
89 /// are unregistered pass IDs. They are only useful for use with
90 /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
93 /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
94 /// during codegen, on SSA form.
95 static char EarlyTailDuplicateID;
97 /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
98 /// optimization after regalloc.
99 static char PostRAMachineLICMID;
102 PassManagerBase *PM = nullptr;
103 AnalysisID StartBefore = nullptr;
104 AnalysisID StartAfter = nullptr;
105 AnalysisID StopBefore = nullptr;
106 AnalysisID StopAfter = nullptr;
108 bool Stopped = false;
109 bool AddingMachinePasses = false;
111 /// Set the StartAfter, StartBefore and StopAfter passes to allow running only
112 /// a portion of the normal code-gen pass sequence.
114 /// If the StartAfter and StartBefore pass ID is zero, then compilation will
115 /// begin at the normal point; otherwise, clear the Started flag to indicate
116 /// that passes should not be added until the starting pass is seen. If the
117 /// Stop pass ID is zero, then compilation will continue to the end.
119 /// This function expects that at least one of the StartAfter or the
120 /// StartBefore pass IDs is null.
121 void setStartStopPasses();
124 LLVMTargetMachine *TM;
125 PassConfigImpl *Impl = nullptr; // Internal data structures
126 bool Initialized = false; // Flagged after all passes are configured.
128 // Target Pass Options
129 // Targets provide a default setting, user flags override.
130 bool DisableVerify = false;
132 /// Default setting for -enable-tail-merge on this target.
133 bool EnableTailMerge = true;
135 /// Require processing of functions such that callees are generated before
137 bool RequireCodeGenSCCOrder = false;
139 /// Add the actual instruction selection passes. This does not include
140 /// preparation passes on IR.
141 bool addCoreISelPasses();
144 TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm);
145 // Dummy constructor.
148 ~TargetPassConfig() override;
152 /// Get the right type of TargetMachine for this target.
153 template<typename TMC> TMC &getTM() const {
154 return *static_cast<TMC*>(TM);
158 void setInitialized() { Initialized = true; }
160 CodeGenOpt::Level getOptLevel() const;
162 /// Describe the status of the codegen
163 /// pipeline set by this target pass config.
164 /// Having a limited codegen pipeline means that options
165 /// have been used to restrict what codegen is doing.
166 /// In particular, that means that codegen won't emit
168 bool hasLimitedCodeGenPipeline() const;
170 /// If hasLimitedCodeGenPipeline is true, this method
171 /// returns a string with the name of the options, separated
172 /// by \p Separator that caused this pipeline to be limited.
174 getLimitedCodeGenPipelineReason(const char *Separator = "/") const;
176 /// Check if the codegen pipeline is limited in such a way that it
177 /// won't be complete. When the codegen pipeline is not complete,
178 /// this means it may not be possible to generate assembly from it.
179 bool willCompleteCodeGenPipeline() const {
180 return !hasLimitedCodeGenPipeline() || (!StopAfter && !StopBefore);
183 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
185 bool getEnableTailMerge() const { return EnableTailMerge; }
186 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
188 bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder; }
189 void setRequiresCodeGenSCCOrder(bool Enable = true) {
190 setOpt(RequireCodeGenSCCOrder, Enable);
193 /// Allow the target to override a specific pass without overriding the pass
194 /// pipeline. When passes are added to the standard pipeline at the
195 /// point where StandardID is expected, add TargetID in its place.
196 void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
198 /// Insert InsertedPassID pass after TargetPassID pass.
199 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
200 bool VerifyAfter = true, bool PrintAfter = true);
202 /// Allow the target to enable a specific standard pass by default.
203 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
205 /// Allow the target to disable a specific standard pass by default.
206 void disablePass(AnalysisID PassID) {
207 substitutePass(PassID, IdentifyingPassPtr());
210 /// Return the pass substituted for StandardID by the target.
211 /// If no substitution exists, return StandardID.
212 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
214 /// Return true if the pass has been substituted by the target or
215 /// overridden on the command line.
216 bool isPassSubstitutedOrOverridden(AnalysisID ID) const;
218 /// Return true if the optimized regalloc pipeline is enabled.
219 bool getOptimizeRegAlloc() const;
221 /// Return true if shrink wrapping is enabled.
222 bool getEnableShrinkWrap() const;
224 /// Return true if the default global register allocator is in use and
225 /// has not be overriden on the command line with '-regalloc=...'
226 bool usingDefaultRegAlloc() const;
228 /// High level function that adds all passes necessary to go from llvm IR
229 /// representation to the MI representation.
230 /// Adds IR based lowering and target specific optimization passes and finally
231 /// the core instruction selection passes.
232 /// \returns true if an error occured, false otherwise.
233 bool addISelPasses();
235 /// Add common target configurable passes that perform LLVM IR to IR
236 /// transforms following machine independent optimization.
237 virtual void addIRPasses();
239 /// Add passes to lower exception handling for the code generator.
240 void addPassesToHandleExceptions();
242 /// Add pass to prepare the LLVM IR for code generation. This should be done
243 /// before exception handling preparation passes.
244 virtual void addCodeGenPrepare();
246 /// Add common passes that perform LLVM IR to IR transforms in preparation for
247 /// instruction selection.
248 virtual void addISelPrepare();
250 /// addInstSelector - This method should install an instruction selector pass,
251 /// which converts from LLVM code to machine instructions.
252 virtual bool addInstSelector() {
256 /// This method should install an IR translator pass, which converts from
257 /// LLVM code to machine instructions with possibly generic opcodes.
258 virtual bool addIRTranslator() { return true; }
260 /// This method may be implemented by targets that want to run passes
261 /// immediately before legalization.
262 virtual void addPreLegalizeMachineIR() {}
264 /// This method should install a legalize pass, which converts the instruction
265 /// sequence into one that can be selected by the target.
266 virtual bool addLegalizeMachineIR() { return true; }
268 /// This method may be implemented by targets that want to run passes
269 /// immediately before the register bank selection.
270 virtual void addPreRegBankSelect() {}
272 /// This method should install a register bank selector pass, which
273 /// assigns register banks to virtual registers without a register
274 /// class or register banks.
275 virtual bool addRegBankSelect() { return true; }
277 /// This method may be implemented by targets that want to run passes
278 /// immediately before the (global) instruction selection.
279 virtual void addPreGlobalInstructionSelect() {}
281 /// This method should install a (global) instruction selector pass, which
282 /// converts possibly generic instructions to fully target-specific
283 /// instructions, thereby constraining all generic virtual registers to
284 /// register classes.
285 virtual bool addGlobalInstructionSelect() { return true; }
287 /// Add the complete, standard set of LLVM CodeGen passes.
288 /// Fully developed targets will not generally override this.
289 virtual void addMachinePasses();
291 /// Create an instance of ScheduleDAGInstrs to be run within the standard
292 /// MachineScheduler pass for this function and target at the current
293 /// optimization level.
295 /// This can also be used to plug a new MachineSchedStrategy into an instance
296 /// of the standard ScheduleDAGMI:
297 /// return new ScheduleDAGMI(C, make_unique<MyStrategy>(C), /*RemoveKillFlags=*/false)
299 /// Return NULL to select the default (generic) machine scheduler.
300 virtual ScheduleDAGInstrs *
301 createMachineScheduler(MachineSchedContext *C) const {
305 /// Similar to createMachineScheduler but used when postRA machine scheduling
307 virtual ScheduleDAGInstrs *
308 createPostMachineScheduler(MachineSchedContext *C) const {
312 /// printAndVerify - Add a pass to dump then verify the machine function, if
313 /// those steps are enabled.
314 void printAndVerify(const std::string &Banner);
316 /// Add a pass to print the machine function if printing is enabled.
317 void addPrintPass(const std::string &Banner);
319 /// Add a pass to perform basic verification of the machine function if
320 /// verification is enabled.
321 void addVerifyPass(const std::string &Banner);
323 /// Check whether or not GlobalISel should be enabled by default.
324 /// Fallback/abort behavior is controlled via other methods.
325 virtual bool isGlobalISelEnabled() const;
327 /// Check whether or not GlobalISel should abort on error.
328 /// When this is disabled, GlobalISel will fall back on SDISel instead of
330 bool isGlobalISelAbortEnabled() const;
332 /// Check whether or not a diagnostic should be emitted when GlobalISel
333 /// uses the fallback path. In other words, it will emit a diagnostic
334 /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
335 virtual bool reportDiagnosticWhenGlobalISelFallback() const;
338 // Helper to verify the analysis is really immutable.
339 void setOpt(bool &Opt, bool Val);
341 /// Methods with trivial inline returns are convenient points in the common
342 /// codegen pass pipeline where targets may insert passes. Methods with
343 /// out-of-line standard implementations are major CodeGen stages called by
344 /// addMachinePasses. Some targets may override major stages when inserting
345 /// passes is insufficient, but maintaining overriden stages is more work.
348 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
349 /// passes (which are run just before instruction selector).
350 virtual bool addPreISel() {
354 /// addMachineSSAOptimization - Add standard passes that optimize machine
355 /// instructions in SSA form.
356 virtual void addMachineSSAOptimization();
358 /// Add passes that optimize instruction level parallelism for out-of-order
359 /// targets. These passes are run while the machine code is still in SSA
360 /// form, so they can use MachineTraceMetrics to control their heuristics.
362 /// All passes added here should preserve the MachineDominatorTree,
363 /// MachineLoopInfo, and MachineTraceMetrics analyses.
364 virtual bool addILPOpts() {
368 /// This method may be implemented by targets that want to run passes
369 /// immediately before register allocation.
370 virtual void addPreRegAlloc() { }
372 /// createTargetRegisterAllocator - Create the register allocator pass for
373 /// this target at the current optimization level.
374 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
376 /// addFastRegAlloc - Add the minimum set of target-independent passes that
377 /// are required for fast register allocation.
378 virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
380 /// addOptimizedRegAlloc - Add passes related to register allocation.
381 /// LLVMTargetMachine provides standard regalloc passes for most targets.
382 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
384 /// addPreRewrite - Add passes to the optimized register allocation pipeline
385 /// after register allocation is complete, but before virtual registers are
386 /// rewritten to physical registers.
388 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
389 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
390 /// When these passes run, VirtRegMap contains legal physreg assignments for
391 /// all virtual registers.
392 virtual bool addPreRewrite() {
396 /// This method may be implemented by targets that want to run passes after
397 /// register allocation pass pipeline but before prolog-epilog insertion.
398 virtual void addPostRegAlloc() { }
400 /// Add passes that optimize machine instructions after register allocation.
401 virtual void addMachineLateOptimization();
403 /// This method may be implemented by targets that want to run passes after
404 /// prolog-epilog insertion and before the second instruction scheduling pass.
405 virtual void addPreSched2() { }
407 /// addGCPasses - Add late codegen passes that analyze code for garbage
408 /// collection. This should return true if GC info should be printed after
410 virtual bool addGCPasses();
412 /// Add standard basic block placement passes.
413 virtual void addBlockPlacement();
415 /// This pass may be implemented by targets that want to run passes
416 /// immediately before machine code is emitted.
417 virtual void addPreEmitPass() { }
419 /// Targets may add passes immediately before machine code is emitted in this
420 /// callback. This is called even later than `addPreEmitPass`.
421 // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
422 // position and remove the `2` suffix here as this callback is what
423 // `addPreEmitPass` *should* be but in reality isn't.
424 virtual void addPreEmitPass2() {}
426 /// Utilities for targets to add passes to the pass manager.
429 /// Add a CodeGen pass at this point in the pipeline after checking overrides.
430 /// Return the pass that was added, or zero if no pass was added.
431 /// @p printAfter if true and adding a machine function pass add an extra
432 /// machine printer pass afterwards
433 /// @p verifyAfter if true and adding a machine function pass add an extra
434 /// machine verification pass afterwards.
435 AnalysisID addPass(AnalysisID PassID, bool verifyAfter = true,
436 bool printAfter = true);
438 /// Add a pass to the PassManager if that pass is supposed to be run, as
439 /// determined by the StartAfter and StopAfter options. Takes ownership of the
441 /// @p printAfter if true and adding a machine function pass add an extra
442 /// machine printer pass afterwards
443 /// @p verifyAfter if true and adding a machine function pass add an extra
444 /// machine verification pass afterwards.
445 void addPass(Pass *P, bool verifyAfter = true, bool printAfter = true);
447 /// addMachinePasses helper to create the target-selected or overriden
449 FunctionPass *createRegAllocPass(bool Optimized);
452 } // end namespace llvm
454 #endif // LLVM_CODEGEN_TARGETPASSCONFIG_H