xref: /llvm-project/llvm/include/llvm/Target/TargetMachine.h (revision 18f8106f310ee702046a11f360af47947c030d2e)
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 class.
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/IR/DataLayout.h"
18 #include "llvm/IR/PassManager.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/CodeGen.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/PGOOptions.h"
25 #include "llvm/Target/CGPassBuilderOption.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/TargetParser/Triple.h"
28 #include <optional>
29 #include <string>
30 #include <utility>
31 
32 extern llvm::cl::opt<bool> NoKernelInfoEndLTO;
33 
34 namespace llvm {
35 
36 class AAManager;
37 using ModulePassManager = PassManager<Module>;
38 
39 class Function;
40 class GlobalValue;
41 class MachineModuleInfoWrapperPass;
42 class Mangler;
43 class MCAsmInfo;
44 class MCContext;
45 class MCInstrInfo;
46 class MCRegisterInfo;
47 class MCSubtargetInfo;
48 class MCSymbol;
49 class raw_pwrite_stream;
50 class PassBuilder;
51 class PassInstrumentationCallbacks;
52 struct PerFunctionMIParsingState;
53 class SMDiagnostic;
54 class SMRange;
55 class Target;
56 class TargetIntrinsicInfo;
57 class TargetIRAnalysis;
58 class TargetTransformInfo;
59 class TargetLoweringObjectFile;
60 class TargetPassConfig;
61 class TargetSubtargetInfo;
62 
63 // The old pass manager infrastructure is hidden in a legacy namespace now.
64 namespace legacy {
65 class PassManagerBase;
66 } // namespace legacy
67 using legacy::PassManagerBase;
68 
69 struct MachineFunctionInfo;
70 namespace yaml {
71 struct MachineFunctionInfo;
72 } // namespace yaml
73 
74 //===----------------------------------------------------------------------===//
75 ///
76 /// Primary interface to the complete machine description for the target
77 /// machine.  All target-specific information should be accessible through this
78 /// interface.
79 ///
80 class TargetMachine {
81 protected: // Can only create subclasses.
82   TargetMachine(const Target &T, StringRef DataLayoutString,
83                 const Triple &TargetTriple, StringRef CPU, StringRef FS,
84                 const TargetOptions &Options);
85 
86   /// The Target that this machine was created for.
87   const Target &TheTarget;
88 
89   /// DataLayout for the target: keep ABI type size and alignment.
90   ///
91   /// The DataLayout is created based on the string representation provided
92   /// during construction. It is kept here only to avoid reparsing the string
93   /// but should not really be used during compilation, because it has an
94   /// internal cache that is context specific.
95   const DataLayout DL;
96 
97   /// Triple string, CPU name, and target feature strings the TargetMachine
98   /// instance is created with.
99   Triple TargetTriple;
100   std::string TargetCPU;
101   std::string TargetFS;
102 
103   Reloc::Model RM = Reloc::Static;
104   CodeModel::Model CMModel = CodeModel::Small;
105   uint64_t LargeDataThreshold = 0;
106   CodeGenOptLevel OptLevel = CodeGenOptLevel::Default;
107 
108   /// Contains target specific asm information.
109   std::unique_ptr<const MCAsmInfo> AsmInfo;
110   std::unique_ptr<const MCRegisterInfo> MRI;
111   std::unique_ptr<const MCInstrInfo> MII;
112   std::unique_ptr<const MCSubtargetInfo> STI;
113 
114   unsigned RequireStructuredCFG : 1;
115   unsigned O0WantsFastISel : 1;
116 
117   // PGO related tunables.
118   std::optional<PGOOptions> PGOOption;
119 
120 public:
121   mutable TargetOptions Options;
122 
123   TargetMachine(const TargetMachine &) = delete;
124   void operator=(const TargetMachine &) = delete;
125   virtual ~TargetMachine();
126 
127   const Target &getTarget() const { return TheTarget; }
128 
129   const Triple &getTargetTriple() const { return TargetTriple; }
130   StringRef getTargetCPU() const { return TargetCPU; }
131   StringRef getTargetFeatureString() const { return TargetFS; }
132   void setTargetFeatureString(StringRef FS) { TargetFS = std::string(FS); }
133 
134   /// Virtual method implemented by subclasses that returns a reference to that
135   /// target's TargetSubtargetInfo-derived member variable.
136   virtual const TargetSubtargetInfo *getSubtargetImpl(const Function &) const {
137     return nullptr;
138   }
139   virtual TargetLoweringObjectFile *getObjFileLowering() const {
140     return nullptr;
141   }
142 
143   /// Create the target's instance of MachineFunctionInfo
144   virtual MachineFunctionInfo *
145   createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F,
146                             const TargetSubtargetInfo *STI) const {
147     return nullptr;
148   }
149 
150   /// Allocate and return a default initialized instance of the YAML
151   /// representation for the MachineFunctionInfo.
152   virtual yaml::MachineFunctionInfo *createDefaultFuncInfoYAML() const {
153     return nullptr;
154   }
155 
156   /// Allocate and initialize an instance of the YAML representation of the
157   /// MachineFunctionInfo.
158   virtual yaml::MachineFunctionInfo *
159   convertFuncInfoToYAML(const MachineFunction &MF) const {
160     return nullptr;
161   }
162 
163   /// Parse out the target's MachineFunctionInfo from the YAML reprsentation.
164   virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &,
165                                         PerFunctionMIParsingState &PFS,
166                                         SMDiagnostic &Error,
167                                         SMRange &SourceRange) const {
168     return false;
169   }
170 
171   /// This method returns a pointer to the specified type of
172   /// TargetSubtargetInfo.  In debug builds, it verifies that the object being
173   /// returned is of the correct type.
174   template <typename STC> const STC &getSubtarget(const Function &F) const {
175     return *static_cast<const STC*>(getSubtargetImpl(F));
176   }
177 
178   /// Create a DataLayout.
179   const DataLayout createDataLayout() const { return DL; }
180 
181   /// Test if a DataLayout if compatible with the CodeGen for this target.
182   ///
183   /// The LLVM Module owns a DataLayout that is used for the target independent
184   /// optimizations and code generation. This hook provides a target specific
185   /// check on the validity of this DataLayout.
186   bool isCompatibleDataLayout(const DataLayout &Candidate) const {
187     return DL == Candidate;
188   }
189 
190   /// Get the pointer size for this target.
191   ///
192   /// This is the only time the DataLayout in the TargetMachine is used.
193   unsigned getPointerSize(unsigned AS) const {
194     return DL.getPointerSize(AS);
195   }
196 
197   unsigned getPointerSizeInBits(unsigned AS) const {
198     return DL.getPointerSizeInBits(AS);
199   }
200 
201   unsigned getProgramPointerSize() const {
202     return DL.getPointerSize(DL.getProgramAddressSpace());
203   }
204 
205   unsigned getAllocaPointerSize() const {
206     return DL.getPointerSize(DL.getAllocaAddrSpace());
207   }
208 
209   /// Reset the target options based on the function's attributes.
210   // FIXME: Remove TargetOptions that affect per-function code generation
211   // from TargetMachine.
212   void resetTargetOptions(const Function &F) const;
213 
214   /// Return target specific asm information.
215   const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); }
216 
217   const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); }
218   const MCInstrInfo *getMCInstrInfo() const { return MII.get(); }
219   const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); }
220 
221   /// If intrinsic information is available, return it.  If not, return null.
222   virtual const TargetIntrinsicInfo *getIntrinsicInfo() const {
223     return nullptr;
224   }
225 
226   bool requiresStructuredCFG() const { return RequireStructuredCFG; }
227   void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; }
228 
229   /// Returns the code generation relocation model. The choices are static, PIC,
230   /// and dynamic-no-pic, and target default.
231   Reloc::Model getRelocationModel() const;
232 
233   /// Returns the code model. The choices are small, kernel, medium, large, and
234   /// target default.
235   CodeModel::Model getCodeModel() const { return CMModel; }
236 
237   /// Returns the maximum code size possible under the code model.
238   uint64_t getMaxCodeSize() const;
239 
240   /// Set the code model.
241   void setCodeModel(CodeModel::Model CM) { CMModel = CM; }
242 
243   void setLargeDataThreshold(uint64_t LDT) { LargeDataThreshold = LDT; }
244   bool isLargeGlobalValue(const GlobalValue *GV) const;
245 
246   bool isPositionIndependent() const;
247 
248   bool shouldAssumeDSOLocal(const GlobalValue *GV) const;
249 
250   /// Returns true if this target uses emulated TLS.
251   bool useEmulatedTLS() const;
252 
253   /// Returns true if this target uses TLS Descriptors.
254   bool useTLSDESC() const;
255 
256   /// Returns the TLS model which should be used for the given global variable.
257   TLSModel::Model getTLSModel(const GlobalValue *GV) const;
258 
259   /// Returns the optimization level: None, Less, Default, or Aggressive.
260   CodeGenOptLevel getOptLevel() const { return OptLevel; }
261 
262   /// Overrides the optimization level.
263   void setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; }
264 
265   void setFastISel(bool Enable) { Options.EnableFastISel = Enable; }
266   bool getO0WantsFastISel() { return O0WantsFastISel; }
267   void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; }
268   void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; }
269   void setGlobalISelAbort(GlobalISelAbortMode Mode) {
270     Options.GlobalISelAbort = Mode;
271   }
272   void setMachineOutliner(bool Enable) {
273     Options.EnableMachineOutliner = Enable;
274   }
275   void setSupportsDefaultOutlining(bool Enable) {
276     Options.SupportsDefaultOutlining = Enable;
277   }
278   void setSupportsDebugEntryValues(bool Enable) {
279     Options.SupportsDebugEntryValues = Enable;
280   }
281 
282   void setCFIFixup(bool Enable) { Options.EnableCFIFixup = Enable; }
283 
284   bool getAIXExtendedAltivecABI() const {
285     return Options.EnableAIXExtendedAltivecABI;
286   }
287 
288   bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
289 
290   /// Return true if unique basic block section names must be generated.
291   bool getUniqueBasicBlockSectionNames() const {
292     return Options.UniqueBasicBlockSectionNames;
293   }
294 
295   bool getSeparateNamedSections() const {
296     return Options.SeparateNamedSections;
297   }
298 
299   /// Return true if data objects should be emitted into their own section,
300   /// corresponds to -fdata-sections.
301   bool getDataSections() const {
302     return Options.DataSections;
303   }
304 
305   /// Return true if functions should be emitted into their own section,
306   /// corresponding to -ffunction-sections.
307   bool getFunctionSections() const {
308     return Options.FunctionSections;
309   }
310 
311   bool getEnableStaticDataPartitioning() const {
312     return Options.EnableStaticDataPartitioning;
313   }
314 
315   /// Return true if visibility attribute should not be emitted in XCOFF,
316   /// corresponding to -mignore-xcoff-visibility.
317   bool getIgnoreXCOFFVisibility() const {
318     return Options.IgnoreXCOFFVisibility;
319   }
320 
321   /// Return true if XCOFF traceback table should be emitted,
322   /// corresponding to -xcoff-traceback-table.
323   bool getXCOFFTracebackTable() const { return Options.XCOFFTracebackTable; }
324 
325   /// If basic blocks should be emitted into their own section,
326   /// corresponding to -fbasic-block-sections.
327   llvm::BasicBlockSection getBBSectionsType() const {
328     return Options.BBSections;
329   }
330 
331   /// Get the list of functions and basic block ids that need unique sections.
332   const MemoryBuffer *getBBSectionsFuncListBuf() const {
333     return Options.BBSectionsFuncListBuf.get();
334   }
335 
336   /// Returns true if a cast between SrcAS and DestAS is a noop.
337   virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
338     return false;
339   }
340 
341   void setPGOOption(std::optional<PGOOptions> PGOOpt) { PGOOption = PGOOpt; }
342   const std::optional<PGOOptions> &getPGOOption() const { return PGOOption; }
343 
344   /// If the specified generic pointer could be assumed as a pointer to a
345   /// specific address space, return that address space.
346   ///
347   /// Under offloading programming, the offloading target may be passed with
348   /// values only prepared on the host side and could assume certain
349   /// properties.
350   virtual unsigned getAssumedAddrSpace(const Value *V) const { return -1; }
351 
352   /// If the specified predicate checks whether a generic pointer falls within
353   /// a specified address space, return that generic pointer and the address
354   /// space being queried.
355   ///
356   /// Such predicates could be specified in @llvm.assume intrinsics for the
357   /// optimizer to assume that the given generic pointer always falls within
358   /// the address space based on that predicate.
359   virtual std::pair<const Value *, unsigned>
360   getPredicatedAddrSpace(const Value *V) const {
361     return std::make_pair(nullptr, -1);
362   }
363 
364   /// Get a \c TargetIRAnalysis appropriate for the target.
365   ///
366   /// This is used to construct the new pass manager's target IR analysis pass,
367   /// set up appropriately for this target machine. Even the old pass manager
368   /// uses this to answer queries about the IR.
369   TargetIRAnalysis getTargetIRAnalysis() const;
370 
371   /// Return a TargetTransformInfo for a given function.
372   ///
373   /// The returned TargetTransformInfo is specialized to the subtarget
374   /// corresponding to \p F.
375   virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const;
376 
377   /// Allow the target to modify the pass pipeline.
378   // TODO: Populate all pass names by using <Target>PassRegistry.def.
379   virtual void registerPassBuilderCallbacks(PassBuilder &) {}
380 
381   /// Allow the target to register alias analyses with the AAManager for use
382   /// with the new pass manager. Only affects the "default" AAManager.
383   virtual void registerDefaultAliasAnalyses(AAManager &) {}
384 
385   /// Add passes to the specified pass manager to get the specified file
386   /// emitted.  Typically this will involve several steps of code generation.
387   /// This method should return true if emission of this file type is not
388   /// supported, or false on success.
389   /// \p MMIWP is an optional parameter that, if set to non-nullptr,
390   /// will be used to set the MachineModuloInfo for this PM.
391   virtual bool
392   addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
393                       raw_pwrite_stream *, CodeGenFileType,
394                       bool /*DisableVerify*/ = true,
395                       MachineModuleInfoWrapperPass *MMIWP = nullptr) {
396     return true;
397   }
398 
399   /// Add passes to the specified pass manager to get machine code emitted with
400   /// the MCJIT. This method returns true if machine code is not supported. It
401   /// fills the MCContext Ctx pointer which can be used to build custom
402   /// MCStreamer.
403   ///
404   virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
405                                  raw_pwrite_stream &,
406                                  bool /*DisableVerify*/ = true) {
407     return true;
408   }
409 
410   /// True if subtarget inserts the final scheduling pass on its own.
411   ///
412   /// Branch relaxation, which must happen after block placement, can
413   /// on some targets (e.g. SystemZ) expose additional post-RA
414   /// scheduling opportunities.
415   virtual bool targetSchedulesPostRAScheduling() const { return false; };
416 
417   void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
418                          Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
419   MCSymbol *getSymbol(const GlobalValue *GV) const;
420 
421   /// The integer bit size to use for SjLj based exception handling.
422   static constexpr unsigned DefaultSjLjDataSize = 32;
423   virtual unsigned getSjLjDataSize() const { return DefaultSjLjDataSize; }
424 
425   static std::pair<int, int> parseBinutilsVersion(StringRef Version);
426 
427   /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
428   /// (e.g. stack) the target returns the corresponding address space.
429   virtual unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
430     return 0;
431   }
432 
433   /// Entry point for module splitting. Targets can implement custom module
434   /// splitting logic, mainly used by LTO for --lto-partitions.
435   ///
436   /// \returns `true` if the module was split, `false` otherwise. When  `false`
437   /// is returned, it is assumed that \p ModuleCallback has never been called
438   /// and \p M has not been modified.
439   virtual bool splitModule(
440       Module &M, unsigned NumParts,
441       function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
442     return false;
443   }
444 
445   /// Create a pass configuration object to be used by addPassToEmitX methods
446   /// for generating a pipeline of CodeGen passes.
447   virtual TargetPassConfig *createPassConfig(PassManagerBase &PM) {
448     return nullptr;
449   }
450 
451   virtual Error buildCodeGenPipeline(ModulePassManager &, raw_pwrite_stream &,
452                                      raw_pwrite_stream *, CodeGenFileType,
453                                      const CGPassBuilderOption &,
454                                      PassInstrumentationCallbacks *) {
455     return make_error<StringError>("buildCodeGenPipeline is not overridden",
456                                    inconvertibleErrorCode());
457   }
458 
459   /// Returns true if the target is expected to pass all machine verifier
460   /// checks. This is a stopgap measure to fix targets one by one. We will
461   /// remove this at some point and always enable the verifier when
462   /// EXPENSIVE_CHECKS is enabled.
463   virtual bool isMachineVerifierClean() const { return true; }
464 
465   /// Adds an AsmPrinter pass to the pipeline that prints assembly or
466   /// machine code from the MI representation.
467   virtual bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out,
468                              raw_pwrite_stream *DwoOut,
469                              CodeGenFileType FileType, MCContext &Context) {
470     return false;
471   }
472 
473   virtual Expected<std::unique_ptr<MCStreamer>>
474   createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
475                    CodeGenFileType FileType, MCContext &Ctx) {
476     return nullptr;
477   }
478 
479   /// True if the target uses physical regs (as nearly all targets do). False
480   /// for stack machines such as WebAssembly and other virtual-register
481   /// machines. If true, all vregs must be allocated before PEI. If false, then
482   /// callee-save register spilling and scavenging are not needed or used. If
483   /// false, implicitly defined registers will still be assumed to be physical
484   /// registers, except that variadic defs will be allocated vregs.
485   virtual bool usesPhysRegsForValues() const { return true; }
486 
487   /// True if the target wants to use interprocedural register allocation by
488   /// default. The -enable-ipra flag can be used to override this.
489   virtual bool useIPRA() const { return false; }
490 
491   /// The default variant to use in unqualified `asm` instructions.
492   /// If this returns 0, `asm "$(foo$|bar$)"` will evaluate to `asm "foo"`.
493   virtual int unqualifiedInlineAsmVariant() const { return 0; }
494 
495   // MachineRegisterInfo callback function
496   virtual void registerMachineRegisterInfoCallback(MachineFunction &MF) const {}
497 };
498 
499 } // end namespace llvm
500 
501 #endif // LLVM_TARGET_TARGETMACHINE_H
502