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

source code of llvm/include/llvm/Target/TargetMachine.h