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/GlobalAlias.h"
17 #include "llvm/IR/GlobalValue.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCTargetOptions.h"
26 #include "llvm/MC/SectionKind.h"
27 #include "llvm/Target/TargetLoweringObjectFile.h"
28 using namespace llvm;
29 
30 //---------------------------------------------------------------------------
31 // TargetMachine Class
32 //
33 
34 TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
35                              const Triple &TT, StringRef CPU, StringRef FS,
36                              const TargetOptions &Options)
37     : TheTarget(T), DL(DataLayoutString), TargetTriple(TT), TargetCPU(CPU),
38       TargetFS(FS), AsmInfo(nullptr), MRI(nullptr), MII(nullptr), STI(nullptr),
39       RequireStructuredCFG(false), DefaultOptions(Options), Options(Options) {
40 }
41 
42 TargetMachine::~TargetMachine() = default;
43 
44 bool TargetMachine::isPositionIndependent() const {
45   return getRelocationModel() == Reloc::PIC_;
46 }
47 
48 /// Reset the target options based on the function's attributes.
49 // FIXME: This function needs to go away for a number of reasons:
50 // a) global state on the TargetMachine is terrible in general,
51 // b) these target options should be passed only on the function
52 //    and not on the TargetMachine (via TargetOptions) at all.
53 void TargetMachine::resetTargetOptions(const Function &F) const {
54 #define RESET_OPTION(X, Y)                                                     \
55   do {                                                                         \
56     if (F.hasFnAttribute(Y))                                                   \
57       Options.X = (F.getFnAttribute(Y).getValueAsString() == "true");          \
58     else                                                                       \
59       Options.X = DefaultOptions.X;                                            \
60   } while (0)
61 
62   RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
63   RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
64   RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
65   RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
66   RESET_OPTION(NoTrappingFPMath, "no-trapping-math");
67 
68   StringRef Denormal =
69     F.getFnAttribute("denormal-fp-math").getValueAsString();
70   if (Denormal == "ieee")
71     Options.FPDenormalMode = FPDenormal::IEEE;
72   else if (Denormal == "preserve-sign")
73     Options.FPDenormalMode = FPDenormal::PreserveSign;
74   else if (Denormal == "positive-zero")
75     Options.FPDenormalMode = FPDenormal::PositiveZero;
76   else
77     Options.FPDenormalMode = DefaultOptions.FPDenormalMode;
78 }
79 
80 /// Returns the code generation relocation model. The choices are static, PIC,
81 /// and dynamic-no-pic.
82 Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
83 
84 /// Returns the code model. The choices are small, kernel, medium, large, and
85 /// target default.
86 CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; }
87 
88 /// Get the IR-specified TLS model for Var.
89 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
90   switch (GV->getThreadLocalMode()) {
91   case GlobalVariable::NotThreadLocal:
92     llvm_unreachable("getSelectedTLSModel for non-TLS variable");
93     break;
94   case GlobalVariable::GeneralDynamicTLSModel:
95     return TLSModel::GeneralDynamic;
96   case GlobalVariable::LocalDynamicTLSModel:
97     return TLSModel::LocalDynamic;
98   case GlobalVariable::InitialExecTLSModel:
99     return TLSModel::InitialExec;
100   case GlobalVariable::LocalExecTLSModel:
101     return TLSModel::LocalExec;
102   }
103   llvm_unreachable("invalid TLS model");
104 }
105 
106 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
107                                          const GlobalValue *GV) const {
108   // If the IR producer requested that this GV be treated as dso local, obey.
109   if (GV && GV->isDSOLocal())
110     return true;
111 
112   // If we are not supossed to use a PLT, we cannot assume that intrinsics are
113   // local since the linker can convert some direct access to access via plt.
114   if (M.getRtLibUseGOT() && !GV)
115     return false;
116 
117   // According to the llvm language reference, we should be able to
118   // just return false in here if we have a GV, as we know it is
119   // dso_preemptable.  At this point in time, the various IR producers
120   // have not been transitioned to always produce a dso_local when it
121   // is possible to do so.
122   // In the case of intrinsics, GV is null and there is nowhere to put
123   // dso_local. Returning false for those will produce worse code in some
124   // architectures. For example, on x86 the caller has to set ebx before calling
125   // a plt.
126   // As a result we still have some logic in here to improve the quality of the
127   // generated code.
128   // FIXME: Add a module level metadata for whether intrinsics should be assumed
129   // local.
130 
131   Reloc::Model RM = getRelocationModel();
132   const Triple &TT = getTargetTriple();
133 
134   // DLLImport explicitly marks the GV as external.
135   if (GV && GV->hasDLLImportStorageClass())
136     return false;
137 
138   // On MinGW, variables that haven't been declared with DLLImport may still
139   // end up automatically imported by the linker. To make this feasible,
140   // don't assume the variables to be DSO local unless we actually know
141   // that for sure. This only has to be done for variables; for functions
142   // the linker can insert thunks for calling functions from another DLL.
143   if (TT.isWindowsGNUEnvironment() && GV && GV->isDeclarationForLinker() &&
144       isa<GlobalVariable>(GV))
145     return false;
146 
147   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
148   // remain unresolved in the link, they can be resolved to zero, which is
149   // outside the current DSO.
150   if (TT.isOSBinFormatCOFF() && GV && GV->hasExternalWeakLinkage())
151     return false;
152 
153   // Every other GV is local on COFF.
154   // Make an exception for windows OS in the triple: Some firmware builds use
155   // *-win32-macho triples. This (accidentally?) produced windows relocations
156   // without GOT tables in older clang versions; Keep this behaviour.
157   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
158     return true;
159 
160   // Most PIC code sequences that assume that a symbol is local cannot
161   // produce a 0 if it turns out the symbol is undefined. While this
162   // is ABI and relocation depended, it seems worth it to handle it
163   // here.
164   if (GV && isPositionIndependent() && GV->hasExternalWeakLinkage())
165     return false;
166 
167   if (GV && !GV->hasDefaultVisibility())
168     return true;
169 
170   if (TT.isOSBinFormatMachO()) {
171     if (RM == Reloc::Static)
172       return true;
173     return GV && GV->isStrongDefinitionForLinker();
174   }
175 
176   assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm());
177   assert(RM != Reloc::DynamicNoPIC);
178 
179   bool IsExecutable =
180       RM == Reloc::Static || M.getPIELevel() != PIELevel::Default;
181   if (IsExecutable) {
182     // If the symbol is defined, it cannot be preempted.
183     if (GV && !GV->isDeclarationForLinker())
184       return true;
185 
186     // A symbol marked nonlazybind should not be accessed with a plt. If the
187     // symbol turns out to be external, the linker will convert a direct
188     // access to an access via the plt, so don't assume it is local.
189     const Function *F = dyn_cast_or_null<Function>(GV);
190     if (F && F->hasFnAttribute(Attribute::NonLazyBind))
191       return false;
192 
193     bool IsTLS = GV && GV->isThreadLocal();
194     bool IsAccessViaCopyRelocs =
195         GV && Options.MCOptions.MCPIECopyRelocations && isa<GlobalVariable>(GV);
196     Triple::ArchType Arch = TT.getArch();
197     bool IsPPC =
198         Arch == Triple::ppc || Arch == Triple::ppc64 || Arch == Triple::ppc64le;
199     // Check if we can use copy relocations. PowerPC has no copy relocations.
200     if (!IsTLS && !IsPPC && (RM == Reloc::Static || IsAccessViaCopyRelocs))
201       return true;
202   }
203 
204   // ELF & wasm support preemption of other symbols.
205   return false;
206 }
207 
208 bool TargetMachine::useEmulatedTLS() const {
209   // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls
210   // was specified explicitly; otherwise uses target triple to decide default.
211   if (Options.ExplicitEmulatedTLS)
212     return Options.EmulatedTLS;
213   return getTargetTriple().hasDefaultEmulatedTLS();
214 }
215 
216 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
217   bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
218   Reloc::Model RM = getRelocationModel();
219   bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
220   bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
221 
222   TLSModel::Model Model;
223   if (IsSharedLibrary) {
224     if (IsLocal)
225       Model = TLSModel::LocalDynamic;
226     else
227       Model = TLSModel::GeneralDynamic;
228   } else {
229     if (IsLocal)
230       Model = TLSModel::LocalExec;
231     else
232       Model = TLSModel::InitialExec;
233   }
234 
235   // If the user specified a more specific model, use that.
236   TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
237   if (SelectedModel > Model)
238     return SelectedModel;
239 
240   return Model;
241 }
242 
243 /// Returns the optimization level: None, Less, Default, or Aggressive.
244 CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
245 
246 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
247 
248 TargetTransformInfo TargetMachine::getTargetTransformInfo(const Function &F) {
249   return TargetTransformInfo(F.getParent()->getDataLayout());
250 }
251 
252 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
253                                       const GlobalValue *GV, Mangler &Mang,
254                                       bool MayAlwaysUsePrivate) const {
255   if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
256     // Simple case: If GV is not private, it is not important to find out if
257     // private labels are legal in this case or not.
258     Mang.getNameWithPrefix(Name, GV, false);
259     return;
260   }
261   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
262   TLOF->getNameWithPrefix(Name, GV, *this);
263 }
264 
265 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
266   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
267   SmallString<128> NameStr;
268   getNameWithPrefix(NameStr, GV, TLOF->getMangler());
269   return TLOF->getContext().getOrCreateSymbol(NameStr);
270 }
271 
272 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
273   // Since Analysis can't depend on Target, use a std::function to invert the
274   // dependency.
275   return TargetIRAnalysis(
276       [this](const Function &F) { return this->getTargetTransformInfo(F); });
277 }
278