TargetLoweringObjectFile.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements classes used to handle lowerings specific to common
  11. // object file formats.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Target/TargetLoweringObjectFile.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/GlobalVariable.h"
  20. #include "llvm/IR/Mangler.h"
  21. #include "llvm/MC/MCAsmInfo.h"
  22. #include "llvm/MC/MCContext.h"
  23. #include "llvm/MC/MCExpr.h"
  24. #include "llvm/MC/MCStreamer.h"
  25. #include "llvm/MC/MCSymbol.h"
  26. #include "llvm/Support/Dwarf.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Target/TargetLowering.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/Target/TargetOptions.h"
  32. #include "llvm/Target/TargetSubtargetInfo.h"
  33. using namespace llvm;
  34. //===----------------------------------------------------------------------===//
  35. // Generic Code
  36. //===----------------------------------------------------------------------===//
  37. /// Initialize - this method must be called before any actual lowering is
  38. /// done. This specifies the current context for codegen, and gives the
  39. /// lowering implementations a chance to set up their default sections.
  40. void TargetLoweringObjectFile::Initialize(MCContext &ctx,
  41. const TargetMachine &TM) {
  42. Ctx = &ctx;
  43. Mang = new Mangler();
  44. InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(),
  45. TM.getCodeModel(), *Ctx);
  46. }
  47. TargetLoweringObjectFile::~TargetLoweringObjectFile() {
  48. delete Mang;
  49. }
  50. static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
  51. const Constant *C = GV->getInitializer();
  52. // Must have zero initializer.
  53. if (!C->isNullValue())
  54. return false;
  55. // Leave constant zeros in readonly constant sections, so they can be shared.
  56. if (GV->isConstant())
  57. return false;
  58. // If the global has an explicit section specified, don't put it in BSS.
  59. if (GV->hasSection())
  60. return false;
  61. // If -nozero-initialized-in-bss is specified, don't ever use BSS.
  62. if (NoZerosInBSS)
  63. return false;
  64. // Otherwise, put it in BSS!
  65. return true;
  66. }
  67. /// IsNullTerminatedString - Return true if the specified constant (which is
  68. /// known to have a type that is an array of 1/2/4 byte elements) ends with a
  69. /// nul value and contains no other nuls in it. Note that this is more general
  70. /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
  71. static bool IsNullTerminatedString(const Constant *C) {
  72. // First check: is we have constant array terminated with zero
  73. if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
  74. unsigned NumElts = CDS->getNumElements();
  75. assert(NumElts != 0 && "Can't have an empty CDS");
  76. if (CDS->getElementAsInteger(NumElts-1) != 0)
  77. return false; // Not null terminated.
  78. // Verify that the null doesn't occur anywhere else in the string.
  79. for (unsigned i = 0; i != NumElts-1; ++i)
  80. if (CDS->getElementAsInteger(i) == 0)
  81. return false;
  82. return true;
  83. }
  84. // Another possibility: [1 x i8] zeroinitializer
  85. if (isa<ConstantAggregateZero>(C))
  86. return cast<ArrayType>(C->getType())->getNumElements() == 1;
  87. return false;
  88. }
  89. MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
  90. const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
  91. assert(!Suffix.empty());
  92. SmallString<60> NameStr;
  93. NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
  94. TM.getNameWithPrefix(NameStr, GV, *Mang);
  95. NameStr.append(Suffix.begin(), Suffix.end());
  96. return Ctx->getOrCreateSymbol(NameStr);
  97. }
  98. MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
  99. const GlobalValue *GV, const TargetMachine &TM,
  100. MachineModuleInfo *MMI) const {
  101. return TM.getSymbol(GV, *Mang);
  102. }
  103. void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
  104. const DataLayout &,
  105. const MCSymbol *Sym) const {
  106. }
  107. /// getKindForGlobal - This is a top-level target-independent classifier for
  108. /// a global variable. Given an global variable and information from TM, it
  109. /// classifies the global in a variety of ways that make various target
  110. /// implementations simpler. The target implementation is free to ignore this
  111. /// extra info of course.
  112. SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
  113. const TargetMachine &TM){
  114. assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
  115. "Can only be used for global definitions");
  116. Reloc::Model ReloModel = TM.getRelocationModel();
  117. // Early exit - functions should be always in text sections.
  118. const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
  119. if (!GVar)
  120. return SectionKind::getText();
  121. // Handle thread-local data first.
  122. if (GVar->isThreadLocal()) {
  123. if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
  124. return SectionKind::getThreadBSS();
  125. return SectionKind::getThreadData();
  126. }
  127. // Variables with common linkage always get classified as common.
  128. if (GVar->hasCommonLinkage())
  129. return SectionKind::getCommon();
  130. // Variable can be easily put to BSS section.
  131. if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
  132. if (GVar->hasLocalLinkage())
  133. return SectionKind::getBSSLocal();
  134. else if (GVar->hasExternalLinkage())
  135. return SectionKind::getBSSExtern();
  136. return SectionKind::getBSS();
  137. }
  138. const Constant *C = GVar->getInitializer();
  139. // If the global is marked constant, we can put it into a mergable section,
  140. // a mergable string section, or general .data if it contains relocations.
  141. if (GVar->isConstant()) {
  142. // If the initializer for the global contains something that requires a
  143. // relocation, then we may have to drop this into a writable data section
  144. // even though it is marked const.
  145. if (!C->needsRelocation()) {
  146. // If the global is required to have a unique address, it can't be put
  147. // into a mergable section: just drop it into the general read-only
  148. // section instead.
  149. if (!GVar->hasGlobalUnnamedAddr())
  150. return SectionKind::getReadOnly();
  151. // If initializer is a null-terminated string, put it in a "cstring"
  152. // section of the right width.
  153. if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
  154. if (IntegerType *ITy =
  155. dyn_cast<IntegerType>(ATy->getElementType())) {
  156. if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
  157. ITy->getBitWidth() == 32) &&
  158. IsNullTerminatedString(C)) {
  159. if (ITy->getBitWidth() == 8)
  160. return SectionKind::getMergeable1ByteCString();
  161. if (ITy->getBitWidth() == 16)
  162. return SectionKind::getMergeable2ByteCString();
  163. assert(ITy->getBitWidth() == 32 && "Unknown width");
  164. return SectionKind::getMergeable4ByteCString();
  165. }
  166. }
  167. }
  168. // Otherwise, just drop it into a mergable constant section. If we have
  169. // a section for this size, use it, otherwise use the arbitrary sized
  170. // mergable section.
  171. switch (GV->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
  172. case 4: return SectionKind::getMergeableConst4();
  173. case 8: return SectionKind::getMergeableConst8();
  174. case 16: return SectionKind::getMergeableConst16();
  175. case 32: return SectionKind::getMergeableConst32();
  176. default:
  177. return SectionKind::getReadOnly();
  178. }
  179. } else {
  180. // In static, ROPI and RWPI relocation models, the linker will resolve
  181. // all addresses, so the relocation entries will actually be constants by
  182. // the time the app starts up. However, we can't put this into a
  183. // mergable section, because the linker doesn't take relocations into
  184. // consideration when it tries to merge entries in the section.
  185. if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
  186. ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
  187. return SectionKind::getReadOnly();
  188. // Otherwise, the dynamic linker needs to fix it up, put it in the
  189. // writable data.rel section.
  190. return SectionKind::getReadOnlyWithRel();
  191. }
  192. }
  193. // Okay, this isn't a constant.
  194. return SectionKind::getData();
  195. }
  196. /// This method computes the appropriate section to emit the specified global
  197. /// variable or function definition. This should not be passed external (or
  198. /// available externally) globals.
  199. MCSection *TargetLoweringObjectFile::SectionForGlobal(
  200. const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
  201. // Select section name.
  202. if (GV->hasSection())
  203. return getExplicitSectionGlobal(GV, Kind, TM);
  204. // Use default section depending on the 'type' of global
  205. return SelectSectionForGlobal(GV, Kind, TM);
  206. }
  207. MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
  208. const Function &F, const TargetMachine &TM) const {
  209. unsigned Align = 0;
  210. return getSectionForConstant(F.getParent()->getDataLayout(),
  211. SectionKind::getReadOnly(), /*C=*/nullptr,
  212. Align);
  213. }
  214. bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
  215. bool UsesLabelDifference, const Function &F) const {
  216. // In PIC mode, we need to emit the jump table to the same section as the
  217. // function body itself, otherwise the label differences won't make sense.
  218. // FIXME: Need a better predicate for this: what about custom entries?
  219. if (UsesLabelDifference)
  220. return true;
  221. // We should also do if the section name is NULL or function is declared
  222. // in discardable section
  223. // FIXME: this isn't the right predicate, should be based on the MCSection
  224. // for the function.
  225. if (F.isWeakForLinker())
  226. return true;
  227. return false;
  228. }
  229. /// Given a mergable constant with the specified size and relocation
  230. /// information, return a section that it should be placed in.
  231. MCSection *TargetLoweringObjectFile::getSectionForConstant(
  232. const DataLayout &DL, SectionKind Kind, const Constant *C,
  233. unsigned &Align) const {
  234. if (Kind.isReadOnly() && ReadOnlySection != nullptr)
  235. return ReadOnlySection;
  236. return DataSection;
  237. }
  238. /// getTTypeGlobalReference - Return an MCExpr to use for a
  239. /// reference to the specified global variable from exception
  240. /// handling information.
  241. const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
  242. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  243. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  244. const MCSymbolRefExpr *Ref =
  245. MCSymbolRefExpr::create(TM.getSymbol(GV, *Mang), getContext());
  246. return getTTypeReference(Ref, Encoding, Streamer);
  247. }
  248. const MCExpr *TargetLoweringObjectFile::
  249. getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
  250. MCStreamer &Streamer) const {
  251. switch (Encoding & 0x70) {
  252. default:
  253. report_fatal_error("We do not support this DWARF encoding yet!");
  254. case dwarf::DW_EH_PE_absptr:
  255. // Do nothing special
  256. return Sym;
  257. case dwarf::DW_EH_PE_pcrel: {
  258. // Emit a label to the streamer for the current position. This gives us
  259. // .-foo addressing.
  260. MCSymbol *PCSym = getContext().createTempSymbol();
  261. Streamer.EmitLabel(PCSym);
  262. const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
  263. return MCBinaryExpr::createSub(Sym, PC, getContext());
  264. }
  265. }
  266. }
  267. const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
  268. // FIXME: It's not clear what, if any, default this should have - perhaps a
  269. // null return could mean 'no location' & we should just do that here.
  270. return MCSymbolRefExpr::create(Sym, *Ctx);
  271. }
  272. void TargetLoweringObjectFile::getNameWithPrefix(
  273. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  274. const TargetMachine &TM) const {
  275. Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
  276. }