1193323Sed//===-- TargetMachine.cpp - General Target Information ---------------------==// 2193323Sed// 3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4353358Sdim// See https://llvm.org/LICENSE.txt for license information. 5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6193323Sed// 7193323Sed//===----------------------------------------------------------------------===// 8193323Sed// 9193323Sed// This file describes the general parts of a Target machine. 10193323Sed// 11193323Sed//===----------------------------------------------------------------------===// 12193323Sed 13249423Sdim#include "llvm/Target/TargetMachine.h" 14288943Sdim#include "llvm/Analysis/TargetTransformInfo.h" 15249423Sdim#include "llvm/IR/Function.h" 16249423Sdim#include "llvm/IR/GlobalAlias.h" 17249423Sdim#include "llvm/IR/GlobalValue.h" 18249423Sdim#include "llvm/IR/GlobalVariable.h" 19309124Sdim#include "llvm/IR/LegacyPassManager.h" 20276479Sdim#include "llvm/IR/Mangler.h" 21198090Srdivacky#include "llvm/MC/MCAsmInfo.h" 22276479Sdim#include "llvm/MC/MCContext.h" 23288943Sdim#include "llvm/MC/MCInstrInfo.h" 24280031Sdim#include "llvm/MC/MCSectionMachO.h" 25276479Sdim#include "llvm/MC/MCTargetOptions.h" 26276479Sdim#include "llvm/MC/SectionKind.h" 27341825Sdim#include "llvm/Target/TargetLoweringObjectFile.h" 28193323Sedusing namespace llvm; 29193323Sed 30193323Sed//--------------------------------------------------------------------------- 31193323Sed// TargetMachine Class 32193323Sed// 33193323Sed 34288943SdimTargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString, 35288943Sdim const Triple &TT, StringRef CPU, StringRef FS, 36234353Sdim const TargetOptions &Options) 37288943Sdim : TheTarget(T), DL(DataLayoutString), TargetTriple(TT), TargetCPU(CPU), 38309124Sdim TargetFS(FS), AsmInfo(nullptr), MRI(nullptr), MII(nullptr), STI(nullptr), 39360784Sdim RequireStructuredCFG(false), O0WantsFastISel(false), 40360784Sdim DefaultOptions(Options), Options(Options) {} 41194178Sed 42344779SdimTargetMachine::~TargetMachine() = default; 43193323Sed 44309124Sdimbool TargetMachine::isPositionIndependent() const { 45309124Sdim return getRelocationModel() == Reloc::PIC_; 46309124Sdim} 47309124Sdim 48341825Sdim/// Reset the target options based on the function's attributes. 49288943Sdim// FIXME: This function needs to go away for a number of reasons: 50288943Sdim// a) global state on the TargetMachine is terrible in general, 51314564Sdim// b) these target options should be passed only on the function 52288943Sdim// and not on the TargetMachine (via TargetOptions) at all. 53280031Sdimvoid TargetMachine::resetTargetOptions(const Function &F) const { 54280031Sdim#define RESET_OPTION(X, Y) \ 55280031Sdim do { \ 56288943Sdim if (F.hasFnAttribute(Y)) \ 57288943Sdim Options.X = (F.getFnAttribute(Y).getValueAsString() == "true"); \ 58314564Sdim else \ 59314564Sdim Options.X = DefaultOptions.X; \ 60249423Sdim } while (0) 61249423Sdim 62249423Sdim RESET_OPTION(UnsafeFPMath, "unsafe-fp-math"); 63249423Sdim RESET_OPTION(NoInfsFPMath, "no-infs-fp-math"); 64249423Sdim RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math"); 65321369Sdim RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math"); 66249423Sdim} 67249423Sdim 68309124Sdim/// Returns the code generation relocation model. The choices are static, PIC, 69309124Sdim/// and dynamic-no-pic. 70309124SdimReloc::Model TargetMachine::getRelocationModel() const { return RM; } 71193323Sed 72309124Sdim/// Returns the code model. The choices are small, kernel, medium, large, and 73309124Sdim/// target default. 74309124SdimCodeModel::Model TargetMachine::getCodeModel() const { return CMModel; } 75193323Sed 76239462Sdim/// Get the IR-specified TLS model for Var. 77276479Sdimstatic TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) { 78276479Sdim switch (GV->getThreadLocalMode()) { 79239462Sdim case GlobalVariable::NotThreadLocal: 80239462Sdim llvm_unreachable("getSelectedTLSModel for non-TLS variable"); 81239462Sdim break; 82239462Sdim case GlobalVariable::GeneralDynamicTLSModel: 83239462Sdim return TLSModel::GeneralDynamic; 84239462Sdim case GlobalVariable::LocalDynamicTLSModel: 85239462Sdim return TLSModel::LocalDynamic; 86239462Sdim case GlobalVariable::InitialExecTLSModel: 87239462Sdim return TLSModel::InitialExec; 88239462Sdim case GlobalVariable::LocalExecTLSModel: 89239462Sdim return TLSModel::LocalExec; 90239462Sdim } 91239462Sdim llvm_unreachable("invalid TLS model"); 92239462Sdim} 93239462Sdim 94309124Sdimbool TargetMachine::shouldAssumeDSOLocal(const Module &M, 95309124Sdim const GlobalValue *GV) const { 96327952Sdim // If the IR producer requested that this GV be treated as dso local, obey. 97327952Sdim if (GV && GV->isDSOLocal()) 98327952Sdim return true; 99327952Sdim 100341825Sdim // If we are not supossed to use a PLT, we cannot assume that intrinsics are 101341825Sdim // local since the linker can convert some direct access to access via plt. 102341825Sdim if (M.getRtLibUseGOT() && !GV) 103341825Sdim return false; 104327952Sdim 105341825Sdim // According to the llvm language reference, we should be able to 106341825Sdim // just return false in here if we have a GV, as we know it is 107341825Sdim // dso_preemptable. At this point in time, the various IR producers 108341825Sdim // have not been transitioned to always produce a dso_local when it 109341825Sdim // is possible to do so. 110341825Sdim // In the case of intrinsics, GV is null and there is nowhere to put 111341825Sdim // dso_local. Returning false for those will produce worse code in some 112341825Sdim // architectures. For example, on x86 the caller has to set ebx before calling 113341825Sdim // a plt. 114341825Sdim // As a result we still have some logic in here to improve the quality of the 115341825Sdim // generated code. 116341825Sdim // FIXME: Add a module level metadata for whether intrinsics should be assumed 117341825Sdim // local. 118341825Sdim 119309124Sdim Reloc::Model RM = getRelocationModel(); 120309124Sdim const Triple &TT = getTargetTriple(); 121309124Sdim 122309124Sdim // DLLImport explicitly marks the GV as external. 123309124Sdim if (GV && GV->hasDLLImportStorageClass()) 124309124Sdim return false; 125309124Sdim 126344779Sdim // On MinGW, variables that haven't been declared with DLLImport may still 127344779Sdim // end up automatically imported by the linker. To make this feasible, 128344779Sdim // don't assume the variables to be DSO local unless we actually know 129344779Sdim // that for sure. This only has to be done for variables; for functions 130344779Sdim // the linker can insert thunks for calling functions from another DLL. 131353358Sdim if (TT.isWindowsGNUEnvironment() && TT.isOSBinFormatCOFF() && GV && 132353358Sdim GV->isDeclarationForLinker() && isa<GlobalVariable>(GV)) 133344779Sdim return false; 134344779Sdim 135353358Sdim // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 136353358Sdim // remain unresolved in the link, they can be resolved to zero, which is 137353358Sdim // outside the current DSO. 138353358Sdim if (TT.isOSBinFormatCOFF() && GV && GV->hasExternalWeakLinkage()) 139353358Sdim return false; 140353358Sdim 141314564Sdim // Every other GV is local on COFF. 142341825Sdim // Make an exception for windows OS in the triple: Some firmware builds use 143314564Sdim // *-win32-macho triples. This (accidentally?) produced windows relocations 144314564Sdim // without GOT tables in older clang versions; Keep this behaviour. 145353358Sdim // Some JIT users use *-win32-elf triples; these shouldn't use GOT tables 146353358Sdim // either. 147353358Sdim if (TT.isOSBinFormatCOFF() || TT.isOSWindows()) 148309124Sdim return true; 149309124Sdim 150327952Sdim // Most PIC code sequences that assume that a symbol is local cannot 151327952Sdim // produce a 0 if it turns out the symbol is undefined. While this 152327952Sdim // is ABI and relocation depended, it seems worth it to handle it 153327952Sdim // here. 154341825Sdim if (GV && isPositionIndependent() && GV->hasExternalWeakLinkage()) 155327952Sdim return false; 156327952Sdim 157341825Sdim if (GV && !GV->hasDefaultVisibility()) 158309124Sdim return true; 159309124Sdim 160309124Sdim if (TT.isOSBinFormatMachO()) { 161309124Sdim if (RM == Reloc::Static) 162309124Sdim return true; 163309124Sdim return GV && GV->isStrongDefinitionForLinker(); 164309124Sdim } 165309124Sdim 166353358Sdim // Due to the AIX linkage model, any global with default visibility is 167353358Sdim // considered non-local. 168353358Sdim if (TT.isOSBinFormatXCOFF()) 169353358Sdim return false; 170353358Sdim 171353358Sdim assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm()); 172309124Sdim assert(RM != Reloc::DynamicNoPIC); 173309124Sdim 174309124Sdim bool IsExecutable = 175309124Sdim RM == Reloc::Static || M.getPIELevel() != PIELevel::Default; 176309124Sdim if (IsExecutable) { 177309124Sdim // If the symbol is defined, it cannot be preempted. 178309124Sdim if (GV && !GV->isDeclarationForLinker()) 179309124Sdim return true; 180309124Sdim 181327952Sdim // A symbol marked nonlazybind should not be accessed with a plt. If the 182327952Sdim // symbol turns out to be external, the linker will convert a direct 183327952Sdim // access to an access via the plt, so don't assume it is local. 184327952Sdim const Function *F = dyn_cast_or_null<Function>(GV); 185327952Sdim if (F && F->hasFnAttribute(Attribute::NonLazyBind)) 186327952Sdim return false; 187360784Sdim Triple::ArchType Arch = TT.getArch(); 188327952Sdim 189360784Sdim // PowerPC prefers avoiding copy relocations. 190360784Sdim if (Arch == Triple::ppc || TT.isPPC64()) 191360784Sdim return false; 192360784Sdim 193360784Sdim // Check if we can use copy relocations. 194360784Sdim if (!(GV && GV->isThreadLocal()) && RM == Reloc::Static) 195309124Sdim return true; 196309124Sdim } 197309124Sdim 198353358Sdim // ELF & wasm support preemption of other symbols. 199309124Sdim return false; 200309124Sdim} 201309124Sdim 202341825Sdimbool TargetMachine::useEmulatedTLS() const { 203341825Sdim // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls 204341825Sdim // was specified explicitly; otherwise uses target triple to decide default. 205341825Sdim if (Options.ExplicitEmulatedTLS) 206341825Sdim return Options.EmulatedTLS; 207341825Sdim return getTargetTriple().hasDefaultEmulatedTLS(); 208341825Sdim} 209341825Sdim 210234353SdimTLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const { 211309124Sdim bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default; 212309124Sdim Reloc::Model RM = getRelocationModel(); 213309124Sdim bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE; 214309124Sdim bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV); 215234353Sdim 216239462Sdim TLSModel::Model Model; 217309124Sdim if (IsSharedLibrary) { 218309124Sdim if (IsLocal) 219239462Sdim Model = TLSModel::LocalDynamic; 220234353Sdim else 221239462Sdim Model = TLSModel::GeneralDynamic; 222234353Sdim } else { 223309124Sdim if (IsLocal) 224239462Sdim Model = TLSModel::LocalExec; 225234353Sdim else 226239462Sdim Model = TLSModel::InitialExec; 227234353Sdim } 228239462Sdim 229239462Sdim // If the user specified a more specific model, use that. 230276479Sdim TLSModel::Model SelectedModel = getSelectedTLSModel(GV); 231239462Sdim if (SelectedModel > Model) 232239462Sdim return SelectedModel; 233239462Sdim 234239462Sdim return Model; 235234353Sdim} 236234353Sdim 237309124Sdim/// Returns the optimization level: None, Less, Default, or Aggressive. 238309124SdimCodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; } 239234353Sdim 240309124Sdimvoid TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; } 241261991Sdim 242327952SdimTargetTransformInfo TargetMachine::getTargetTransformInfo(const Function &F) { 243327952Sdim return TargetTransformInfo(F.getParent()->getDataLayout()); 244193323Sed} 245193323Sed 246276479Sdimvoid TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name, 247276479Sdim const GlobalValue *GV, Mangler &Mang, 248276479Sdim bool MayAlwaysUsePrivate) const { 249276479Sdim if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) { 250276479Sdim // Simple case: If GV is not private, it is not important to find out if 251276479Sdim // private labels are legal in this case or not. 252276479Sdim Mang.getNameWithPrefix(Name, GV, false); 253276479Sdim return; 254276479Sdim } 255288943Sdim const TargetLoweringObjectFile *TLOF = getObjFileLowering(); 256314564Sdim TLOF->getNameWithPrefix(Name, GV, *this); 257276479Sdim} 258276479Sdim 259314564SdimMCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const { 260314564Sdim const TargetLoweringObjectFile *TLOF = getObjFileLowering(); 261288943Sdim SmallString<128> NameStr; 262314564Sdim getNameWithPrefix(NameStr, GV, TLOF->getMangler()); 263288943Sdim return TLOF->getContext().getOrCreateSymbol(NameStr); 264276479Sdim} 265327952Sdim 266327952SdimTargetIRAnalysis TargetMachine::getTargetIRAnalysis() { 267327952Sdim // Since Analysis can't depend on Target, use a std::function to invert the 268327952Sdim // dependency. 269327952Sdim return TargetIRAnalysis( 270327952Sdim [this](const Function &F) { return this->getTargetTransformInfo(F); }); 271327952Sdim} 272