TargetMachine.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. #include "llvm/Target/TargetMachine.h"
  13. #include "llvm/Analysis/TargetTransformInfo.h"
  14. #include "llvm/IR/Function.h"
  15. #include "llvm/IR/GlobalValue.h"
  16. #include "llvm/IR/GlobalVariable.h"
  17. #include "llvm/IR/Mangler.h"
  18. #include "llvm/MC/MCAsmInfo.h"
  19. #include "llvm/MC/MCContext.h"
  20. #include "llvm/MC/MCInstrInfo.h"
  21. #include "llvm/MC/MCRegisterInfo.h"
  22. #include "llvm/MC/MCSubtargetInfo.h"
  23. #include "llvm/Target/TargetLoweringObjectFile.h"
  24. using namespace llvm;
  25. //---------------------------------------------------------------------------
  26. // TargetMachine Class
  27. //
  28. TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
  29. const Triple &TT, StringRef CPU, StringRef FS,
  30. const TargetOptions &Options)
  31. : TheTarget(T), DL(DataLayoutString), TargetTriple(TT),
  32. TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
  33. MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
  34. O0WantsFastISel(false), DefaultOptions(Options), Options(Options) {}
  35. TargetMachine::~TargetMachine() = default;
  36. bool TargetMachine::isPositionIndependent() const {
  37. return getRelocationModel() == Reloc::PIC_;
  38. }
  39. /// Reset the target options based on the function's attributes.
  40. /// setFunctionAttributes should have made the raw attribute value consistent
  41. /// with the command line flag if used.
  42. //
  43. // FIXME: This function needs to go away for a number of reasons:
  44. // a) global state on the TargetMachine is terrible in general,
  45. // b) these target options should be passed only on the function
  46. // and not on the TargetMachine (via TargetOptions) at all.
  47. void TargetMachine::resetTargetOptions(const Function &F) const {
  48. #define RESET_OPTION(X, Y) \
  49. do { \
  50. Options.X = F.getFnAttribute(Y).getValueAsBool(); \
  51. } while (0)
  52. RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
  53. RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
  54. RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
  55. RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
  56. RESET_OPTION(ApproxFuncFPMath, "approx-func-fp-math");
  57. }
  58. /// Returns the code generation relocation model. The choices are static, PIC,
  59. /// and dynamic-no-pic.
  60. Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
  61. /// Get the IR-specified TLS model for Var.
  62. static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
  63. switch (GV->getThreadLocalMode()) {
  64. case GlobalVariable::NotThreadLocal:
  65. llvm_unreachable("getSelectedTLSModel for non-TLS variable");
  66. break;
  67. case GlobalVariable::GeneralDynamicTLSModel:
  68. return TLSModel::GeneralDynamic;
  69. case GlobalVariable::LocalDynamicTLSModel:
  70. return TLSModel::LocalDynamic;
  71. case GlobalVariable::InitialExecTLSModel:
  72. return TLSModel::InitialExec;
  73. case GlobalVariable::LocalExecTLSModel:
  74. return TLSModel::LocalExec;
  75. }
  76. llvm_unreachable("invalid TLS model");
  77. }
  78. bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
  79. const GlobalValue *GV) const {
  80. const Triple &TT = getTargetTriple();
  81. Reloc::Model RM = getRelocationModel();
  82. // According to the llvm language reference, we should be able to
  83. // just return false in here if we have a GV, as we know it is
  84. // dso_preemptable. At this point in time, the various IR producers
  85. // have not been transitioned to always produce a dso_local when it
  86. // is possible to do so.
  87. //
  88. // As a result we still have some logic in here to improve the quality of the
  89. // generated code.
  90. if (!GV)
  91. return false;
  92. // If the IR producer requested that this GV be treated as dso local, obey.
  93. if (GV->isDSOLocal())
  94. return true;
  95. if (TT.isOSBinFormatCOFF()) {
  96. // DLLImport explicitly marks the GV as external.
  97. if (GV->hasDLLImportStorageClass())
  98. return false;
  99. // On MinGW, variables that haven't been declared with DLLImport may still
  100. // end up automatically imported by the linker. To make this feasible,
  101. // don't assume the variables to be DSO local unless we actually know
  102. // that for sure. This only has to be done for variables; for functions
  103. // the linker can insert thunks for calling functions from another DLL.
  104. if (TT.isWindowsGNUEnvironment() && GV->isDeclarationForLinker() &&
  105. isa<GlobalVariable>(GV))
  106. return false;
  107. // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
  108. // unresolved in the link, they can be resolved to zero, which is outside
  109. // the current DSO.
  110. if (GV->hasExternalWeakLinkage())
  111. return false;
  112. // Every other GV is local on COFF.
  113. return true;
  114. }
  115. if (TT.isOSBinFormatGOFF())
  116. return true;
  117. if (TT.isOSBinFormatMachO()) {
  118. if (RM == Reloc::Static)
  119. return true;
  120. return GV->isStrongDefinitionForLinker();
  121. }
  122. assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
  123. TT.isOSBinFormatXCOFF());
  124. return false;
  125. }
  126. bool TargetMachine::useEmulatedTLS() const {
  127. // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls
  128. // was specified explicitly; otherwise uses target triple to decide default.
  129. if (Options.ExplicitEmulatedTLS)
  130. return Options.EmulatedTLS;
  131. return getTargetTriple().hasDefaultEmulatedTLS();
  132. }
  133. TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
  134. bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
  135. Reloc::Model RM = getRelocationModel();
  136. bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
  137. bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
  138. TLSModel::Model Model;
  139. if (IsSharedLibrary) {
  140. if (IsLocal)
  141. Model = TLSModel::LocalDynamic;
  142. else
  143. Model = TLSModel::GeneralDynamic;
  144. } else {
  145. if (IsLocal)
  146. Model = TLSModel::LocalExec;
  147. else
  148. Model = TLSModel::InitialExec;
  149. }
  150. // If the user specified a more specific model, use that.
  151. TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
  152. if (SelectedModel > Model)
  153. return SelectedModel;
  154. return Model;
  155. }
  156. /// Returns the optimization level: None, Less, Default, or Aggressive.
  157. CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
  158. void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
  159. TargetTransformInfo
  160. TargetMachine::getTargetTransformInfo(const Function &F) const {
  161. return TargetTransformInfo(F.getParent()->getDataLayout());
  162. }
  163. void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
  164. const GlobalValue *GV, Mangler &Mang,
  165. bool MayAlwaysUsePrivate) const {
  166. if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
  167. // Simple case: If GV is not private, it is not important to find out if
  168. // private labels are legal in this case or not.
  169. Mang.getNameWithPrefix(Name, GV, false);
  170. return;
  171. }
  172. const TargetLoweringObjectFile *TLOF = getObjFileLowering();
  173. TLOF->getNameWithPrefix(Name, GV, *this);
  174. }
  175. MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
  176. const TargetLoweringObjectFile *TLOF = getObjFileLowering();
  177. // XCOFF symbols could have special naming convention.
  178. if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
  179. return TargetSymbol;
  180. SmallString<128> NameStr;
  181. getNameWithPrefix(NameStr, GV, TLOF->getMangler());
  182. return TLOF->getContext().getOrCreateSymbol(NameStr);
  183. }
  184. TargetIRAnalysis TargetMachine::getTargetIRAnalysis() const {
  185. // Since Analysis can't depend on Target, use a std::function to invert the
  186. // dependency.
  187. return TargetIRAnalysis(
  188. [this](const Function &F) { return this->getTargetTransformInfo(F); });
  189. }
  190. std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
  191. if (Version == "none")
  192. return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
  193. std::pair<int, int> Ret;
  194. if (!Version.consumeInteger(10, Ret.first) && Version.consume_front("."))
  195. Version.consumeInteger(10, Ret.second);
  196. return Ret;
  197. }