LLVM  9.0.0svn
TargetMachine.h
Go to the documentation of this file.
1 //===-- llvm/Target/TargetMachine.h - Target Information --------*- 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 the TargetMachine and LLVMTargetMachine classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_TARGET_TARGETMACHINE_H
14 #define LLVM_TARGET_TARGETMACHINE_H
15 
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"
22 #include <string>
23 
24 namespace llvm {
25 
26 class Function;
27 class GlobalValue;
28 class MachineModuleInfo;
29 class Mangler;
30 class MCAsmInfo;
31 class MCContext;
32 class MCInstrInfo;
33 class MCRegisterInfo;
34 class MCSubtargetInfo;
35 class MCSymbol;
36 class raw_pwrite_stream;
37 class PassManagerBuilder;
38 struct PerFunctionMIParsingState;
39 class SMDiagnostic;
40 class SMRange;
41 class Target;
42 class TargetIntrinsicInfo;
43 class TargetIRAnalysis;
44 class TargetTransformInfo;
45 class TargetLoweringObjectFile;
46 class TargetPassConfig;
47 class TargetSubtargetInfo;
48 
49 // The old pass manager infrastructure is hidden in a legacy namespace now.
50 namespace legacy {
51 class PassManagerBase;
52 }
53 using legacy::PassManagerBase;
54 
55 namespace yaml {
56 struct MachineFunctionInfo;
57 }
58 
59 //===----------------------------------------------------------------------===//
60 ///
61 /// Primary interface to the complete machine description for the target
62 /// machine. All target-specific information should be accessible through this
63 /// interface.
64 ///
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);
70 
71  /// The Target that this machine was created for.
72  const Target &TheTarget;
73 
74  /// DataLayout for the target: keep ABI type size and alignment.
75  ///
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.
80  const DataLayout DL;
81 
82  /// Triple string, CPU name, and target feature strings the TargetMachine
83  /// instance is created with.
85  std::string TargetCPU;
86  std::string TargetFS;
87 
91 
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;
97 
98  unsigned RequireStructuredCFG : 1;
99  unsigned O0WantsFastISel : 1;
100 
101 public:
104 
105  TargetMachine(const TargetMachine &) = delete;
106  void operator=(const TargetMachine &) = delete;
107  virtual ~TargetMachine();
108 
109  const Target &getTarget() const { return TheTarget; }
110 
111  const Triple &getTargetTriple() const { return TargetTriple; }
112  StringRef getTargetCPU() const { return TargetCPU; }
113  StringRef getTargetFeatureString() const { return TargetFS; }
114 
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 {
118  return nullptr;
119  }
121  return nullptr;
122  }
123 
124  /// Allocate and return a default initialized instance of the YAML
125  /// representation for the MachineFunctionInfo.
127  return nullptr;
128  }
129 
130  /// Allocate and initialize an instance of the YAML representation of the
131  /// MachineFunctionInfo.
132  virtual yaml::MachineFunctionInfo *
134  return nullptr;
135  }
136 
137  /// Parse out the target's MachineFunctionInfo from the YAML reprsentation.
141  SMRange &SourceRange) const {
142  return false;
143  }
144 
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));
150  }
151 
152  /// Create a DataLayout.
153  const DataLayout createDataLayout() const { return DL; }
154 
155  /// Test if a DataLayout if compatible with the CodeGen for this target.
156  ///
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;
162  }
163 
164  /// Get the pointer size for this target.
165  ///
166  /// This is the only time the DataLayout in the TargetMachine is used.
167  unsigned getPointerSize(unsigned AS) const {
168  return DL.getPointerSize(AS);
169  }
170 
171  unsigned getPointerSizeInBits(unsigned AS) const {
172  return DL.getPointerSizeInBits(AS);
173  }
174 
175  unsigned getProgramPointerSize() const {
176  return DL.getPointerSize(DL.getProgramAddressSpace());
177  }
178 
179  unsigned getAllocaPointerSize() const {
180  return DL.getPointerSize(DL.getAllocaAddrSpace());
181  }
182 
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;
187 
188  /// Return target specific asm information.
189  const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); }
190 
191  const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); }
192  const MCInstrInfo *getMCInstrInfo() const { return MII.get(); }
193  const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); }
194 
195  /// If intrinsic information is available, return it. If not, return null.
196  virtual const TargetIntrinsicInfo *getIntrinsicInfo() const {
197  return nullptr;
198  }
199 
200  bool requiresStructuredCFG() const { return RequireStructuredCFG; }
201  void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; }
202 
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;
206 
207  /// Returns the code model. The choices are small, kernel, medium, large, and
208  /// target default.
209  CodeModel::Model getCodeModel() const;
210 
211  bool isPositionIndependent() const;
212 
213  bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const;
214 
215  /// Returns true if this target uses emulated TLS.
216  bool useEmulatedTLS() const;
217 
218  /// Returns the TLS model which should be used for the given global variable.
219  TLSModel::Model getTLSModel(const GlobalValue *GV) const;
220 
221  /// Returns the optimization level: None, Less, Default, or Aggressive.
222  CodeGenOpt::Level getOptLevel() const;
223 
224  /// Overrides the optimization level.
225  void setOptLevel(CodeGenOpt::Level Level);
226 
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; }
232  Options.GlobalISelAbort = Mode;
233  }
234  void setMachineOutliner(bool Enable) {
235  Options.EnableMachineOutliner = Enable;
236  }
237  void setSupportsDefaultOutlining(bool Enable) {
238  Options.SupportsDefaultOutlining = Enable;
239  }
240 
241  bool shouldPrintMachineCode() const { return Options.PrintMachineCode; }
242 
243  bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
244 
245  /// Return true if data objects should be emitted into their own section,
246  /// corresponds to -fdata-sections.
247  bool getDataSections() const {
248  return Options.DataSections;
249  }
250 
251  /// Return true if functions should be emitted into their own section,
252  /// corresponding to -ffunction-sections.
253  bool getFunctionSections() const {
254  return Options.FunctionSections;
255  }
256 
257  /// Get a \c TargetIRAnalysis appropriate for the target.
258  ///
259  /// This is used to construct the new pass manager's target IR analysis pass,
260  /// set up appropriately for this target machine. Even the old pass manager
261  /// uses this to answer queries about the IR.
262  TargetIRAnalysis getTargetIRAnalysis();
263 
264  /// Return a TargetTransformInfo for a given function.
265  ///
266  /// The returned TargetTransformInfo is specialized to the subtarget
267  /// corresponding to \p F.
268  virtual TargetTransformInfo getTargetTransformInfo(const Function &F);
269 
270  /// Allow the target to modify the pass manager, e.g. by calling
271  /// PassManagerBuilder::addExtension.
273 
274  /// These enums are meant to be passed into addPassesToEmitFile to indicate
275  /// what type of file to emit, and returned by it to indicate what type of
276  /// file could actually be made.
280  CGFT_Null // Do not emit any output.
281  };
282 
283  /// Add passes to the specified pass manager to get the specified file
284  /// emitted. Typically this will involve several steps of code generation.
285  /// This method should return true if emission of this file type is not
286  /// supported, or false on success.
287  /// \p MMI is an optional parameter that, if set to non-nullptr,
288  /// will be used to set the MachineModuloInfo for this PM.
291  bool /*DisableVerify*/ = true,
292  MachineModuleInfo *MMI = nullptr) {
293  return true;
294  }
295 
296  /// Add passes to the specified pass manager to get machine code emitted with
297  /// the MCJIT. This method returns true if machine code is not supported. It
298  /// fills the MCContext Ctx pointer which can be used to build custom
299  /// MCStreamer.
300  ///
303  bool /*DisableVerify*/ = true) {
304  return true;
305  }
306 
307  /// True if subtarget inserts the final scheduling pass on its own.
308  ///
309  /// Branch relaxation, which must happen after block placement, can
310  /// on some targets (e.g. SystemZ) expose additional post-RA
311  /// scheduling opportunities.
312  virtual bool targetSchedulesPostRAScheduling() const { return false; };
313 
314  void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
315  Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
316  MCSymbol *getSymbol(const GlobalValue *GV) const;
317 };
318 
319 /// This class describes a target machine that is implemented with the LLVM
320 /// target-independent code generator.
321 ///
323 protected: // Can only create subclasses.
324  LLVMTargetMachine(const Target &T, StringRef DataLayoutString,
325  const Triple &TT, StringRef CPU, StringRef FS,
326  const TargetOptions &Options, Reloc::Model RM,
328 
329  void initAsmInfo();
330 
331 public:
332  /// Get a TargetTransformInfo implementation for the target.
333  ///
334  /// The TTI returned uses the common code generator to answer queries about
335  /// the IR.
336  TargetTransformInfo getTargetTransformInfo(const Function &F) override;
337 
338  /// Create a pass configuration object to be used by addPassToEmitX methods
339  /// for generating a pipeline of CodeGen passes.
340  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
341 
342  /// Add passes to the specified pass manager to get the specified file
343  /// emitted. Typically this will involve several steps of code generation.
344  /// \p MMI is an optional parameter that, if set to non-nullptr,
345  /// will be used to set the MachineModuloInfofor this PM.
346  bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
348  bool DisableVerify = true,
349  MachineModuleInfo *MMI = nullptr) override;
350 
351  /// Add passes to the specified pass manager to get machine code emitted with
352  /// the MCJIT. This method returns true if machine code is not supported. It
353  /// fills the MCContext Ctx pointer which can be used to build custom
354  /// MCStreamer.
355  bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
356  raw_pwrite_stream &Out,
357  bool DisableVerify = true) override;
358 
359  /// Returns true if the target is expected to pass all machine verifier
360  /// checks. This is a stopgap measure to fix targets one by one. We will
361  /// remove this at some point and always enable the verifier when
362  /// EXPENSIVE_CHECKS is enabled.
363  virtual bool isMachineVerifierClean() const { return true; }
364 
365  /// Adds an AsmPrinter pass to the pipeline that prints assembly or
366  /// machine code from the MI representation.
367  bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out,
368  raw_pwrite_stream *DwoOut, CodeGenFileType FileTYpe,
369  MCContext &Context);
370 
371  /// True if the target uses physical regs at Prolog/Epilog insertion
372  /// time. If true (most machines), all vregs must be allocated before
373  /// PEI. If false (virtual-register machines), then callee-save register
374  /// spilling and scavenging are not needed or used.
375  virtual bool usesPhysRegsForPEI() const { return true; }
376 
377  /// True if the target wants to use interprocedural register allocation by
378  /// default. The -enable-ipra flag can be used to override this.
379  virtual bool useIPRA() const {
380  return false;
381  }
382 };
383 
384 /// Helper method for getting the code model, returning Default if
385 /// CM does not have a value. The tiny and kernel models will produce
386 /// an error, so targets that support them or require more complex codemodel
387 /// selection logic should implement and call their own getEffectiveCodeModel.
389  CodeModel::Model Default) {
390  if (CM) {
391  // By default, targets do not support the tiny and kernel models.
392  if (*CM == CodeModel::Tiny)
393  report_fatal_error("Target does not support the tiny CodeModel", false);
394  if (*CM == CodeModel::Kernel)
395  report_fatal_error("Target does not support the kernel CodeModel", false);
396  return *CM;
397  }
398  return Default;
399 }
400 
401 } // end namespace llvm
402 
403 #endif // LLVM_TARGET_TARGETMACHINE_H
virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange) const
Parse out the target&#39;s MachineFunctionInfo from the YAML reprsentation.
Represents a range in source code.
Definition: SMLoc.h:48
const MCRegisterInfo * getMCRegisterInfo() const
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
StringRef getTargetFeatureString() const
unsigned PrintMachineCode
PrintMachineCode - This flag is enabled when the -print-machineinstrs option is specified on the comm...
CodeModel::Model getEffectiveCodeModel(Optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value...
LLVMContext & Context
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
SI Whole Quad Mode
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&, raw_pwrite_stream &, bool=true)
Add passes to the specified pass manager to get machine code emitted with the MCJIT.
virtual yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with...
Definition: TargetMachine.h:84
unsigned DataSections
Emit data into separate sections.
bool requiresStructuredCFG() const
unsigned EnableMachineOutliner
Enables the MachineOutliner pass.
void setO0WantsFastISel(bool Enable)
Analysis pass providing the TargetTransformInfo.
virtual bool useIPRA() const
True if the target wants to use interprocedural register allocation by default.
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:388
unsigned getProgramPointerSize() const
F(f)
const DataLayout createDataLayout() const
Create a DataLayout.
void setGlobalISelAbort(GlobalISelAbortMode Mode)
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfo *MMI=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
unsigned getAllocaAddrSpace() const
Definition: DataLayout.h:269
virtual bool usesPhysRegsForPEI() const
True if the target uses physical regs at Prolog/Epilog insertion time.
bool isCompatibleDataLayout(const DataLayout &Candidate) const
Test if a DataLayout if compatible with the CodeGen for this target.
Target-Independent Code Generator Pass Configuration Options.
virtual bool isMachineVerifierClean() const
Returns true if the target is expected to pass all machine verifier checks.
Context object for machine code objects.
Definition: MCContext.h:62
unsigned FunctionSections
Emit functions into separate sections.
unsigned getPointerSizeInBits(unsigned AS) const
std::unique_ptr< const MCSubtargetInfo > STI
Definition: TargetMachine.h:96
StringRef getTargetCPU() const
unsigned UniqueSectionNames
Expected< const typename ELFT::Sym * > getSymbol(typename ELFT::SymRange Symbols, uint32_t Index)
Definition: ELF.h:334
bool getDataSections() const
Return true if data objects should be emitted into their own section, corresponds to -fdata-sections...
unsigned SupportsDefaultOutlining
Set if the target supports default outlining behaviour.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
unsigned getAllocaPointerSize() const
unsigned EnableGlobalISel
EnableGlobalISel - This flag enables global instruction selection.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
bool getFunctionSections() const
Return true if functions should be emitted into their own section, corresponding to -ffunction-sectio...
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:648
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:23
std::unique_ptr< const MCAsmInfo > AsmInfo
Contains target specific asm information.
Definition: TargetMachine.h:93
This class describes a target machine that is implemented with the LLVM target-independent code gener...
const Triple & getTargetTriple() const
void setMachineOutliner(bool Enable)
const Target & TheTarget
The Target that this machine was created for.
Definition: TargetMachine.h:72
const Target & getTarget() const
void setSupportsDefaultOutlining(bool Enable)
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
unsigned getPointerSize(unsigned AS) const
Get the pointer size for this target.
TargetIntrinsicInfo - Interface to description of machine instruction set.
const TargetOptions DefaultOptions
virtual void adjustPassManager(PassManagerBuilder &)
Allow the target to modify the pass manager, e.g.
FileType
Defines the file type this file represents.
Definition: InterfaceFile.h:65
virtual TargetLoweringObjectFile * getObjFileLowering() const
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
const MCRegisterDesc & get(unsigned RegNo) const
Provide a get method, equivalent to [], but more useful with a pointer to this object.
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
void setRequiresStructuredCFG(bool Value)
void setFastISel(bool Enable)
const MCSubtargetInfo * getMCSubtargetInfo() const
virtual bool targetSchedulesPostRAScheduling() const
True if subtarget inserts the final scheduling pass on its own.
unsigned getProgramAddressSpace() const
Definition: DataLayout.h:282
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
Target - Wrapper for Target specific information.
virtual yaml::MachineFunctionInfo * convertFuncInfoToYAML(const MachineFunction &MF) const
Allocate and initialize an instance of the YAML representation of the MachineFunctionInfo.
std::string TargetCPU
Definition: TargetMachine.h:85
unsigned RequireStructuredCFG
Definition: TargetMachine.h:98
TargetSubtargetInfo - Generic base class for all target subtargets.
Targets should override this in a way that mirrors the implementation of llvm::MachineFunctionInfo.
GlobalISelAbortMode
Enable abort calls when global instruction selection fails to lower/select an instruction.
bool getUniqueSectionNames() const
unsigned O0WantsFastISel
Definition: TargetMachine.h:99
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
virtual const TargetIntrinsicInfo * getIntrinsicInfo() const
If intrinsic information is available, return it. If not, return null.
TargetOptions Options
void setGlobalISel(bool Enable)
Generic base class for all target subtargets.
std::unique_ptr< const MCInstrInfo > MII
Definition: TargetMachine.h:95
std::string TargetFS
Definition: TargetMachine.h:86
bool shouldPrintMachineCode() const
std::unique_ptr< const MCRegisterInfo > MRI
Definition: TargetMachine.h:94
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:340
const DataLayout DL
DataLayout for the target: keep ABI type size and alignment.
Definition: TargetMachine.h:80
const MCInstrInfo * getMCInstrInfo() const
LLVM Value Representation.
Definition: Value.h:72
GlobalISelAbortMode GlobalISelAbort
EnableGlobalISelAbort - Control abort behaviour when global instruction selection fails to lower/sele...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit...
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
This class contains meta information specific to a module.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:259