LLVM 19.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/MC/MCAsmInfo.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCInstrInfo.h"
26using namespace llvm;
27
28//---------------------------------------------------------------------------
29// TargetMachine Class
30//
31
33 const Triple &TT, StringRef CPU, StringRef FS,
35 : TheTarget(T), DL(DataLayoutString), TargetTriple(TT),
36 TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
37 MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
38 O0WantsFastISel(false), Options(Options) {}
39
41
43 if (getTargetTriple().getArch() != Triple::x86_64)
44 return false;
45
46 auto *GO = GVal->getAliaseeObject();
47
48 // Be conservative if we can't find an underlying GlobalObject.
49 if (!GO)
50 return true;
51
52 auto *GV = dyn_cast<GlobalVariable>(GO);
53
54 // Functions/GlobalIFuncs are only large under the large code model.
55 if (!GV)
57
58 if (GV->isThreadLocal())
59 return false;
60
61 // For x86-64, we treat an explicit GlobalVariable small code model to mean
62 // that the global should be placed in a small section, and ditto for large.
63 if (auto CM = GV->getCodeModel()) {
64 if (*CM == CodeModel::Small)
65 return false;
66 if (*CM == CodeModel::Large)
67 return true;
68 }
69
70 // Treat all globals in explicit sections as small, except for the standard
71 // large sections of .lbss, .ldata, .lrodata. This reduces the risk of linking
72 // together small and large sections, resulting in small references to large
73 // data sections. The code model attribute overrides this above.
74 if (GV->hasSection()) {
75 StringRef Name = GV->getSection();
76 auto IsPrefix = [&](StringRef Prefix) {
77 StringRef S = Name;
78 return S.consume_front(Prefix) && (S.empty() || S[0] == '.');
79 };
80 return IsPrefix(".lbss") || IsPrefix(".ldata") || IsPrefix(".lrodata");
81 }
82
83 // Respect large data threshold for medium and large code models.
86 if (!GV->getValueType()->isSized())
87 return true;
88 // Linker defined start/stop symbols can point to arbitrary points in the
89 // binary, so treat them as large.
90 if (GV->isDeclaration() && (GV->getName() == "__ehdr_start" ||
91 GV->getName().starts_with("__start_") ||
92 GV->getName().starts_with("__stop_")))
93 return true;
94 const DataLayout &DL = GV->getParent()->getDataLayout();
95 uint64_t Size = DL.getTypeSizeInBits(GV->getValueType()) / 8;
96 return Size == 0 || Size > LargeDataThreshold;
97 }
98
99 return false;
100}
101
104}
105
106/// Reset the target options based on the function's attributes.
107/// setFunctionAttributes should have made the raw attribute value consistent
108/// with the command line flag if used.
109//
110// FIXME: This function needs to go away for a number of reasons:
111// a) global state on the TargetMachine is terrible in general,
112// b) these target options should be passed only on the function
113// and not on the TargetMachine (via TargetOptions) at all.
115#define RESET_OPTION(X, Y) \
116 do { \
117 Options.X = F.getFnAttribute(Y).getValueAsBool(); \
118 } while (0)
119
120 RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
121 RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
122 RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
123 RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
124 RESET_OPTION(ApproxFuncFPMath, "approx-func-fp-math");
125}
126
127/// Returns the code generation relocation model. The choices are static, PIC,
128/// and dynamic-no-pic.
130
132 switch (getCodeModel()) {
133 case CodeModel::Tiny:
134 return llvm::maxUIntN(10);
135 case CodeModel::Small:
138 return llvm::maxUIntN(31);
139 case CodeModel::Large:
140 return llvm::maxUIntN(64);
141 }
142 llvm_unreachable("Unhandled CodeModel enum");
143}
144
145/// Get the IR-specified TLS model for Var.
147 switch (GV->getThreadLocalMode()) {
149 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
150 break;
158 return TLSModel::LocalExec;
159 }
160 llvm_unreachable("invalid TLS model");
161}
162
164 const GlobalValue *GV) const {
165 const Triple &TT = getTargetTriple();
167
168 // According to the llvm language reference, we should be able to
169 // just return false in here if we have a GV, as we know it is
170 // dso_preemptable. At this point in time, the various IR producers
171 // have not been transitioned to always produce a dso_local when it
172 // is possible to do so.
173 //
174 // As a result we still have some logic in here to improve the quality of the
175 // generated code.
176 if (!GV)
177 return false;
178
179 // If the IR producer requested that this GV be treated as dso local, obey.
180 if (GV->isDSOLocal())
181 return true;
182
183 if (TT.isOSBinFormatCOFF()) {
184 // DLLImport explicitly marks the GV as external.
185 if (GV->hasDLLImportStorageClass())
186 return false;
187
188 // On MinGW, variables that haven't been declared with DLLImport may still
189 // end up automatically imported by the linker. To make this feasible,
190 // don't assume the variables to be DSO local unless we actually know
191 // that for sure. This only has to be done for variables; for functions
192 // the linker can insert thunks for calling functions from another DLL.
193 if (TT.isWindowsGNUEnvironment() && GV->isDeclarationForLinker() &&
194 isa<GlobalVariable>(GV))
195 return false;
196
197 // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
198 // unresolved in the link, they can be resolved to zero, which is outside
199 // the current DSO.
200 if (GV->hasExternalWeakLinkage())
201 return false;
202
203 // Every other GV is local on COFF.
204 return true;
205 }
206
207 if (TT.isOSBinFormatGOFF())
208 return true;
209
210 if (TT.isOSBinFormatMachO()) {
211 if (RM == Reloc::Static)
212 return true;
213 return GV->isStrongDefinitionForLinker();
214 }
215
216 assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
217 TT.isOSBinFormatXCOFF());
218 return false;
219}
220
223
225 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
227 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
228 bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
229
230 TLSModel::Model Model;
231 if (IsSharedLibrary) {
232 if (IsLocal)
234 else
236 } else {
237 if (IsLocal)
238 Model = TLSModel::LocalExec;
239 else
240 Model = TLSModel::InitialExec;
241 }
242
243 // If the user specified a more specific model, use that.
244 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
245 if (SelectedModel > Model)
246 return SelectedModel;
247
248 return Model;
249}
250
251/// Returns the optimization level: None, Less, Default, or Aggressive.
253
255
258 return TargetTransformInfo(F.getParent()->getDataLayout());
259}
260
262 const GlobalValue *GV, Mangler &Mang,
263 bool MayAlwaysUsePrivate) const {
264 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
265 // Simple case: If GV is not private, it is not important to find out if
266 // private labels are legal in this case or not.
267 Mang.getNameWithPrefix(Name, GV, false);
268 return;
269 }
271 TLOF->getNameWithPrefix(Name, GV, *this);
272}
273
276 // XCOFF symbols could have special naming convention.
277 if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
278 return TargetSymbol;
279
280 SmallString<128> NameStr;
281 getNameWithPrefix(NameStr, GV, TLOF->getMangler());
282 return TLOF->getContext().getOrCreateSymbol(NameStr);
283}
284
286 // Since Analysis can't depend on Target, use a std::function to invert the
287 // dependency.
288 return TargetIRAnalysis(
289 [this](const Function &F) { return this->getTargetTransformInfo(F); });
290}
291
292std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
293 if (Version == "none")
294 return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
295 std::pair<int, int> Ret;
296 if (!Version.consumeInteger(10, Ret.first) && Version.consume_front("."))
297 Version.consumeInteger(10, Ret.second);
298 return Ret;
299}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
std::string Name
uint64_t Size
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV)
Get the IR-specified TLS model for Var.
#define RESET_OPTION(X, Y)
This pass exposes codegen information to IR-level passes.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:672
bool isDSOLocal() const
Definition: GlobalValue.h:305
bool hasPrivateLinkage() const
Definition: GlobalValue.h:526
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:528
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
bool hasDLLImportStorageClass() const
Definition: GlobalValue.h:278
bool isDeclarationForLinker() const
Definition: GlobalValue.h:617
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:368
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
Definition: GlobalValue.h:630
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:200
MCContext & getContext() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
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:119
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition: Module.cpp:589
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:631
Analysis pass providing the TargetTransformInfo.
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
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 ...
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool isPositionIndependent() const
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.
uint64_t LargeDataThreshold
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
virtual TargetLoweringObjectFile * getObjFileLowering() const
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.
Definition: TargetMachine.h:91
static std::pair< int, int > parseBinutilsVersion(StringRef Version)
TargetIRAnalysis getTargetIRAnalysis() const
Get a TargetIRAnalysis appropriate for the target.
TargetOptions Options
virtual ~TargetMachine()
MCSymbol * getSymbol(const GlobalValue *GV) const
bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const
CodeModel::Model getCodeModel() const
Returns the code model.
bool isLargeGlobalValue(const GlobalValue *GV) const
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
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
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
CodeGenOptLevel OptLevel
void setOptLevel(CodeGenOptLevel Level)
Overrides the optimization level.
unsigned EnableTLSDESC
EnableTLSDESC - This flag enables TLS Descriptors.
unsigned EmulatedTLS
EmulatedTLS - This flag enables emulated TLS model, using emutls function in the runtime library.
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:44
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ GeneralDynamic
Definition: CodeGen.h:46
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition: MathExtras.h:201
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858