TargetLoweringObjectFileImpl.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.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/CodeGen/TargetLoweringObjectFileImpl.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/IR/DerivedTypes.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/GlobalVariable.h"
  24. #include "llvm/IR/Mangler.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/MC/MCContext.h"
  27. #include "llvm/MC/MCExpr.h"
  28. #include "llvm/MC/MCSectionCOFF.h"
  29. #include "llvm/MC/MCSectionELF.h"
  30. #include "llvm/MC/MCSectionMachO.h"
  31. #include "llvm/MC/MCStreamer.h"
  32. #include "llvm/MC/MCSymbol.h"
  33. #include "llvm/Support/Dwarf.h"
  34. #include "llvm/Support/ELF.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include "llvm/Target/TargetLowering.h"
  38. #include "llvm/Target/TargetMachine.h"
  39. #include "llvm/Target/TargetSubtargetInfo.h"
  40. using namespace llvm;
  41. using namespace dwarf;
  42. //===----------------------------------------------------------------------===//
  43. // ELF
  44. //===----------------------------------------------------------------------===//
  45. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  46. const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
  47. MachineModuleInfo *MMI) const {
  48. unsigned Encoding = getPersonalityEncoding();
  49. if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
  50. return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
  51. TM.getSymbol(GV, Mang)->getName());
  52. if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
  53. return TM.getSymbol(GV, Mang);
  54. report_fatal_error("We do not support this DWARF encoding yet!");
  55. }
  56. void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
  57. const TargetMachine &TM,
  58. const MCSymbol *Sym) const {
  59. SmallString<64> NameData("DW.ref.");
  60. NameData += Sym->getName();
  61. MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
  62. Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
  63. Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
  64. StringRef Prefix = ".data.";
  65. NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
  66. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  67. const MCSection *Sec = getContext().getELFSection(NameData,
  68. ELF::SHT_PROGBITS,
  69. Flags,
  70. SectionKind::getDataRel(),
  71. 0, Label->getName());
  72. unsigned Size = TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
  73. Streamer.SwitchSection(Sec);
  74. Streamer.EmitValueToAlignment(
  75. TM.getSubtargetImpl()->getDataLayout()->getPointerABIAlignment());
  76. Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
  77. const MCExpr *E = MCConstantExpr::Create(Size, getContext());
  78. Streamer.EmitELFSize(Label, E);
  79. Streamer.EmitLabel(Label);
  80. Streamer.EmitSymbolValue(Sym, Size);
  81. }
  82. const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
  83. const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
  84. const TargetMachine &TM, MachineModuleInfo *MMI,
  85. MCStreamer &Streamer) const {
  86. if (Encoding & dwarf::DW_EH_PE_indirect) {
  87. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  88. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
  89. // Add information about the stub reference to ELFMMI so that the stub
  90. // gets emitted by the asmprinter.
  91. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  92. if (!StubSym.getPointer()) {
  93. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  94. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  95. }
  96. return TargetLoweringObjectFile::
  97. getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
  98. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  99. }
  100. return TargetLoweringObjectFile::
  101. getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
  102. }
  103. static SectionKind
  104. getELFKindForNamedSection(StringRef Name, SectionKind K) {
  105. // N.B.: The defaults used in here are no the same ones used in MC.
  106. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  107. // both gas and MC will produce a section with no flags. Given
  108. // section(".eh_frame") gcc will produce:
  109. //
  110. // .section .eh_frame,"a",@progbits
  111. if (Name.empty() || Name[0] != '.') return K;
  112. // Some lame default implementation based on some magic section names.
  113. if (Name == ".bss" ||
  114. Name.startswith(".bss.") ||
  115. Name.startswith(".gnu.linkonce.b.") ||
  116. Name.startswith(".llvm.linkonce.b.") ||
  117. Name == ".sbss" ||
  118. Name.startswith(".sbss.") ||
  119. Name.startswith(".gnu.linkonce.sb.") ||
  120. Name.startswith(".llvm.linkonce.sb."))
  121. return SectionKind::getBSS();
  122. if (Name == ".tdata" ||
  123. Name.startswith(".tdata.") ||
  124. Name.startswith(".gnu.linkonce.td.") ||
  125. Name.startswith(".llvm.linkonce.td."))
  126. return SectionKind::getThreadData();
  127. if (Name == ".tbss" ||
  128. Name.startswith(".tbss.") ||
  129. Name.startswith(".gnu.linkonce.tb.") ||
  130. Name.startswith(".llvm.linkonce.tb."))
  131. return SectionKind::getThreadBSS();
  132. return K;
  133. }
  134. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  135. if (Name == ".init_array")
  136. return ELF::SHT_INIT_ARRAY;
  137. if (Name == ".fini_array")
  138. return ELF::SHT_FINI_ARRAY;
  139. if (Name == ".preinit_array")
  140. return ELF::SHT_PREINIT_ARRAY;
  141. if (K.isBSS() || K.isThreadBSS())
  142. return ELF::SHT_NOBITS;
  143. return ELF::SHT_PROGBITS;
  144. }
  145. static unsigned
  146. getELFSectionFlags(SectionKind K) {
  147. unsigned Flags = 0;
  148. if (!K.isMetadata())
  149. Flags |= ELF::SHF_ALLOC;
  150. if (K.isText())
  151. Flags |= ELF::SHF_EXECINSTR;
  152. if (K.isWriteable())
  153. Flags |= ELF::SHF_WRITE;
  154. if (K.isThreadLocal())
  155. Flags |= ELF::SHF_TLS;
  156. // K.isMergeableConst() is left out to honour PR4650
  157. if (K.isMergeableCString() || K.isMergeableConst4() ||
  158. K.isMergeableConst8() || K.isMergeableConst16())
  159. Flags |= ELF::SHF_MERGE;
  160. if (K.isMergeableCString())
  161. Flags |= ELF::SHF_STRINGS;
  162. return Flags;
  163. }
  164. static const Comdat *getELFComdat(const GlobalValue *GV) {
  165. const Comdat *C = GV->getComdat();
  166. if (!C)
  167. return nullptr;
  168. if (C->getSelectionKind() != Comdat::Any)
  169. report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
  170. C->getName() + "' cannot be lowered.");
  171. return C;
  172. }
  173. const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  174. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  175. const TargetMachine &TM) const {
  176. StringRef SectionName = GV->getSection();
  177. // Infer section flags from the section name if we can.
  178. Kind = getELFKindForNamedSection(SectionName, Kind);
  179. StringRef Group = "";
  180. unsigned Flags = getELFSectionFlags(Kind);
  181. if (const Comdat *C = getELFComdat(GV)) {
  182. Group = C->getName();
  183. Flags |= ELF::SHF_GROUP;
  184. }
  185. return getContext().getELFSection(SectionName,
  186. getELFSectionType(SectionName, Kind), Flags,
  187. Kind, /*EntrySize=*/0, Group);
  188. }
  189. /// getSectionPrefixForGlobal - Return the section prefix name used by options
  190. /// FunctionsSections and DataSections.
  191. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  192. if (Kind.isText()) return ".text.";
  193. if (Kind.isReadOnly()) return ".rodata.";
  194. if (Kind.isBSS()) return ".bss.";
  195. if (Kind.isThreadData()) return ".tdata.";
  196. if (Kind.isThreadBSS()) return ".tbss.";
  197. if (Kind.isDataNoRel()) return ".data.";
  198. if (Kind.isDataRelLocal()) return ".data.rel.local.";
  199. if (Kind.isDataRel()) return ".data.rel.";
  200. if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
  201. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  202. return ".data.rel.ro.";
  203. }
  204. const MCSection *TargetLoweringObjectFileELF::
  205. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  206. Mangler &Mang, const TargetMachine &TM) const {
  207. // If we have -ffunction-section or -fdata-section then we should emit the
  208. // global value to a uniqued section specifically for it.
  209. bool EmitUniquedSection;
  210. if (Kind.isText())
  211. EmitUniquedSection = TM.getFunctionSections();
  212. else
  213. EmitUniquedSection = TM.getDataSections();
  214. // If this global is linkonce/weak and the target handles this by emitting it
  215. // into a 'uniqued' section name, create and return the section now.
  216. if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
  217. !Kind.isCommon()) {
  218. StringRef Prefix = getSectionPrefixForGlobal(Kind);
  219. SmallString<128> Name(Prefix);
  220. TM.getNameWithPrefix(Name, GV, Mang, true);
  221. StringRef Group = "";
  222. unsigned Flags = getELFSectionFlags(Kind);
  223. if (GV->isWeakForLinker() || GV->hasComdat()) {
  224. if (const Comdat *C = getELFComdat(GV))
  225. Group = C->getName();
  226. else
  227. Group = Name.substr(Prefix.size());
  228. Flags |= ELF::SHF_GROUP;
  229. }
  230. return getContext().getELFSection(Name.str(),
  231. getELFSectionType(Name.str(), Kind),
  232. Flags, Kind, 0, Group);
  233. }
  234. if (Kind.isText()) return TextSection;
  235. if (Kind.isMergeable1ByteCString() ||
  236. Kind.isMergeable2ByteCString() ||
  237. Kind.isMergeable4ByteCString()) {
  238. // We also need alignment here.
  239. // FIXME: this is getting the alignment of the character, not the
  240. // alignment of the global!
  241. unsigned Align =
  242. TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
  243. cast<GlobalVariable>(GV));
  244. const char *SizeSpec = ".rodata.str1.";
  245. if (Kind.isMergeable2ByteCString())
  246. SizeSpec = ".rodata.str2.";
  247. else if (Kind.isMergeable4ByteCString())
  248. SizeSpec = ".rodata.str4.";
  249. else
  250. assert(Kind.isMergeable1ByteCString() && "unknown string width");
  251. std::string Name = SizeSpec + utostr(Align);
  252. return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
  253. ELF::SHF_ALLOC |
  254. ELF::SHF_MERGE |
  255. ELF::SHF_STRINGS,
  256. Kind);
  257. }
  258. if (Kind.isMergeableConst()) {
  259. if (Kind.isMergeableConst4() && MergeableConst4Section)
  260. return MergeableConst4Section;
  261. if (Kind.isMergeableConst8() && MergeableConst8Section)
  262. return MergeableConst8Section;
  263. if (Kind.isMergeableConst16() && MergeableConst16Section)
  264. return MergeableConst16Section;
  265. return ReadOnlySection; // .const
  266. }
  267. if (Kind.isReadOnly()) return ReadOnlySection;
  268. if (Kind.isThreadData()) return TLSDataSection;
  269. if (Kind.isThreadBSS()) return TLSBSSSection;
  270. // Note: we claim that common symbols are put in BSSSection, but they are
  271. // really emitted with the magic .comm directive, which creates a symbol table
  272. // entry but not a section.
  273. if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
  274. if (Kind.isDataNoRel()) return DataSection;
  275. if (Kind.isDataRelLocal()) return DataRelLocalSection;
  276. if (Kind.isDataRel()) return DataRelSection;
  277. if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
  278. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  279. return DataRelROSection;
  280. }
  281. /// getSectionForConstant - Given a mergeable constant with the
  282. /// specified size and relocation information, return a section that it
  283. /// should be placed in.
  284. const MCSection *
  285. TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
  286. const Constant *C) const {
  287. if (Kind.isMergeableConst4() && MergeableConst4Section)
  288. return MergeableConst4Section;
  289. if (Kind.isMergeableConst8() && MergeableConst8Section)
  290. return MergeableConst8Section;
  291. if (Kind.isMergeableConst16() && MergeableConst16Section)
  292. return MergeableConst16Section;
  293. if (Kind.isReadOnly())
  294. return ReadOnlySection;
  295. if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
  296. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  297. return DataRelROSection;
  298. }
  299. const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  300. unsigned Priority, const MCSymbol *KeySym) const {
  301. // The default scheme is .ctor / .dtor, so we have to invert the priority
  302. // numbering.
  303. if (Priority == 65535)
  304. return StaticCtorSection;
  305. if (UseInitArray) {
  306. std::string Name = std::string(".init_array.") + utostr(Priority);
  307. return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
  308. ELF::SHF_ALLOC | ELF::SHF_WRITE,
  309. SectionKind::getDataRel());
  310. } else {
  311. std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
  312. return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
  313. ELF::SHF_ALLOC |ELF::SHF_WRITE,
  314. SectionKind::getDataRel());
  315. }
  316. }
  317. const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  318. unsigned Priority, const MCSymbol *KeySym) const {
  319. // The default scheme is .ctor / .dtor, so we have to invert the priority
  320. // numbering.
  321. if (Priority == 65535)
  322. return StaticDtorSection;
  323. if (UseInitArray) {
  324. std::string Name = std::string(".fini_array.") + utostr(Priority);
  325. return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
  326. ELF::SHF_ALLOC | ELF::SHF_WRITE,
  327. SectionKind::getDataRel());
  328. } else {
  329. std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
  330. return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
  331. ELF::SHF_ALLOC |ELF::SHF_WRITE,
  332. SectionKind::getDataRel());
  333. }
  334. }
  335. void
  336. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  337. UseInitArray = UseInitArray_;
  338. if (!UseInitArray)
  339. return;
  340. StaticCtorSection =
  341. getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  342. ELF::SHF_WRITE |
  343. ELF::SHF_ALLOC,
  344. SectionKind::getDataRel());
  345. StaticDtorSection =
  346. getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  347. ELF::SHF_WRITE |
  348. ELF::SHF_ALLOC,
  349. SectionKind::getDataRel());
  350. }
  351. //===----------------------------------------------------------------------===//
  352. // MachO
  353. //===----------------------------------------------------------------------===//
  354. /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
  355. /// option string. Returns StringRef() if the option does not specify a library.
  356. StringRef TargetLoweringObjectFileMachO::
  357. getDepLibFromLinkerOpt(StringRef LinkerOption) const {
  358. const char *LibCmd = "-l";
  359. if (LinkerOption.startswith(LibCmd))
  360. return LinkerOption.substr(strlen(LibCmd));
  361. return StringRef();
  362. }
  363. /// emitModuleFlags - Perform code emission for module flags.
  364. void TargetLoweringObjectFileMachO::
  365. emitModuleFlags(MCStreamer &Streamer,
  366. ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  367. Mangler &Mang, const TargetMachine &TM) const {
  368. unsigned VersionVal = 0;
  369. unsigned ImageInfoFlags = 0;
  370. MDNode *LinkerOptions = nullptr;
  371. StringRef SectionVal;
  372. for (ArrayRef<Module::ModuleFlagEntry>::iterator
  373. i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
  374. const Module::ModuleFlagEntry &MFE = *i;
  375. // Ignore flags with 'Require' behavior.
  376. if (MFE.Behavior == Module::Require)
  377. continue;
  378. StringRef Key = MFE.Key->getString();
  379. Value *Val = MFE.Val;
  380. if (Key == "Objective-C Image Info Version") {
  381. VersionVal = cast<ConstantInt>(Val)->getZExtValue();
  382. } else if (Key == "Objective-C Garbage Collection" ||
  383. Key == "Objective-C GC Only" ||
  384. Key == "Objective-C Is Simulated") {
  385. ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
  386. } else if (Key == "Objective-C Image Info Section") {
  387. SectionVal = cast<MDString>(Val)->getString();
  388. } else if (Key == "Linker Options") {
  389. LinkerOptions = cast<MDNode>(Val);
  390. }
  391. }
  392. // Emit the linker options if present.
  393. if (LinkerOptions) {
  394. for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
  395. MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
  396. SmallVector<std::string, 4> StrOptions;
  397. // Convert to strings.
  398. for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
  399. MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
  400. StrOptions.push_back(MDOption->getString());
  401. }
  402. Streamer.EmitLinkerOptions(StrOptions);
  403. }
  404. }
  405. // The section is mandatory. If we don't have it, then we don't have GC info.
  406. if (SectionVal.empty()) return;
  407. StringRef Segment, Section;
  408. unsigned TAA = 0, StubSize = 0;
  409. bool TAAParsed;
  410. std::string ErrorCode =
  411. MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
  412. TAA, TAAParsed, StubSize);
  413. if (!ErrorCode.empty())
  414. // If invalid, report the error with report_fatal_error.
  415. report_fatal_error("Invalid section specifier '" + Section + "': " +
  416. ErrorCode + ".");
  417. // Get the section.
  418. const MCSectionMachO *S =
  419. getContext().getMachOSection(Segment, Section, TAA, StubSize,
  420. SectionKind::getDataNoRel());
  421. Streamer.SwitchSection(S);
  422. Streamer.EmitLabel(getContext().
  423. GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  424. Streamer.EmitIntValue(VersionVal, 4);
  425. Streamer.EmitIntValue(ImageInfoFlags, 4);
  426. Streamer.AddBlankLine();
  427. }
  428. static void checkMachOComdat(const GlobalValue *GV) {
  429. const Comdat *C = GV->getComdat();
  430. if (!C)
  431. return;
  432. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  433. "' cannot be lowered.");
  434. }
  435. const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  436. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  437. const TargetMachine &TM) const {
  438. // Parse the section specifier and create it if valid.
  439. StringRef Segment, Section;
  440. unsigned TAA = 0, StubSize = 0;
  441. bool TAAParsed;
  442. checkMachOComdat(GV);
  443. std::string ErrorCode =
  444. MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
  445. TAA, TAAParsed, StubSize);
  446. if (!ErrorCode.empty()) {
  447. // If invalid, report the error with report_fatal_error.
  448. report_fatal_error("Global variable '" + GV->getName() +
  449. "' has an invalid section specifier '" +
  450. GV->getSection() + "': " + ErrorCode + ".");
  451. }
  452. // Get the section.
  453. const MCSectionMachO *S =
  454. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  455. // If TAA wasn't set by ParseSectionSpecifier() above,
  456. // use the value returned by getMachOSection() as a default.
  457. if (!TAAParsed)
  458. TAA = S->getTypeAndAttributes();
  459. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  460. // If the user declared multiple globals with different section flags, we need
  461. // to reject it here.
  462. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  463. // If invalid, report the error with report_fatal_error.
  464. report_fatal_error("Global variable '" + GV->getName() +
  465. "' section type or attributes does not match previous"
  466. " section specifier");
  467. }
  468. return S;
  469. }
  470. bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
  471. const MCSection &Section) const {
  472. const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
  473. // Sections holding 1 byte strings are atomized based on the data
  474. // they contain.
  475. // Sections holding 2 byte strings require symbols in order to be
  476. // atomized.
  477. // There is no dedicated section for 4 byte strings.
  478. if (SMO.getKind().isMergeable1ByteCString())
  479. return false;
  480. if (SMO.getSegmentName() == "__DATA" &&
  481. SMO.getSectionName() == "__cfstring")
  482. return false;
  483. switch (SMO.getType()) {
  484. default:
  485. return true;
  486. // These sections are atomized at the element boundaries without using
  487. // symbols.
  488. case MachO::S_4BYTE_LITERALS:
  489. case MachO::S_8BYTE_LITERALS:
  490. case MachO::S_16BYTE_LITERALS:
  491. case MachO::S_LITERAL_POINTERS:
  492. case MachO::S_NON_LAZY_SYMBOL_POINTERS:
  493. case MachO::S_LAZY_SYMBOL_POINTERS:
  494. case MachO::S_MOD_INIT_FUNC_POINTERS:
  495. case MachO::S_MOD_TERM_FUNC_POINTERS:
  496. case MachO::S_INTERPOSING:
  497. return false;
  498. }
  499. }
  500. const MCSection *TargetLoweringObjectFileMachO::
  501. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  502. Mangler &Mang, const TargetMachine &TM) const {
  503. checkMachOComdat(GV);
  504. // Handle thread local data.
  505. if (Kind.isThreadBSS()) return TLSBSSSection;
  506. if (Kind.isThreadData()) return TLSDataSection;
  507. if (Kind.isText())
  508. return GV->isWeakForLinker() ? TextCoalSection : TextSection;
  509. // If this is weak/linkonce, put this in a coalescable section, either in text
  510. // or data depending on if it is writable.
  511. if (GV->isWeakForLinker()) {
  512. if (Kind.isReadOnly())
  513. return ConstTextCoalSection;
  514. return DataCoalSection;
  515. }
  516. // FIXME: Alignment check should be handled by section classifier.
  517. if (Kind.isMergeable1ByteCString() &&
  518. TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
  519. cast<GlobalVariable>(GV)) < 32)
  520. return CStringSection;
  521. // Do not put 16-bit arrays in the UString section if they have an
  522. // externally visible label, this runs into issues with certain linker
  523. // versions.
  524. if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
  525. TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
  526. cast<GlobalVariable>(GV)) < 32)
  527. return UStringSection;
  528. if (Kind.isMergeableConst()) {
  529. if (Kind.isMergeableConst4())
  530. return FourByteConstantSection;
  531. if (Kind.isMergeableConst8())
  532. return EightByteConstantSection;
  533. if (Kind.isMergeableConst16())
  534. return SixteenByteConstantSection;
  535. }
  536. // Otherwise, if it is readonly, but not something we can specially optimize,
  537. // just drop it in .const.
  538. if (Kind.isReadOnly())
  539. return ReadOnlySection;
  540. // If this is marked const, put it into a const section. But if the dynamic
  541. // linker needs to write to it, put it in the data segment.
  542. if (Kind.isReadOnlyWithRel())
  543. return ConstDataSection;
  544. // Put zero initialized globals with strong external linkage in the
  545. // DATA, __common section with the .zerofill directive.
  546. if (Kind.isBSSExtern())
  547. return DataCommonSection;
  548. // Put zero initialized globals with local linkage in __DATA,__bss directive
  549. // with the .zerofill directive (aka .lcomm).
  550. if (Kind.isBSSLocal())
  551. return DataBSSSection;
  552. // Otherwise, just drop the variable in the normal data section.
  553. return DataSection;
  554. }
  555. const MCSection *
  556. TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
  557. const Constant *C) const {
  558. // If this constant requires a relocation, we have to put it in the data
  559. // segment, not in the text segment.
  560. if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
  561. return ConstDataSection;
  562. if (Kind.isMergeableConst4())
  563. return FourByteConstantSection;
  564. if (Kind.isMergeableConst8())
  565. return EightByteConstantSection;
  566. if (Kind.isMergeableConst16())
  567. return SixteenByteConstantSection;
  568. return ReadOnlySection; // .const
  569. }
  570. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  571. const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
  572. const TargetMachine &TM, MachineModuleInfo *MMI,
  573. MCStreamer &Streamer) const {
  574. // The mach-o version of this method defaults to returning a stub reference.
  575. if (Encoding & DW_EH_PE_indirect) {
  576. MachineModuleInfoMachO &MachOMMI =
  577. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  578. MCSymbol *SSym =
  579. getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
  580. // Add information about the stub reference to MachOMMI so that the stub
  581. // gets emitted by the asmprinter.
  582. MachineModuleInfoImpl::StubValueTy &StubSym =
  583. GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
  584. MachOMMI.getGVStubEntry(SSym);
  585. if (!StubSym.getPointer()) {
  586. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  587. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  588. }
  589. return TargetLoweringObjectFile::
  590. getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
  591. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  592. }
  593. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
  594. TM, MMI, Streamer);
  595. }
  596. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  597. const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
  598. MachineModuleInfo *MMI) const {
  599. // The mach-o version of this method defaults to returning a stub reference.
  600. MachineModuleInfoMachO &MachOMMI =
  601. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  602. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
  603. // Add information about the stub reference to MachOMMI so that the stub
  604. // gets emitted by the asmprinter.
  605. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  606. if (!StubSym.getPointer()) {
  607. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  608. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  609. }
  610. return SSym;
  611. }
  612. //===----------------------------------------------------------------------===//
  613. // COFF
  614. //===----------------------------------------------------------------------===//
  615. static unsigned
  616. getCOFFSectionFlags(SectionKind K) {
  617. unsigned Flags = 0;
  618. if (K.isMetadata())
  619. Flags |=
  620. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  621. else if (K.isText())
  622. Flags |=
  623. COFF::IMAGE_SCN_MEM_EXECUTE |
  624. COFF::IMAGE_SCN_MEM_READ |
  625. COFF::IMAGE_SCN_CNT_CODE;
  626. else if (K.isBSS ())
  627. Flags |=
  628. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  629. COFF::IMAGE_SCN_MEM_READ |
  630. COFF::IMAGE_SCN_MEM_WRITE;
  631. else if (K.isThreadLocal())
  632. Flags |=
  633. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  634. COFF::IMAGE_SCN_MEM_READ |
  635. COFF::IMAGE_SCN_MEM_WRITE;
  636. else if (K.isReadOnly())
  637. Flags |=
  638. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  639. COFF::IMAGE_SCN_MEM_READ;
  640. else if (K.isWriteable())
  641. Flags |=
  642. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  643. COFF::IMAGE_SCN_MEM_READ |
  644. COFF::IMAGE_SCN_MEM_WRITE;
  645. return Flags;
  646. }
  647. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  648. const Comdat *C = GV->getComdat();
  649. assert(C && "expected GV to have a Comdat!");
  650. StringRef ComdatGVName = C->getName();
  651. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  652. if (!ComdatGV)
  653. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  654. "' does not exist.");
  655. if (ComdatGV->getComdat() != C)
  656. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  657. "' is not a key for it's COMDAT.");
  658. return ComdatGV;
  659. }
  660. static int getSelectionForCOFF(const GlobalValue *GV) {
  661. if (const Comdat *C = GV->getComdat()) {
  662. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  663. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  664. ComdatKey = GA->getBaseObject();
  665. if (ComdatKey == GV) {
  666. switch (C->getSelectionKind()) {
  667. case Comdat::Any:
  668. return COFF::IMAGE_COMDAT_SELECT_ANY;
  669. case Comdat::ExactMatch:
  670. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  671. case Comdat::Largest:
  672. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  673. case Comdat::NoDuplicates:
  674. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  675. case Comdat::SameSize:
  676. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  677. }
  678. } else {
  679. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  680. }
  681. } else if (GV->isWeakForLinker()) {
  682. return COFF::IMAGE_COMDAT_SELECT_ANY;
  683. }
  684. return 0;
  685. }
  686. const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  687. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  688. const TargetMachine &TM) const {
  689. int Selection = 0;
  690. unsigned Characteristics = getCOFFSectionFlags(Kind);
  691. StringRef Name = GV->getSection();
  692. StringRef COMDATSymName = "";
  693. if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
  694. Selection = getSelectionForCOFF(GV);
  695. const GlobalValue *ComdatGV;
  696. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  697. ComdatGV = getComdatGVForCOFF(GV);
  698. else
  699. ComdatGV = GV;
  700. if (!ComdatGV->hasPrivateLinkage()) {
  701. MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
  702. COMDATSymName = Sym->getName();
  703. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  704. } else {
  705. Selection = 0;
  706. }
  707. }
  708. return getContext().getCOFFSection(Name,
  709. Characteristics,
  710. Kind,
  711. COMDATSymName,
  712. Selection);
  713. }
  714. static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  715. if (Kind.isText())
  716. return ".text";
  717. if (Kind.isBSS())
  718. return ".bss";
  719. if (Kind.isThreadLocal())
  720. return ".tls$";
  721. if (Kind.isWriteable())
  722. return ".data";
  723. return ".rdata";
  724. }
  725. const MCSection *TargetLoweringObjectFileCOFF::
  726. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  727. Mangler &Mang, const TargetMachine &TM) const {
  728. // If we have -ffunction-sections then we should emit the global value to a
  729. // uniqued section specifically for it.
  730. bool EmitUniquedSection;
  731. if (Kind.isText())
  732. EmitUniquedSection = TM.getFunctionSections();
  733. else
  734. EmitUniquedSection = TM.getDataSections();
  735. // If this global is linkonce/weak and the target handles this by emitting it
  736. // into a 'uniqued' section name, create and return the section now.
  737. // Section names depend on the name of the symbol which is not feasible if the
  738. // symbol has private linkage.
  739. if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
  740. !Kind.isCommon()) {
  741. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  742. unsigned Characteristics = getCOFFSectionFlags(Kind);
  743. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  744. int Selection = getSelectionForCOFF(GV);
  745. if (!Selection)
  746. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  747. const GlobalValue *ComdatGV;
  748. if (GV->hasComdat())
  749. ComdatGV = getComdatGVForCOFF(GV);
  750. else
  751. ComdatGV = GV;
  752. if (!ComdatGV->hasPrivateLinkage()) {
  753. MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
  754. StringRef COMDATSymName = Sym->getName();
  755. return getContext().getCOFFSection(Name, Characteristics, Kind,
  756. COMDATSymName, Selection);
  757. }
  758. }
  759. if (Kind.isText())
  760. return TextSection;
  761. if (Kind.isThreadLocal())
  762. return TLSDataSection;
  763. if (Kind.isReadOnly())
  764. return ReadOnlySection;
  765. // Note: we claim that common symbols are put in BSSSection, but they are
  766. // really emitted with the magic .comm directive, which creates a symbol table
  767. // entry but not a section.
  768. if (Kind.isBSS() || Kind.isCommon())
  769. return BSSSection;
  770. return DataSection;
  771. }
  772. StringRef TargetLoweringObjectFileCOFF::
  773. getDepLibFromLinkerOpt(StringRef LinkerOption) const {
  774. const char *LibCmd = "/DEFAULTLIB:";
  775. if (LinkerOption.startswith(LibCmd))
  776. return LinkerOption.substr(strlen(LibCmd));
  777. return StringRef();
  778. }
  779. void TargetLoweringObjectFileCOFF::
  780. emitModuleFlags(MCStreamer &Streamer,
  781. ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  782. Mangler &Mang, const TargetMachine &TM) const {
  783. MDNode *LinkerOptions = nullptr;
  784. // Look for the "Linker Options" flag, since it's the only one we support.
  785. for (ArrayRef<Module::ModuleFlagEntry>::iterator
  786. i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
  787. const Module::ModuleFlagEntry &MFE = *i;
  788. StringRef Key = MFE.Key->getString();
  789. Value *Val = MFE.Val;
  790. if (Key == "Linker Options") {
  791. LinkerOptions = cast<MDNode>(Val);
  792. break;
  793. }
  794. }
  795. if (!LinkerOptions)
  796. return;
  797. // Emit the linker options to the linker .drectve section. According to the
  798. // spec, this section is a space-separated string containing flags for linker.
  799. const MCSection *Sec = getDrectveSection();
  800. Streamer.SwitchSection(Sec);
  801. for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
  802. MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
  803. for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
  804. MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
  805. StringRef Op = MDOption->getString();
  806. // Lead with a space for consistency with our dllexport implementation.
  807. std::string Escaped(" ");
  808. if (Op.find(" ") != StringRef::npos) {
  809. // The PE-COFF spec says args with spaces must be quoted. It doesn't say
  810. // how to escape quotes, but it probably uses this algorithm:
  811. // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
  812. // FIXME: Reuse escaping code from Support/Windows/Program.inc
  813. Escaped.push_back('\"');
  814. Escaped.append(Op);
  815. Escaped.push_back('\"');
  816. } else {
  817. Escaped.append(Op);
  818. }
  819. Streamer.EmitBytes(Escaped);
  820. }
  821. }
  822. }
  823. static const MCSection *getAssociativeCOFFSection(MCContext &Ctx,
  824. const MCSection *Sec,
  825. const MCSymbol *KeySym) {
  826. // Return the normal section if we don't have to be associative.
  827. if (!KeySym)
  828. return Sec;
  829. // Make an associative section with the same name and kind as the normal
  830. // section.
  831. const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec);
  832. unsigned Characteristics =
  833. SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
  834. return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics,
  835. SecCOFF->getKind(), KeySym->getName(),
  836. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
  837. }
  838. const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  839. unsigned Priority, const MCSymbol *KeySym) const {
  840. return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym);
  841. }
  842. const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  843. unsigned Priority, const MCSymbol *KeySym) const {
  844. return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym);
  845. }