1 //===-- llvm/Target/TargetMachine.h - Target Information --------*- 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 // This file defines the TargetMachine and LLVMTargetMachine classes.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_TARGET_TARGETMACHINE_H
14 #define LLVM_TARGET_TARGETMACHINE_H
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/CodeGen.h"
21 #include "llvm/Target/TargetOptions.h"
28 class MachineModuleInfoWrapperPass;
34 class MCSubtargetInfo;
36 class raw_pwrite_stream;
37 class PassManagerBuilder;
38 struct PerFunctionMIParsingState;
42 class TargetIntrinsicInfo;
43 class TargetIRAnalysis;
44 class TargetTransformInfo;
45 class TargetLoweringObjectFile;
46 class TargetPassConfig;
47 class TargetSubtargetInfo;
49 // The old pass manager infrastructure is hidden in a legacy namespace now.
51 class PassManagerBase;
53 using legacy::PassManagerBase;
56 struct MachineFunctionInfo;
59 //===----------------------------------------------------------------------===//
61 /// Primary interface to the complete machine description for the target
62 /// machine. All target-specific information should be accessible through this
66 protected: // Can only create subclasses.
67 TargetMachine(const Target &T, StringRef DataLayoutString,
68 const Triple &TargetTriple, StringRef CPU, StringRef FS,
69 const TargetOptions &Options);
71 /// The Target that this machine was created for.
72 const Target &TheTarget;
74 /// DataLayout for the target: keep ABI type size and alignment.
76 /// The DataLayout is created based on the string representation provided
77 /// during construction. It is kept here only to avoid reparsing the string
78 /// but should not really be used during compilation, because it has an
79 /// internal cache that is context specific.
82 /// Triple string, CPU name, and target feature strings the TargetMachine
83 /// instance is created with.
85 std::string TargetCPU;
88 Reloc::Model RM = Reloc::Static;
89 CodeModel::Model CMModel = CodeModel::Small;
90 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
92 /// Contains target specific asm information.
93 std::unique_ptr<const MCAsmInfo> AsmInfo;
94 std::unique_ptr<const MCRegisterInfo> MRI;
95 std::unique_ptr<const MCInstrInfo> MII;
96 std::unique_ptr<const MCSubtargetInfo> STI;
98 unsigned RequireStructuredCFG : 1;
99 unsigned O0WantsFastISel : 1;
102 const TargetOptions DefaultOptions;
103 mutable TargetOptions Options;
105 TargetMachine(const TargetMachine &) = delete;
106 void operator=(const TargetMachine &) = delete;
107 virtual ~TargetMachine();
109 const Target &getTarget() const { return TheTarget; }
111 const Triple &getTargetTriple() const { return TargetTriple; }
112 StringRef getTargetCPU() const { return TargetCPU; }
113 StringRef getTargetFeatureString() const { return TargetFS; }
115 /// Virtual method implemented by subclasses that returns a reference to that
116 /// target's TargetSubtargetInfo-derived member variable.
117 virtual const TargetSubtargetInfo *getSubtargetImpl(const Function &) const {
120 virtual TargetLoweringObjectFile *getObjFileLowering() const {
124 /// Allocate and return a default initialized instance of the YAML
125 /// representation for the MachineFunctionInfo.
126 virtual yaml::MachineFunctionInfo *createDefaultFuncInfoYAML() const {
130 /// Allocate and initialize an instance of the YAML representation of the
131 /// MachineFunctionInfo.
132 virtual yaml::MachineFunctionInfo *
133 convertFuncInfoToYAML(const MachineFunction &MF) const {
137 /// Parse out the target's MachineFunctionInfo from the YAML reprsentation.
138 virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &,
139 PerFunctionMIParsingState &PFS,
141 SMRange &SourceRange) const {
145 /// This method returns a pointer to the specified type of
146 /// TargetSubtargetInfo. In debug builds, it verifies that the object being
147 /// returned is of the correct type.
148 template <typename STC> const STC &getSubtarget(const Function &F) const {
149 return *static_cast<const STC*>(getSubtargetImpl(F));
152 /// Create a DataLayout.
153 const DataLayout createDataLayout() const { return DL; }
155 /// Test if a DataLayout if compatible with the CodeGen for this target.
157 /// The LLVM Module owns a DataLayout that is used for the target independent
158 /// optimizations and code generation. This hook provides a target specific
159 /// check on the validity of this DataLayout.
160 bool isCompatibleDataLayout(const DataLayout &Candidate) const {
161 return DL == Candidate;
164 /// Get the pointer size for this target.
166 /// This is the only time the DataLayout in the TargetMachine is used.
167 unsigned getPointerSize(unsigned AS) const {
168 return DL.getPointerSize(AS);
171 unsigned getPointerSizeInBits(unsigned AS) const {
172 return DL.getPointerSizeInBits(AS);
175 unsigned getProgramPointerSize() const {
176 return DL.getPointerSize(DL.getProgramAddressSpace());
179 unsigned getAllocaPointerSize() const {
180 return DL.getPointerSize(DL.getAllocaAddrSpace());
183 /// Reset the target options based on the function's attributes.
184 // FIXME: Remove TargetOptions that affect per-function code generation
185 // from TargetMachine.
186 void resetTargetOptions(const Function &F) const;
188 /// Return target specific asm information.
189 const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); }
191 const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); }
192 const MCInstrInfo *getMCInstrInfo() const { return MII.get(); }
193 const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); }
195 /// If intrinsic information is available, return it. If not, return null.
196 virtual const TargetIntrinsicInfo *getIntrinsicInfo() const {
200 bool requiresStructuredCFG() const { return RequireStructuredCFG; }
201 void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; }
203 /// Returns the code generation relocation model. The choices are static, PIC,
204 /// and dynamic-no-pic, and target default.
205 Reloc::Model getRelocationModel() const;
207 /// Returns the code model. The choices are small, kernel, medium, large, and
209 CodeModel::Model getCodeModel() const;
211 bool isPositionIndependent() const;
213 bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const;
215 /// Returns true if this target uses emulated TLS.
216 bool useEmulatedTLS() const;
218 /// Returns the TLS model which should be used for the given global variable.
219 TLSModel::Model getTLSModel(const GlobalValue *GV) const;
221 /// Returns the optimization level: None, Less, Default, or Aggressive.
222 CodeGenOpt::Level getOptLevel() const;
224 /// Overrides the optimization level.
225 void setOptLevel(CodeGenOpt::Level Level);
227 void setFastISel(bool Enable) { Options.EnableFastISel = Enable; }
228 bool getO0WantsFastISel() { return O0WantsFastISel; }
229 void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; }
230 void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; }
231 void setGlobalISelAbort(GlobalISelAbortMode Mode) {
232 Options.GlobalISelAbort = Mode;
234 void setMachineOutliner(bool Enable) {
235 Options.EnableMachineOutliner = Enable;
237 void setSupportsDefaultOutlining(bool Enable) {
238 Options.SupportsDefaultOutlining = Enable;
240 void setSupportsDebugEntryValues(bool Enable) {
241 Options.SupportsDebugEntryValues = Enable;
244 bool shouldPrintMachineCode() const { return Options.PrintMachineCode; }
246 bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
248 /// Return true if unique basic block section names must be generated.
249 bool getUniqueBasicBlockSectionNames() const {
250 return Options.UniqueBasicBlockSectionNames;
253 /// Return true if data objects should be emitted into their own section,
254 /// corresponds to -fdata-sections.
255 bool getDataSections() const {
256 return Options.DataSections;
259 /// Return true if functions should be emitted into their own section,
260 /// corresponding to -ffunction-sections.
261 bool getFunctionSections() const {
262 return Options.FunctionSections;
265 /// If basic blocks should be emitted into their own section,
266 /// corresponding to -fbasic-block-sections.
267 llvm::BasicBlockSection getBBSectionsType() const {
268 return Options.BBSections;
271 /// Get the list of functions and basic block ids that need unique sections.
272 const MemoryBuffer *getBBSectionsFuncListBuf() const {
273 return Options.BBSectionsFuncListBuf.get();
276 /// Get a \c TargetIRAnalysis appropriate for the target.
278 /// This is used to construct the new pass manager's target IR analysis pass,
279 /// set up appropriately for this target machine. Even the old pass manager
280 /// uses this to answer queries about the IR.
281 TargetIRAnalysis getTargetIRAnalysis();
283 /// Return a TargetTransformInfo for a given function.
285 /// The returned TargetTransformInfo is specialized to the subtarget
286 /// corresponding to \p F.
287 virtual TargetTransformInfo getTargetTransformInfo(const Function &F);
289 /// Allow the target to modify the pass manager, e.g. by calling
290 /// PassManagerBuilder::addExtension.
291 virtual void adjustPassManager(PassManagerBuilder &) {}
293 /// Add passes to the specified pass manager to get the specified file
294 /// emitted. Typically this will involve several steps of code generation.
295 /// This method should return true if emission of this file type is not
296 /// supported, or false on success.
297 /// \p MMIWP is an optional parameter that, if set to non-nullptr,
298 /// will be used to set the MachineModuloInfo for this PM.
300 addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
301 raw_pwrite_stream *, CodeGenFileType,
302 bool /*DisableVerify*/ = true,
303 MachineModuleInfoWrapperPass *MMIWP = nullptr) {
307 /// Add passes to the specified pass manager to get machine code emitted with
308 /// the MCJIT. This method returns true if machine code is not supported. It
309 /// fills the MCContext Ctx pointer which can be used to build custom
312 virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
314 bool /*DisableVerify*/ = true) {
318 /// True if subtarget inserts the final scheduling pass on its own.
320 /// Branch relaxation, which must happen after block placement, can
321 /// on some targets (e.g. SystemZ) expose additional post-RA
322 /// scheduling opportunities.
323 virtual bool targetSchedulesPostRAScheduling() const { return false; };
325 void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
326 Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
327 MCSymbol *getSymbol(const GlobalValue *GV) const;
329 /// The integer bit size to use for SjLj based exception handling.
330 static constexpr unsigned DefaultSjLjDataSize = 32;
331 virtual unsigned getSjLjDataSize() const { return DefaultSjLjDataSize; }
334 /// This class describes a target machine that is implemented with the LLVM
335 /// target-independent code generator.
337 class LLVMTargetMachine : public TargetMachine {
338 protected: // Can only create subclasses.
339 LLVMTargetMachine(const Target &T, StringRef DataLayoutString,
340 const Triple &TT, StringRef CPU, StringRef FS,
341 const TargetOptions &Options, Reloc::Model RM,
342 CodeModel::Model CM, CodeGenOpt::Level OL);
347 /// Get a TargetTransformInfo implementation for the target.
349 /// The TTI returned uses the common code generator to answer queries about
351 TargetTransformInfo getTargetTransformInfo(const Function &F) override;
353 /// Create a pass configuration object to be used by addPassToEmitX methods
354 /// for generating a pipeline of CodeGen passes.
355 virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
357 /// Add passes to the specified pass manager to get the specified file
358 /// emitted. Typically this will involve several steps of code generation.
359 /// \p MMIWP is an optional parameter that, if set to non-nullptr,
360 /// will be used to set the MachineModuloInfo for this PM.
362 addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
363 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
364 bool DisableVerify = true,
365 MachineModuleInfoWrapperPass *MMIWP = nullptr) override;
367 /// Add passes to the specified pass manager to get machine code emitted with
368 /// the MCJIT. This method returns true if machine code is not supported. It
369 /// fills the MCContext Ctx pointer which can be used to build custom
371 bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
372 raw_pwrite_stream &Out,
373 bool DisableVerify = true) override;
375 /// Returns true if the target is expected to pass all machine verifier
376 /// checks. This is a stopgap measure to fix targets one by one. We will
377 /// remove this at some point and always enable the verifier when
378 /// EXPENSIVE_CHECKS is enabled.
379 virtual bool isMachineVerifierClean() const { return true; }
381 /// Adds an AsmPrinter pass to the pipeline that prints assembly or
382 /// machine code from the MI representation.
383 bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out,
384 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
387 /// True if the target uses physical regs (as nearly all targets do). False
388 /// for stack machines such as WebAssembly and other virtual-register
389 /// machines. If true, all vregs must be allocated before PEI. If false, then
390 /// callee-save register spilling and scavenging are not needed or used. If
391 /// false, implicitly defined registers will still be assumed to be physical
392 /// registers, except that variadic defs will be allocated vregs.
393 virtual bool usesPhysRegsForValues() const { return true; }
395 /// True if the target wants to use interprocedural register allocation by
396 /// default. The -enable-ipra flag can be used to override this.
397 virtual bool useIPRA() const {
402 /// Helper method for getting the code model, returning Default if
403 /// CM does not have a value. The tiny and kernel models will produce
404 /// an error, so targets that support them or require more complex codemodel
405 /// selection logic should implement and call their own getEffectiveCodeModel.
406 inline CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM,
407 CodeModel::Model Default) {
409 // By default, targets do not support the tiny and kernel models.
410 if (*CM == CodeModel::Tiny)
411 report_fatal_error("Target does not support the tiny CodeModel", false);
412 if (*CM == CodeModel::Kernel)
413 report_fatal_error("Target does not support the kernel CodeModel", false);
419 } // end namespace llvm
421 #endif // LLVM_TARGET_TARGETMACHINE_H