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