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
13#include "llvm/Target/TargetMachine.h"
14#include "llvm/Analysis/TargetTransformInfo.h"
15#include "llvm/IR/Function.h"
16#include "llvm/IR/GlobalValue.h"
17#include "llvm/IR/GlobalVariable.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"
23#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
26#include "llvm/MC/TargetRegistry.h"
27#include "llvm/Support/CodeGen.h"
28#include "llvm/Target/TargetLoweringObjectFile.h"
29using namespace llvm;
30
31cl::opt<bool> llvm::NoKernelInfoEndLTO(
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(Val: false), cl::Hidden);
35
36//---------------------------------------------------------------------------
37// TargetMachine Class
38//
39
40TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
41 const Triple &TT, StringRef CPU, StringRef FS,
42 const TargetOptions &Options)
43 : TheTarget(T), DL(DataLayoutString), TargetTriple(TT),
44 TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
45 MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
46 O0WantsFastISel(false), Options(Options) {}
47
48TargetMachine::~TargetMachine() = default;
49
50Expected<std::unique_ptr<MCStreamer>>
51TargetMachine::createMCStreamer(raw_pwrite_stream &Out,
52 raw_pwrite_stream *DwoOut,
53 CodeGenFileType FileType, MCContext &Ctx) {
54 return nullptr;
55}
56
57bool TargetMachine::isLargeGlobalValue(const GlobalValue *GVal) const {
58 if (getTargetTriple().getArch() != Triple::x86_64)
59 return false;
60
61 // Remaining logic below is ELF-specific. For other object file formats where
62 // the large code model is mostly used for JIT compilation, just look at the
63 // code model.
64 if (!getTargetTriple().isOSBinFormatELF())
65 return getCodeModel() == CodeModel::Large;
66
67 auto *GO = GVal->getAliaseeObject();
68
69 // Be conservative if we can't find an underlying GlobalObject.
70 if (!GO)
71 return true;
72
73 auto *GV = dyn_cast<GlobalVariable>(Val: GO);
74
75 auto IsPrefix = [](StringRef Name, StringRef Prefix) {
76 return Name.consume_front(Prefix) && (Name.empty() || Name[0] == '.');
77 };
78
79 // Functions/GlobalIFuncs are only large under the large code model.
80 if (!GV) {
81 // Handle explicit sections as we do for GlobalVariables with an explicit
82 // section, see comments below.
83 if (GO->hasSection()) {
84 StringRef Name = GO->getSection();
85 return IsPrefix(Name, ".ltext");
86 }
87 return getCodeModel() == CodeModel::Large;
88 }
89
90 if (GV->isThreadLocal())
91 return false;
92
93 // For x86-64, we treat an explicit GlobalVariable small code model to mean
94 // that the global should be placed in a small section, and ditto for large.
95 if (auto CM = GV->getCodeModel()) {
96 if (*CM == CodeModel::Small)
97 return false;
98 if (*CM == CodeModel::Large)
99 return true;
100 }
101
102 // Treat all globals in explicit sections as small, except for the standard
103 // large sections of .lbss, .ldata, .lrodata. This reduces the risk of linking
104 // together small and large sections, resulting in small references to large
105 // data sections. The code model attribute overrides this above.
106 if (GV->hasSection()) {
107 StringRef Name = GV->getSection();
108 return IsPrefix(Name, ".lbss") || IsPrefix(Name, ".ldata") ||
109 IsPrefix(Name, ".lrodata");
110 }
111
112 // Respect large data threshold for medium and large code models.
113 if (getCodeModel() == CodeModel::Medium ||
114 getCodeModel() == CodeModel::Large) {
115 if (!GV->getValueType()->isSized())
116 return true;
117 // Linker defined start/stop symbols can point to arbitrary points in the
118 // binary, so treat them as large.
119 if (GV->isDeclaration() && (GV->getName() == "__ehdr_start" ||
120 GV->getName().starts_with(Prefix: "__start_") ||
121 GV->getName().starts_with(Prefix: "__stop_")))
122 return true;
123 // Linkers do not currently support PT_GNU_RELRO for SHF_X86_64_LARGE
124 // sections; that would require the linker to emit more than one
125 // PT_GNU_RELRO because large sections are discontiguous by design, and most
126 // ELF dynamic loaders do not support that (bionic appears to support it but
127 // glibc/musl/FreeBSD/NetBSD/OpenBSD appear not to). With current linkers
128 // these sections will end up in .ldata which results in silently disabling
129 // RELRO. If this ever gets supported by downstream components in the future
130 // we could add an opt-in flag for moving these sections to .ldata.rel.ro
131 // which would trigger the creation of a second PT_GNU_RELRO.
132 if (!GV->isDeclarationForLinker() &&
133 TargetLoweringObjectFile::getKindForGlobal(GO: GV, TM: *this)
134 .isReadOnlyWithRel())
135 return false;
136 const DataLayout &DL = GV->getDataLayout();
137 uint64_t Size = GV->getGlobalSize(DL);
138 return Size == 0 || Size > LargeDataThreshold;
139 }
140
141 return false;
142}
143
144bool TargetMachine::isPositionIndependent() const {
145 return getRelocationModel() == Reloc::PIC_;
146}
147
148/// Returns the code generation relocation model. The choices are static, PIC,
149/// and dynamic-no-pic.
150Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
151
152uint64_t TargetMachine::getMaxCodeSize() const {
153 switch (getCodeModel()) {
154 case CodeModel::Tiny:
155 return llvm::maxUIntN(N: 10);
156 case CodeModel::Small:
157 case CodeModel::Kernel:
158 case CodeModel::Medium:
159 return llvm::maxUIntN(N: 31);
160 case CodeModel::Large:
161 return llvm::maxUIntN(N: 64);
162 }
163 llvm_unreachable("Unhandled CodeModel enum");
164}
165
166/// Get the IR-specified TLS model for Var.
167static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
168 switch (GV->getThreadLocalMode()) {
169 case GlobalVariable::NotThreadLocal:
170 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
171 break;
172 case GlobalVariable::GeneralDynamicTLSModel:
173 return TLSModel::GeneralDynamic;
174 case GlobalVariable::LocalDynamicTLSModel:
175 return TLSModel::LocalDynamic;
176 case GlobalVariable::InitialExecTLSModel:
177 return TLSModel::InitialExec;
178 case GlobalVariable::LocalExecTLSModel:
179 return TLSModel::LocalExec;
180 }
181 llvm_unreachable("invalid TLS model");
182}
183
184bool TargetMachine::shouldAssumeDSOLocal(const GlobalValue *GV) const {
185 const Triple &TT = getTargetTriple();
186 Reloc::Model RM = getRelocationModel();
187
188 // According to the llvm language reference, we should be able to
189 // just return false in here if we have a GV, as we know it is
190 // dso_preemptable. At this point in time, the various IR producers
191 // have not been transitioned to always produce a dso_local when it
192 // is possible to do so.
193 //
194 // As a result we still have some logic in here to improve the quality of the
195 // generated code.
196 if (!GV)
197 return false;
198
199 // If the IR producer requested that this GV be treated as dso local, obey.
200 if (GV->isDSOLocal())
201 return true;
202
203 if (TT.isOSBinFormatCOFF()) {
204 // DLLImport explicitly marks the GV as external.
205 if (GV->hasDLLImportStorageClass())
206 return false;
207
208 // On MinGW, variables that haven't been declared with DLLImport may still
209 // end up automatically imported by the linker. To make this feasible,
210 // don't assume the variables to be DSO local unless we actually know
211 // that for sure. This only has to be done for variables; for functions
212 // the linker can insert thunks for calling functions from another DLL.
213 if (TT.isOSCygMing() && GV->isDeclarationForLinker() &&
214 isa<GlobalVariable>(Val: GV))
215 return false;
216
217 // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
218 // unresolved in the link, they can be resolved to zero, which is outside
219 // the current DSO.
220 if (GV->hasExternalWeakLinkage())
221 return false;
222
223 // Every other GV is local on COFF.
224 return true;
225 }
226
227 if (TT.isOSBinFormatGOFF())
228 return true;
229
230 if (TT.isOSBinFormatMachO()) {
231 if (RM == Reloc::Static)
232 return true;
233 return GV->isStrongDefinitionForLinker();
234 }
235
236 assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
237 TT.isOSBinFormatXCOFF());
238 return false;
239}
240
241bool TargetMachine::useEmulatedTLS() const { return Options.EmulatedTLS; }
242bool TargetMachine::useTLSDESC() const { return Options.EnableTLSDESC; }
243
244TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
245 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
246 Reloc::Model RM = getRelocationModel();
247 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
248 bool IsLocal = shouldAssumeDSOLocal(GV);
249
250 TLSModel::Model Model;
251 if (IsSharedLibrary) {
252 if (IsLocal)
253 Model = TLSModel::LocalDynamic;
254 else
255 Model = TLSModel::GeneralDynamic;
256 } else {
257 if (IsLocal)
258 Model = TLSModel::LocalExec;
259 else
260 Model = TLSModel::InitialExec;
261 }
262
263 // If the user specified a more specific model, use that.
264 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
265 if (SelectedModel > Model)
266 return SelectedModel;
267
268 return Model;
269}
270
271TargetTransformInfo
272TargetMachine::getTargetTransformInfo(const Function &F) const {
273 return TargetTransformInfo(F.getDataLayout());
274}
275
276void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
277 const GlobalValue *GV, Mangler &Mang,
278 bool MayAlwaysUsePrivate) const {
279 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
280 // Simple case: If GV is not private, it is not important to find out if
281 // private labels are legal in this case or not.
282 Mang.getNameWithPrefix(OutName&: Name, GV, CannotUsePrivateLabel: false);
283 return;
284 }
285 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
286 TLOF->getNameWithPrefix(OutName&: Name, GV, TM: *this);
287}
288
289MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
290 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
291 // XCOFF symbols could have special naming convention.
292 if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, TM: *this))
293 return TargetSymbol;
294
295 SmallString<128> NameStr;
296 getNameWithPrefix(Name&: NameStr, GV, Mang&: TLOF->getMangler());
297 return TLOF->getContext().getOrCreateSymbol(Name: NameStr);
298}
299
300TargetIRAnalysis TargetMachine::getTargetIRAnalysis() const {
301 // Since Analysis can't depend on Target, use a std::function to invert the
302 // dependency.
303 return TargetIRAnalysis(
304 [this](const Function &F) { return this->getTargetTransformInfo(F); });
305}
306
307std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
308 if (Version == "none")
309 return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
310 std::pair<int, int> Ret;
311 if (!Version.consumeInteger(Radix: 10, Result&: Ret.first) && Version.consume_front(Prefix: "."))
312 Version.consumeInteger(Radix: 10, Result&: Ret.second);
313 return Ret;
314}
315
316const MCSubtargetInfo &TargetMachine::getMCSubtargetInfo(StringRef CPU,
317 StringRef FS) {
318 if (CPU.empty() && FS.empty())
319 return *STI;
320 SmallString<128> Key = CPU;
321 Key += '/';
322 Key += FS;
323 auto &Entry = MCSubtargetMap[Key];
324 if (!Entry)
325 Entry.reset(p: getTarget().createMCSubtargetInfo(TheTriple: getTargetTriple(), CPU, Features: FS));
326 return *Entry;
327}
328