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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

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