TargetLoweringObjectFileImpl.cpp 35 KB

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