TargetMachine.cpp 8.6 KB

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