1bb8507e6SMatthias Braun //===-- TargetMachine.cpp - General Target Information ---------------------==//
2bb8507e6SMatthias Braun //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bb8507e6SMatthias Braun //
7bb8507e6SMatthias Braun //===----------------------------------------------------------------------===//
8bb8507e6SMatthias Braun //
9bb8507e6SMatthias Braun // This file describes the general parts of a Target machine.
10bb8507e6SMatthias Braun //
11bb8507e6SMatthias Braun //===----------------------------------------------------------------------===//
12bb8507e6SMatthias Braun 
13bb8507e6SMatthias Braun #include "llvm/Target/TargetMachine.h"
14bb8507e6SMatthias Braun #include "llvm/Analysis/TargetTransformInfo.h"
15bb8507e6SMatthias Braun #include "llvm/IR/Function.h"
16bb8507e6SMatthias Braun #include "llvm/IR/GlobalAlias.h"
17bb8507e6SMatthias Braun #include "llvm/IR/GlobalValue.h"
18bb8507e6SMatthias Braun #include "llvm/IR/GlobalVariable.h"
19bb8507e6SMatthias Braun #include "llvm/IR/LegacyPassManager.h"
20bb8507e6SMatthias Braun #include "llvm/IR/Mangler.h"
21bb8507e6SMatthias Braun #include "llvm/MC/MCAsmInfo.h"
22bb8507e6SMatthias Braun #include "llvm/MC/MCContext.h"
23bb8507e6SMatthias Braun #include "llvm/MC/MCInstrInfo.h"
24bb8507e6SMatthias Braun #include "llvm/MC/MCSectionMachO.h"
25bb8507e6SMatthias Braun #include "llvm/MC/MCTargetOptions.h"
26bb8507e6SMatthias Braun #include "llvm/MC/SectionKind.h"
276054e650SDavid Blaikie #include "llvm/Target/TargetLoweringObjectFile.h"
28bb8507e6SMatthias Braun using namespace llvm;
29bb8507e6SMatthias Braun 
30bb8507e6SMatthias Braun //---------------------------------------------------------------------------
31bb8507e6SMatthias Braun // TargetMachine Class
32bb8507e6SMatthias Braun //
33bb8507e6SMatthias Braun 
34bb8507e6SMatthias Braun TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
35bb8507e6SMatthias Braun                              const Triple &TT, StringRef CPU, StringRef FS,
36bb8507e6SMatthias Braun                              const TargetOptions &Options)
37adcd0268SBenjamin Kramer     : TheTarget(T), DL(DataLayoutString), TargetTriple(TT),
38adcd0268SBenjamin Kramer       TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
39adcd0268SBenjamin Kramer       MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
40adcd0268SBenjamin Kramer       O0WantsFastISel(false), DefaultOptions(Options), Options(Options) {}
41bb8507e6SMatthias Braun 
4210a21625SFangrui Song TargetMachine::~TargetMachine() = default;
43bb8507e6SMatthias Braun 
44bb8507e6SMatthias Braun bool TargetMachine::isPositionIndependent() const {
45bb8507e6SMatthias Braun   return getRelocationModel() == Reloc::PIC_;
46bb8507e6SMatthias Braun }
47bb8507e6SMatthias Braun 
485f8f34e4SAdrian Prantl /// Reset the target options based on the function's attributes.
49c378e52cSMatt Arsenault /// setFunctionAttributes should have made the raw attribute value consistent
50c378e52cSMatt Arsenault /// with the command line flag if used.
51c378e52cSMatt Arsenault //
52bb8507e6SMatthias Braun // FIXME: This function needs to go away for a number of reasons:
53bb8507e6SMatthias Braun // a) global state on the TargetMachine is terrible in general,
54bb8507e6SMatthias Braun // b) these target options should be passed only on the function
55bb8507e6SMatthias Braun //    and not on the TargetMachine (via TargetOptions) at all.
56bb8507e6SMatthias Braun void TargetMachine::resetTargetOptions(const Function &F) const {
57bb8507e6SMatthias Braun #define RESET_OPTION(X, Y)                                              \
58bb8507e6SMatthias Braun   do {                                                                  \
59bb8507e6SMatthias Braun     Options.X = (F.getFnAttribute(Y).getValueAsString() == "true");     \
60bb8507e6SMatthias Braun   } while (0)
61bb8507e6SMatthias Braun 
62bb8507e6SMatthias Braun   RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
63bb8507e6SMatthias Braun   RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
64bb8507e6SMatthias Braun   RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
65bb8507e6SMatthias Braun   RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
66bb8507e6SMatthias Braun }
67bb8507e6SMatthias Braun 
68bb8507e6SMatthias Braun /// Returns the code generation relocation model. The choices are static, PIC,
69bb8507e6SMatthias Braun /// and dynamic-no-pic.
70bb8507e6SMatthias Braun Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
71bb8507e6SMatthias Braun 
72bb8507e6SMatthias Braun /// Returns the code model. The choices are small, kernel, medium, large, and
73bb8507e6SMatthias Braun /// target default.
74bb8507e6SMatthias Braun CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; }
75bb8507e6SMatthias Braun 
76bb8507e6SMatthias Braun /// Get the IR-specified TLS model for Var.
77bb8507e6SMatthias Braun static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
78bb8507e6SMatthias Braun   switch (GV->getThreadLocalMode()) {
79bb8507e6SMatthias Braun   case GlobalVariable::NotThreadLocal:
80bb8507e6SMatthias Braun     llvm_unreachable("getSelectedTLSModel for non-TLS variable");
81bb8507e6SMatthias Braun     break;
82bb8507e6SMatthias Braun   case GlobalVariable::GeneralDynamicTLSModel:
83bb8507e6SMatthias Braun     return TLSModel::GeneralDynamic;
84bb8507e6SMatthias Braun   case GlobalVariable::LocalDynamicTLSModel:
85bb8507e6SMatthias Braun     return TLSModel::LocalDynamic;
86bb8507e6SMatthias Braun   case GlobalVariable::InitialExecTLSModel:
87bb8507e6SMatthias Braun     return TLSModel::InitialExec;
88bb8507e6SMatthias Braun   case GlobalVariable::LocalExecTLSModel:
89bb8507e6SMatthias Braun     return TLSModel::LocalExec;
90bb8507e6SMatthias Braun   }
91bb8507e6SMatthias Braun   llvm_unreachable("invalid TLS model");
92bb8507e6SMatthias Braun }
93bb8507e6SMatthias Braun 
94bb8507e6SMatthias Braun bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
95bb8507e6SMatthias Braun                                          const GlobalValue *GV) const {
96*68edf39eSFangrui Song   const Triple &TT = getTargetTriple();
97*68edf39eSFangrui Song   Reloc::Model RM = getRelocationModel();
9863c378d3SRafael Espindola 
9963c378d3SRafael Espindola   // According to the llvm language reference, we should be able to
10063c378d3SRafael Espindola   // just return false in here if we have a GV, as we know it is
10163c378d3SRafael Espindola   // dso_preemptable.  At this point in time, the various IR producers
10263c378d3SRafael Espindola   // have not been transitioned to always produce a dso_local when it
10363c378d3SRafael Espindola   // is possible to do so.
104*68edf39eSFangrui Song   // In the case of ExternalSymbolSDNode, GV is null and there is nowhere to put
10563c378d3SRafael Espindola   // dso_local. Returning false for those will produce worse code in some
10663c378d3SRafael Espindola   // architectures. For example, on x86 the caller has to set ebx before calling
10763c378d3SRafael Espindola   // a plt.
10863c378d3SRafael Espindola   // As a result we still have some logic in here to improve the quality of the
10963c378d3SRafael Espindola   // generated code.
11063c378d3SRafael Espindola   // FIXME: Add a module level metadata for whether intrinsics should be assumed
11163c378d3SRafael Espindola   // local.
112*68edf39eSFangrui Song   if (!GV) {
113*68edf39eSFangrui Song     if (TT.isOSBinFormatCOFF())
114*68edf39eSFangrui Song       return true;
115*68edf39eSFangrui Song     if (TT.isOSBinFormatELF() && TT.isX86() && RM == Reloc::Static) {
116*68edf39eSFangrui Song       // For -fno-plt, we cannot assume that intrinsics are local since the
117*68edf39eSFangrui Song       // linker can convert some direct access to access via plt.
118*68edf39eSFangrui Song       return !M.getRtLibUseGOT();
119*68edf39eSFangrui Song     }
1206f36637bSRafael Espindola 
121*68edf39eSFangrui Song     return false;
122*68edf39eSFangrui Song   }
123*68edf39eSFangrui Song 
124*68edf39eSFangrui Song   // If the IR producer requested that this GV be treated as dso local, obey.
125*68edf39eSFangrui Song   if (GV->isDSOLocal())
126*68edf39eSFangrui Song     return true;
127bb8507e6SMatthias Braun 
128bb8507e6SMatthias Braun   // DLLImport explicitly marks the GV as external.
129*68edf39eSFangrui Song   if (GV->hasDLLImportStorageClass())
130bb8507e6SMatthias Braun     return false;
131bb8507e6SMatthias Braun 
13268df812cSMartin Storsjo   // On MinGW, variables that haven't been declared with DLLImport may still
13368df812cSMartin Storsjo   // end up automatically imported by the linker. To make this feasible,
13468df812cSMartin Storsjo   // don't assume the variables to be DSO local unless we actually know
13568df812cSMartin Storsjo   // that for sure. This only has to be done for variables; for functions
13668df812cSMartin Storsjo   // the linker can insert thunks for calling functions from another DLL.
137*68edf39eSFangrui Song   if (TT.isWindowsGNUEnvironment() && TT.isOSBinFormatCOFF() &&
138514f3a12SMartin Storsjo       GV->isDeclarationForLinker() && isa<GlobalVariable>(GV))
13968df812cSMartin Storsjo     return false;
14068df812cSMartin Storsjo 
1416bf108d7SReid Kleckner   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1426bf108d7SReid Kleckner   // remain unresolved in the link, they can be resolved to zero, which is
1436bf108d7SReid Kleckner   // outside the current DSO.
144*68edf39eSFangrui Song   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1456bf108d7SReid Kleckner     return false;
1466bf108d7SReid Kleckner 
147bb8507e6SMatthias Braun   // Every other GV is local on COFF.
148ba02f3f2SRafael Espindola   // Make an exception for windows OS in the triple: Some firmware builds use
149bb8507e6SMatthias Braun   // *-win32-macho triples. This (accidentally?) produced windows relocations
150bb8507e6SMatthias Braun   // without GOT tables in older clang versions; Keep this behaviour.
151514f3a12SMartin Storsjo   // Some JIT users use *-win32-elf triples; these shouldn't use GOT tables
152514f3a12SMartin Storsjo   // either.
153514f3a12SMartin Storsjo   if (TT.isOSBinFormatCOFF() || TT.isOSWindows())
154bb8507e6SMatthias Braun     return true;
155bb8507e6SMatthias Braun 
1562393c3b4SRafael Espindola   // Most PIC code sequences that assume that a symbol is local cannot
1572393c3b4SRafael Espindola   // produce a 0 if it turns out the symbol is undefined. While this
1582393c3b4SRafael Espindola   // is ABI and relocation depended, it seems worth it to handle it
1592393c3b4SRafael Espindola   // here.
160*68edf39eSFangrui Song   if (isPositionIndependent() && GV->hasExternalWeakLinkage())
1612393c3b4SRafael Espindola     return false;
1622393c3b4SRafael Espindola 
163*68edf39eSFangrui Song   if (!GV->hasDefaultVisibility())
164bb8507e6SMatthias Braun     return true;
165bb8507e6SMatthias Braun 
166ea38ac5bSSam Clegg   if (TT.isOSBinFormatMachO()) {
167bb8507e6SMatthias Braun     if (RM == Reloc::Static)
168bb8507e6SMatthias Braun       return true;
169*68edf39eSFangrui Song     return GV->isStrongDefinitionForLinker();
170bb8507e6SMatthias Braun   }
171bb8507e6SMatthias Braun 
1728e1d921bSJason Liu   // Due to the AIX linkage model, any global with default visibility is
1738e1d921bSJason Liu   // considered non-local.
1748e1d921bSJason Liu   if (TT.isOSBinFormatXCOFF())
1758e1d921bSJason Liu     return false;
1768e1d921bSJason Liu 
177ea38ac5bSSam Clegg   assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm());
178bb8507e6SMatthias Braun   assert(RM != Reloc::DynamicNoPIC);
179bb8507e6SMatthias Braun 
180bb8507e6SMatthias Braun   bool IsExecutable =
181bb8507e6SMatthias Braun       RM == Reloc::Static || M.getPIELevel() != PIELevel::Default;
182bb8507e6SMatthias Braun   if (IsExecutable) {
183bb8507e6SMatthias Braun     // If the symbol is defined, it cannot be preempted.
184*68edf39eSFangrui Song     if (!GV->isDeclarationForLinker())
185bb8507e6SMatthias Braun       return true;
186bb8507e6SMatthias Braun 
187056b3fd6SSriraman Tallam     // A symbol marked nonlazybind should not be accessed with a plt. If the
188056b3fd6SSriraman Tallam     // symbol turns out to be external, the linker will convert a direct
189056b3fd6SSriraman Tallam     // access to an access via the plt, so don't assume it is local.
190*68edf39eSFangrui Song     const Function *F = dyn_cast<Function>(GV);
191056b3fd6SSriraman Tallam     if (F && F->hasFnAttribute(Attribute::NonLazyBind))
192056b3fd6SSriraman Tallam       return false;
193bb8507e6SMatthias Braun     Triple::ArchType Arch = TT.getArch();
194d2bb8c16SFangrui Song 
1951ab9327dSFangrui Song     // PowerPC64 prefers TOC indirection to avoid copy relocations.
1961ab9327dSFangrui Song     if (TT.isPPC64())
197d2bb8c16SFangrui Song       return false;
198d2bb8c16SFangrui Song 
199961f31d8SFangrui Song     // dso_local is traditionally implied for Reloc::Static. Eventually we shall
200961f31d8SFangrui Song     // drop the if block entirely and respect dso_local/dso_preemptable
201961f31d8SFangrui Song     // specifiers set by the frontend.
202961f31d8SFangrui Song     if (RM == Reloc::Static) {
203961f31d8SFangrui Song       // We currently respect dso_local/dso_preemptable specifiers for
204961f31d8SFangrui Song       // variables.
205*68edf39eSFangrui Song       if (F)
206bb8507e6SMatthias Braun         return true;
2072ec43a7bSFangrui Song       // TODO Remove the special case for x86-32.
2082ec43a7bSFangrui Song       if (Arch == Triple::x86 && !GV->isThreadLocal())
209961f31d8SFangrui Song         return true;
210961f31d8SFangrui Song     }
2119d55e4eeSFangrui Song   } else if (TT.isOSBinFormatELF()) {
2129d55e4eeSFangrui Song     // If dso_local allows AsmPrinter::getSymbolPreferLocal to use a local
2139d55e4eeSFangrui Song     // alias, set the flag. We cannot set dso_local for other global values,
2149d55e4eeSFangrui Song     // because otherwise direct accesses to a probably interposable symbol (even
2159d55e4eeSFangrui Song     // if the codegen assumes not) will be rejected by the linker.
216*68edf39eSFangrui Song     if (!GV->canBenefitFromLocalAlias())
2179d55e4eeSFangrui Song       return false;
2189d55e4eeSFangrui Song     return TT.isX86() && M.noSemanticInterposition();
219bb8507e6SMatthias Braun   }
220bb8507e6SMatthias Braun 
221ea38ac5bSSam Clegg   // ELF & wasm support preemption of other symbols.
222bb8507e6SMatthias Braun   return false;
223bb8507e6SMatthias Braun }
224bb8507e6SMatthias Braun 
2259f9e4681SChih-Hung Hsieh bool TargetMachine::useEmulatedTLS() const {
2269f9e4681SChih-Hung Hsieh   // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls
2279f9e4681SChih-Hung Hsieh   // was specified explicitly; otherwise uses target triple to decide default.
2289f9e4681SChih-Hung Hsieh   if (Options.ExplicitEmulatedTLS)
2299f9e4681SChih-Hung Hsieh     return Options.EmulatedTLS;
2309f9e4681SChih-Hung Hsieh   return getTargetTriple().hasDefaultEmulatedTLS();
2319f9e4681SChih-Hung Hsieh }
2329f9e4681SChih-Hung Hsieh 
233bb8507e6SMatthias Braun TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
234bb8507e6SMatthias Braun   bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
235bb8507e6SMatthias Braun   Reloc::Model RM = getRelocationModel();
236bb8507e6SMatthias Braun   bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
237bb8507e6SMatthias Braun   bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
238bb8507e6SMatthias Braun 
239bb8507e6SMatthias Braun   TLSModel::Model Model;
240bb8507e6SMatthias Braun   if (IsSharedLibrary) {
241bb8507e6SMatthias Braun     if (IsLocal)
242bb8507e6SMatthias Braun       Model = TLSModel::LocalDynamic;
243bb8507e6SMatthias Braun     else
244bb8507e6SMatthias Braun       Model = TLSModel::GeneralDynamic;
245bb8507e6SMatthias Braun   } else {
246bb8507e6SMatthias Braun     if (IsLocal)
247bb8507e6SMatthias Braun       Model = TLSModel::LocalExec;
248bb8507e6SMatthias Braun     else
249bb8507e6SMatthias Braun       Model = TLSModel::InitialExec;
250bb8507e6SMatthias Braun   }
251bb8507e6SMatthias Braun 
252bb8507e6SMatthias Braun   // If the user specified a more specific model, use that.
253bb8507e6SMatthias Braun   TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
254bb8507e6SMatthias Braun   if (SelectedModel > Model)
255bb8507e6SMatthias Braun     return SelectedModel;
256bb8507e6SMatthias Braun 
257bb8507e6SMatthias Braun   return Model;
258bb8507e6SMatthias Braun }
259bb8507e6SMatthias Braun 
260bb8507e6SMatthias Braun /// Returns the optimization level: None, Less, Default, or Aggressive.
261bb8507e6SMatthias Braun CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
262bb8507e6SMatthias Braun 
263bb8507e6SMatthias Braun void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
264bb8507e6SMatthias Braun 
26526d11ca4SSanjoy Das TargetTransformInfo TargetMachine::getTargetTransformInfo(const Function &F) {
266bb8507e6SMatthias Braun   return TargetTransformInfo(F.getParent()->getDataLayout());
267bb8507e6SMatthias Braun }
268bb8507e6SMatthias Braun 
269bb8507e6SMatthias Braun void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
270bb8507e6SMatthias Braun                                       const GlobalValue *GV, Mangler &Mang,
271bb8507e6SMatthias Braun                                       bool MayAlwaysUsePrivate) const {
272bb8507e6SMatthias Braun   if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
273bb8507e6SMatthias Braun     // Simple case: If GV is not private, it is not important to find out if
274bb8507e6SMatthias Braun     // private labels are legal in this case or not.
275bb8507e6SMatthias Braun     Mang.getNameWithPrefix(Name, GV, false);
276bb8507e6SMatthias Braun     return;
277bb8507e6SMatthias Braun   }
278bb8507e6SMatthias Braun   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
279bb8507e6SMatthias Braun   TLOF->getNameWithPrefix(Name, GV, *this);
280bb8507e6SMatthias Braun }
281bb8507e6SMatthias Braun 
282bb8507e6SMatthias Braun MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
283bb8507e6SMatthias Braun   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
28477618cc2Sjasonliu   // XCOFF symbols could have special naming convention.
28577618cc2Sjasonliu   if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
28677618cc2Sjasonliu     return TargetSymbol;
28777618cc2Sjasonliu 
288bb8507e6SMatthias Braun   SmallString<128> NameStr;
289bb8507e6SMatthias Braun   getNameWithPrefix(NameStr, GV, TLOF->getMangler());
290bb8507e6SMatthias Braun   return TLOF->getContext().getOrCreateSymbol(NameStr);
291bb8507e6SMatthias Braun }
29226d11ca4SSanjoy Das 
29326d11ca4SSanjoy Das TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
29426d11ca4SSanjoy Das   // Since Analysis can't depend on Target, use a std::function to invert the
29526d11ca4SSanjoy Das   // dependency.
29626d11ca4SSanjoy Das   return TargetIRAnalysis(
29726d11ca4SSanjoy Das       [this](const Function &F) { return this->getTargetTransformInfo(F); });
29826d11ca4SSanjoy Das }
299