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