LLVM 24.0.0git
TargetMachine.cpp
Go to the documentation of this file.
1//===-- TargetMachine.cpp - General Target Information ---------------------==//
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 describes the general parts of a Target machine.
10//
11//===----------------------------------------------------------------------===//
12
15#include "llvm/IR/Function.h"
16#include "llvm/IR/GlobalValue.h"
18#include "llvm/IR/Mangler.h"
19#include "llvm/IR/Module.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCStreamer.h"
29using namespace llvm;
30
32 "no-kernel-info-end-lto",
33 cl::desc("remove the kernel-info pass at the end of the full LTO pipeline"),
34 cl::init(false), cl::Hidden);
35
36//---------------------------------------------------------------------------
37// TargetMachine Class
38//
39
41 ExceptionHandling Model) {
42 // Each model is valid only where its object format or architecture defines
43 // it. DwarfCFI and SjLj are the generic unwinding schemes, valid on any
44 // target that has exception handling by default.
45 switch (Model) {
48 return TT.getDefaultExceptionHandling() != ExceptionHandling::None;
50 return TT.isOSBinFormatCOFF();
52 return (TT.isARM() || TT.isThumb()) && TT.isOSBinFormatELF();
54 return TT.isOSBinFormatXCOFF();
56 return TT.isOSBinFormatGOFF();
59 return TT.isWasm();
62 break;
63 }
64
65 llvm_unreachable("unexpected exception model");
66}
67
86
88
89/// NOTE: There are targets that still do not support the debug entry values
90/// production and that is being controlled with the SupportsDebugEntryValues.
91/// In addition, SCE debugger does not have the feature implemented, so prefer
92/// not to emit the debug entry values in that case.
93/// The EnableDebugEntryValues can be used for the testing purposes.
95 // Only the explicitly-set "debugger-tuning" module flag suppresses entry
96 // values.
97 return Options.EnableDebugEntryValues ||
99}
100
103 raw_pwrite_stream *DwoOut,
104 CodeGenFileType FileType, MCContext &Ctx) {
105 return nullptr;
106}
107
109 if (getTargetTriple().getArch() != Triple::x86_64)
110 return false;
111
112 if (!getTargetTriple().isOSBinFormatELF())
113 return getCodeModel() == CodeModel::Large;
114
116 return Size == 0 || Size > LargeDataThreshold;
117
118 return false;
119}
120
122 if (getTargetTriple().getArch() != Triple::x86_64)
123 return false;
124
125 // Remaining logic below is ELF-specific. For other object file formats where
126 // the large code model is mostly used for JIT compilation, just look at the
127 // code model.
128 if (!getTargetTriple().isOSBinFormatELF())
129 return getCodeModel() == CodeModel::Large;
130
131 auto *GO = GVal->getAliaseeObject();
132
133 // Be conservative if we can't find an underlying GlobalObject.
134 if (!GO)
135 return true;
136
137 auto *GV = dyn_cast<GlobalVariable>(GO);
138
139 auto IsPrefix = [](StringRef Name, StringRef Prefix) {
140 return Name.consume_front(Prefix) && (Name.empty() || Name[0] == '.');
141 };
142
143 // Functions/GlobalIFuncs are only large under the large code model.
144 if (!GV) {
145 // Handle explicit sections as we do for GlobalVariables with an explicit
146 // section, see comments below.
147 if (GO->hasSection()) {
148 StringRef Name = GO->getSection();
149 return IsPrefix(Name, ".ltext");
150 }
151 return getCodeModel() == CodeModel::Large;
152 }
153
154 if (GV->isThreadLocal())
155 return false;
156
157 // For x86-64, we treat an explicit GlobalVariable small code model to mean
158 // that the global should be placed in a small section, and ditto for large.
159 if (auto CM = GV->getCodeModel()) {
160 if (*CM == CodeModel::Small)
161 return false;
162 if (*CM == CodeModel::Large)
163 return true;
164 }
165
166 // Treat all globals in user-defined sections as small, except for the
167 // standard large sections of .lbss, .ldata, .lrodata. This reduces the risk
168 // of linking together small and large sections, resulting in small
169 // references to large data sections. The code model attribute overrides this
170 // above.
171 if (GV->hasSection() || GV->hasImplicitSection()) {
174 if (!SectionName.empty()) {
175 return IsPrefix(SectionName, ".lbss") ||
176 IsPrefix(SectionName, ".ldata") ||
177 IsPrefix(SectionName, ".lrodata");
178 }
179 }
180
181 // Respect large data threshold for medium and large code models.
184 if (!GV->getValueType()->isSized())
185 return true;
186 // Linker defined start/stop symbols can point to arbitrary points in the
187 // binary, so treat them as large.
188 if (GV->isDeclaration() && (GV->getName() == "__ehdr_start" ||
189 GV->getName().starts_with("__start_") ||
190 GV->getName().starts_with("__stop_")))
191 return true;
192 // Check the size before getKindForGlobal() below, which may walk the
193 // global's entire initializer.
194 const DataLayout &DL = GV->getDataLayout();
195 if (!isLargeDataSize(GV->getGlobalSize(DL)))
196 return false;
197 // Linkers do not currently support PT_GNU_RELRO for SHF_X86_64_LARGE
198 // sections; that would require the linker to emit more than one
199 // PT_GNU_RELRO because large sections are discontiguous by design, and most
200 // ELF dynamic loaders do not support that (bionic appears to support it but
201 // glibc/musl/FreeBSD/NetBSD/OpenBSD appear not to). With current linkers
202 // these sections will end up in .ldata which results in silently disabling
203 // RELRO. If this ever gets supported by downstream components in the future
204 // we could add an opt-in flag for moving these sections to .ldata.rel.ro
205 // which would trigger the creation of a second PT_GNU_RELRO.
206 if (!GV->isDeclarationForLinker() &&
208 .isReadOnlyWithRel())
209 return false;
210 return true;
211 }
212
213 return false;
214}
215
219
220/// Returns the code generation relocation model. The choices are static, PIC,
221/// and dynamic-no-pic.
223
225 switch (getCodeModel()) {
226 case CodeModel::Tiny:
227 return llvm::maxUIntN(10);
228 case CodeModel::Small:
231 return llvm::maxUIntN(31);
232 case CodeModel::Large:
233 return llvm::maxUIntN(64);
234 }
235 llvm_unreachable("Unhandled CodeModel enum");
236}
237
238/// Get the IR-specified TLS model for Var.
240 switch (GV->getThreadLocalMode()) {
242 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
243 break;
251 return TLSModel::LocalExec;
252 }
253 llvm_unreachable("invalid TLS model");
254}
255
257 const Triple &TT = getTargetTriple();
259
260 // According to the llvm language reference, we should be able to
261 // just return false in here if we have a GV, as we know it is
262 // dso_preemptable. At this point in time, the various IR producers
263 // have not been transitioned to always produce a dso_local when it
264 // is possible to do so.
265 //
266 // As a result we still have some logic in here to improve the quality of the
267 // generated code.
268 if (!GV)
269 return false;
270
271 // If the IR producer requested that this GV be treated as dso local, obey.
272 if (GV->isDSOLocal())
273 return true;
274
275 if (TT.isOSBinFormatCOFF()) {
276 // DLLImport explicitly marks the GV as external.
277 if (GV->hasDLLImportStorageClass())
278 return false;
279
280 // On MinGW, variables that haven't been declared with DLLImport may still
281 // end up automatically imported by the linker. To make this feasible,
282 // don't assume the variables to be DSO local unless we actually know
283 // that for sure. This only has to be done for variables; for functions
284 // the linker can insert thunks for calling functions from another DLL.
285 if (TT.isOSCygMing() && GV->isDeclarationForLinker() &&
287 return false;
288
289 // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
290 // unresolved in the link, they can be resolved to zero, which is outside
291 // the current DSO.
292 if (GV->hasExternalWeakLinkage())
293 return false;
294
295 // Every other GV is local on COFF.
296 return true;
297 }
298
299 if (TT.isOSBinFormatGOFF())
300 return true;
301
302 if (TT.isOSBinFormatMachO()) {
303 if (RM == Reloc::Static)
304 return true;
305 return GV->isStrongDefinitionForLinker();
306 }
307
308 assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
309 TT.isOSBinFormatXCOFF());
310 return false;
311}
312
313bool TargetMachine::useEmulatedTLS() const { return Options.EmulatedTLS; }
314bool TargetMachine::useTLSDESC() const { return Options.EnableTLSDESC; }
315
317 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
319 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
320 bool IsLocal = shouldAssumeDSOLocal(GV);
321
322 TLSModel::Model Model;
323 if (IsSharedLibrary) {
324 if (IsLocal)
326 else
328 } else {
329 if (IsLocal)
330 Model = TLSModel::LocalExec;
331 else
332 Model = TLSModel::InitialExec;
333 }
334
335 // If the user specified a more specific model, use that.
336 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
337 if (SelectedModel > Model)
338 return SelectedModel;
339
340 return Model;
341}
342
345 return TargetTransformInfo(F.getDataLayout());
346}
347
349 const GlobalValue *GV, Mangler &Mang,
350 bool MayAlwaysUsePrivate) const {
351 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
352 // Simple case: If GV is not private, it is not important to find out if
353 // private labels are legal in this case or not.
354 Mang.getNameWithPrefix(Name, GV, false);
355 return;
356 }
358 TLOF->getNameWithPrefix(Name, GV, *this);
359}
360
363 // XCOFF symbols could have special naming convention.
364 if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
365 return TargetSymbol;
366
367 SmallString<128> NameStr;
368 getNameWithPrefix(NameStr, GV, TLOF->getMangler());
369 return TLOF->getContext().getOrCreateSymbol(NameStr);
370}
371
373 // Since Analysis can't depend on Target, use a std::function to invert the
374 // dependency.
375 return TargetIRAnalysis(
376 [this](const Function &F) { return this->getTargetTransformInfo(F); });
377}
378
380 if (const auto *MD = cast_or_null<MDString>(M.getModuleFlag("target-abi")))
381 return MD->getString();
382 return Options.MCOptions.getABIName();
383}
384
386 // The "target-abi" module flag must agree with the -target-abi option.
387 StringRef OptionABI = Options.MCOptions.getABIName();
388 if (!OptionABI.empty()) {
389 if (const auto *MD =
390 cast_or_null<MDString>(M.getModuleFlag("target-abi"))) {
391 if (OptionABI != MD->getString())
392 M.getContext().emitError(
393 "-target-abi option != target-abi module flag");
394 }
395 }
396}
397
399 StringRef FS) {
400 if (CPU.empty() && FS.empty())
401 return *STI;
402 SmallString<128> Key = CPU;
403 Key += '/';
404 Key += FS;
405 auto &Entry = MCSubtargetMap[Key];
406 if (!Entry)
407 Entry.reset(getTarget().createMCSubtargetInfo(getTargetTriple(), CPU, FS));
408 return *Entry;
409}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define T
static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV)
Get the IR-specified TLS model for Var.
static bool isExceptionModelSupportedByDefault(const Triple &TT, ExceptionHandling Model)
This pass exposes codegen information to IR-level passes.
static MCSubtargetInfo * createMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Tagged union holding either a T or a Error.
Definition Error.h:485
bool isDSOLocal() const
bool hasPrivateLinkage() const
bool hasExternalWeakLinkage() const
ThreadLocalMode getThreadLocalMode() const
bool hasDLLImportStorageClass() const
bool isDeclarationForLinker() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
Context object for machine code objects.
Definition MCContext.h:84
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
MCContext & getContext() const
Generic base class for all target subtargets.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition Mangler.cpp:121
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition Module.cpp:672
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Analysis pass providing the TargetTransformInfo.
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
static StringRef getCustomSectionName(const GlobalObject *GO, const TargetMachine &TM)
Return the section name specified by 'pragma clang section' or the section attribute.
virtual MCSymbol * getTargetSymbol(const GlobalValue *GV, const TargetMachine &TM) const
Targets that have a special convention for their symbols could use this hook to return a specialized ...
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with.
std::unique_ptr< const MCAsmInfo > AsmInfo
Contains target specific asm information.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool isPositionIndependent() const
void setSupportsExceptionModel(ExceptionHandling Model, bool Value=true)
Override whether this target can lower exceptions using Model.
uint64_t getMaxCodeSize() const
Returns the maximum code size possible under the code model.
const Triple & getTargetTriple() const
bool useTLSDESC() const
Returns true if this target uses TLS Descriptors.
StringMap< std::unique_ptr< const MCSubtargetInfo > > MCSubtargetMap
MC subtarget keyed by target features and target CPU.
const MCSubtargetInfo & getMCSubtargetInfo() const
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
bool shouldEmitDebugEntryValues(DebuggerKind Tuning) const
NOTE: There are targets that still do not support the debug entry values production.
std::unique_ptr< const MCInstrInfo > MII
virtual TargetLoweringObjectFile * getObjFileLowering() const
StringRef getTargetABIName(const Module &M) const
Returns the effective target ABI name: the "target-abi" module flag if present, otherwise the -target...
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const
Return a TargetTransformInfo for a given function.
const DataLayout DL
DataLayout for the target: keep ABI type size and alignment.
unsigned SupportsDebugEntryValues
Set if the target supports the debug entry values by default.
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
virtual Expected< std::unique_ptr< MCStreamer > > createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
std::unique_ptr< const MCSubtargetInfo > STI
TargetIRAnalysis getTargetIRAnalysis() const
Get a TargetIRAnalysis appropriate for the target.
TargetOptions Options
void verifyOptionsConsistency(const Module &M) const
Diagnoses command-line codegen options that conflict with the corresponding module flags (e....
unsigned RequireStructuredCFG
unsigned EnableTiedFastRegAlloc
virtual ~TargetMachine()
MCSymbol * getSymbol(const GlobalValue *GV) const
bool isLargeDataSize(uint64_t Size) const
unsigned SupportsDefaultOutlining
Set if the target supports default outlining behaviour.
const Target & getTarget() const
const Target & TheTarget
The Target that this machine was created for.
CodeModel::Model getCodeModel() const
Returns the code model.
bool isLargeGlobalValue(const GlobalValue *GV) const
TargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TargetTriple, StringRef CPU, StringRef FS, const TargetOptions &Options)
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
std::unique_ptr< const MCRegisterInfo > MRI
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
An abstract base class for streams implementations that also support a pwrite operation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto cast_or_null(const Y &Val)
Definition Casting.h:714
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:309
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
ExceptionHandling
Definition CodeGen.h:54
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:64
@ Emscripten
Emscripten JavaScript-based exception handling.
Definition CodeGen.h:62
@ None
No exception support.
Definition CodeGen.h:56
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
@ AIX
AIX Exception Handling.
Definition CodeGen.h:63
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
DebuggerKind
Identify a debugger for "tuning" the debug info.
Definition CodeGen.h:231
@ SCE
Tune debug info for SCE targets (e.g. PS4).
Definition CodeGen.h:235
LLVM_ABI llvm::cl::opt< bool > NoKernelInfoEndLTO
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879