2
0

TargetLoweringObjectFileImpl.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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/MCSymbolELF.h"
  33. #include "llvm/MC/MCValue.h"
  34. #include "llvm/Support/Dwarf.h"
  35. #include "llvm/Support/ELF.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Target/TargetLowering.h"
  39. #include "llvm/Target/TargetMachine.h"
  40. #include "llvm/Target/TargetSubtargetInfo.h"
  41. using namespace llvm;
  42. using namespace dwarf;
  43. //===----------------------------------------------------------------------===//
  44. // ELF
  45. //===----------------------------------------------------------------------===//
  46. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  47. const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
  48. MachineModuleInfo *MMI) const {
  49. unsigned Encoding = getPersonalityEncoding();
  50. if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
  51. return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
  52. TM.getSymbol(GV, Mang)->getName());
  53. if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
  54. return TM.getSymbol(GV, Mang);
  55. report_fatal_error("We do not support this DWARF encoding yet!");
  56. }
  57. void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
  58. const TargetMachine &TM,
  59. const MCSymbol *Sym) const {
  60. SmallString<64> NameData("DW.ref.");
  61. NameData += Sym->getName();
  62. MCSymbolELF *Label =
  63. cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
  64. Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
  65. Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
  66. StringRef Prefix = ".data.";
  67. NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
  68. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  69. MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
  70. Flags, 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 getELFSectionFlags(SectionKind K) {
  144. unsigned Flags = 0;
  145. if (!K.isMetadata())
  146. Flags |= ELF::SHF_ALLOC;
  147. if (K.isText())
  148. Flags |= ELF::SHF_EXECINSTR;
  149. if (K.isWriteable())
  150. Flags |= ELF::SHF_WRITE;
  151. if (K.isThreadLocal())
  152. Flags |= ELF::SHF_TLS;
  153. if (K.isMergeableCString() || K.isMergeableConst())
  154. Flags |= ELF::SHF_MERGE;
  155. if (K.isMergeableCString())
  156. Flags |= ELF::SHF_STRINGS;
  157. return Flags;
  158. }
  159. static const Comdat *getELFComdat(const GlobalValue *GV) {
  160. const Comdat *C = GV->getComdat();
  161. if (!C)
  162. return nullptr;
  163. if (C->getSelectionKind() != Comdat::Any)
  164. report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
  165. C->getName() + "' cannot be lowered.");
  166. return C;
  167. }
  168. MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  169. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  170. const TargetMachine &TM) const {
  171. StringRef SectionName = GV->getSection();
  172. // Infer section flags from the section name if we can.
  173. Kind = getELFKindForNamedSection(SectionName, Kind);
  174. StringRef Group = "";
  175. unsigned Flags = getELFSectionFlags(Kind);
  176. if (const Comdat *C = getELFComdat(GV)) {
  177. Group = C->getName();
  178. Flags |= ELF::SHF_GROUP;
  179. }
  180. return getContext().getELFSection(SectionName,
  181. getELFSectionType(SectionName, Kind), Flags,
  182. /*EntrySize=*/0, Group);
  183. }
  184. /// Return the section prefix name used by options FunctionsSections and
  185. /// DataSections.
  186. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  187. if (Kind.isText())
  188. return ".text";
  189. if (Kind.isReadOnly())
  190. return ".rodata";
  191. if (Kind.isBSS())
  192. return ".bss";
  193. if (Kind.isThreadData())
  194. return ".tdata";
  195. if (Kind.isThreadBSS())
  196. return ".tbss";
  197. if (Kind.isDataNoRel())
  198. return ".data";
  199. if (Kind.isDataRelLocal())
  200. return ".data.rel.local";
  201. if (Kind.isDataRel())
  202. return ".data.rel";
  203. if (Kind.isReadOnlyWithRelLocal())
  204. return ".data.rel.ro.local";
  205. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  206. return ".data.rel.ro";
  207. }
  208. static MCSectionELF *
  209. selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
  210. SectionKind Kind, Mangler &Mang,
  211. const TargetMachine &TM, bool EmitUniqueSection,
  212. unsigned Flags, unsigned *NextUniqueID) {
  213. unsigned EntrySize = 0;
  214. if (Kind.isMergeableCString()) {
  215. if (Kind.isMergeable2ByteCString()) {
  216. EntrySize = 2;
  217. } else if (Kind.isMergeable4ByteCString()) {
  218. EntrySize = 4;
  219. } else {
  220. EntrySize = 1;
  221. assert(Kind.isMergeable1ByteCString() && "unknown string width");
  222. }
  223. } else if (Kind.isMergeableConst()) {
  224. if (Kind.isMergeableConst4()) {
  225. EntrySize = 4;
  226. } else if (Kind.isMergeableConst8()) {
  227. EntrySize = 8;
  228. } else {
  229. assert(Kind.isMergeableConst16() && "unknown data width");
  230. EntrySize = 16;
  231. }
  232. }
  233. StringRef Group = "";
  234. if (const Comdat *C = getELFComdat(GV)) {
  235. Flags |= ELF::SHF_GROUP;
  236. Group = C->getName();
  237. }
  238. bool UniqueSectionNames = TM.getUniqueSectionNames();
  239. SmallString<128> Name;
  240. if (Kind.isMergeableCString()) {
  241. // We also need alignment here.
  242. // FIXME: this is getting the alignment of the character, not the
  243. // alignment of the global!
  244. unsigned Align =
  245. TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
  246. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  247. Name = SizeSpec + utostr(Align);
  248. } else if (Kind.isMergeableConst()) {
  249. Name = ".rodata.cst";
  250. Name += utostr(EntrySize);
  251. } else {
  252. Name = getSectionPrefixForGlobal(Kind);
  253. }
  254. if (EmitUniqueSection && UniqueSectionNames) {
  255. Name.push_back('.');
  256. TM.getNameWithPrefix(Name, GV, Mang, true);
  257. }
  258. unsigned UniqueID = ~0;
  259. if (EmitUniqueSection && !UniqueSectionNames) {
  260. UniqueID = *NextUniqueID;
  261. (*NextUniqueID)++;
  262. }
  263. return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
  264. EntrySize, Group, UniqueID);
  265. }
  266. MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
  267. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  268. const TargetMachine &TM) const {
  269. unsigned Flags = getELFSectionFlags(Kind);
  270. // If we have -ffunction-section or -fdata-section then we should emit the
  271. // global value to a uniqued section specifically for it.
  272. bool EmitUniqueSection = false;
  273. if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
  274. if (Kind.isText())
  275. EmitUniqueSection = TM.getFunctionSections();
  276. else
  277. EmitUniqueSection = TM.getDataSections();
  278. }
  279. EmitUniqueSection |= GV->hasComdat();
  280. return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
  281. EmitUniqueSection, Flags, &NextUniqueID);
  282. }
  283. MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
  284. const Function &F, Mangler &Mang, const TargetMachine &TM) const {
  285. // If the function can be removed, produce a unique section so that
  286. // the table doesn't prevent the removal.
  287. const Comdat *C = F.getComdat();
  288. bool EmitUniqueSection = TM.getFunctionSections() || C;
  289. if (!EmitUniqueSection)
  290. return ReadOnlySection;
  291. return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
  292. Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
  293. &NextUniqueID);
  294. }
  295. bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
  296. bool UsesLabelDifference, const Function &F) const {
  297. // We can always create relative relocations, so use another section
  298. // that can be marked non-executable.
  299. return false;
  300. }
  301. /// Given a mergeable constant with the specified size and relocation
  302. /// information, return a section that it should be placed in.
  303. MCSection *
  304. TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
  305. const Constant *C) const {
  306. if (Kind.isMergeableConst4() && MergeableConst4Section)
  307. return MergeableConst4Section;
  308. if (Kind.isMergeableConst8() && MergeableConst8Section)
  309. return MergeableConst8Section;
  310. if (Kind.isMergeableConst16() && MergeableConst16Section)
  311. return MergeableConst16Section;
  312. if (Kind.isReadOnly())
  313. return ReadOnlySection;
  314. if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
  315. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  316. return DataRelROSection;
  317. }
  318. static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
  319. bool IsCtor, unsigned Priority,
  320. const MCSymbol *KeySym) {
  321. std::string Name;
  322. unsigned Type;
  323. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  324. StringRef COMDAT = KeySym ? KeySym->getName() : "";
  325. if (KeySym)
  326. Flags |= ELF::SHF_GROUP;
  327. if (UseInitArray) {
  328. if (IsCtor) {
  329. Type = ELF::SHT_INIT_ARRAY;
  330. Name = ".init_array";
  331. } else {
  332. Type = ELF::SHT_FINI_ARRAY;
  333. Name = ".fini_array";
  334. }
  335. if (Priority != 65535) {
  336. Name += '.';
  337. Name += utostr(Priority);
  338. }
  339. } else {
  340. // The default scheme is .ctor / .dtor, so we have to invert the priority
  341. // numbering.
  342. if (IsCtor)
  343. Name = ".ctors";
  344. else
  345. Name = ".dtors";
  346. if (Priority != 65535) {
  347. Name += '.';
  348. Name += utostr(65535 - Priority);
  349. }
  350. Type = ELF::SHT_PROGBITS;
  351. }
  352. return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
  353. }
  354. MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  355. unsigned Priority, const MCSymbol *KeySym) const {
  356. return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
  357. KeySym);
  358. }
  359. MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  360. unsigned Priority, const MCSymbol *KeySym) const {
  361. return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
  362. KeySym);
  363. }
  364. void
  365. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  366. UseInitArray = UseInitArray_;
  367. if (!UseInitArray)
  368. return;
  369. StaticCtorSection = getContext().getELFSection(
  370. ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
  371. StaticDtorSection = getContext().getELFSection(
  372. ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
  373. }
  374. //===----------------------------------------------------------------------===//
  375. // MachO
  376. //===----------------------------------------------------------------------===//
  377. TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
  378. : TargetLoweringObjectFile() {
  379. SupportIndirectSymViaGOTPCRel = true;
  380. }
  381. /// emitModuleFlags - Perform code emission for module flags.
  382. void TargetLoweringObjectFileMachO::
  383. emitModuleFlags(MCStreamer &Streamer,
  384. ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  385. Mangler &Mang, const TargetMachine &TM) const {
  386. unsigned VersionVal = 0;
  387. unsigned ImageInfoFlags = 0;
  388. MDNode *LinkerOptions = nullptr;
  389. StringRef SectionVal;
  390. for (ArrayRef<Module::ModuleFlagEntry>::iterator
  391. i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
  392. const Module::ModuleFlagEntry &MFE = *i;
  393. // Ignore flags with 'Require' behavior.
  394. if (MFE.Behavior == Module::Require)
  395. continue;
  396. StringRef Key = MFE.Key->getString();
  397. Metadata *Val = MFE.Val;
  398. if (Key == "Objective-C Image Info Version") {
  399. VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
  400. } else if (Key == "Objective-C Garbage Collection" ||
  401. Key == "Objective-C GC Only" ||
  402. Key == "Objective-C Is Simulated" ||
  403. Key == "Objective-C Image Swift Version") {
  404. ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
  405. } else if (Key == "Objective-C Image Info Section") {
  406. SectionVal = cast<MDString>(Val)->getString();
  407. } else if (Key == "Linker Options") {
  408. LinkerOptions = cast<MDNode>(Val);
  409. }
  410. }
  411. // Emit the linker options if present.
  412. if (LinkerOptions) {
  413. for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
  414. MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
  415. SmallVector<std::string, 4> StrOptions;
  416. // Convert to strings.
  417. for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
  418. MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
  419. StrOptions.push_back(MDOption->getString());
  420. }
  421. Streamer.EmitLinkerOptions(StrOptions);
  422. }
  423. }
  424. // The section is mandatory. If we don't have it, then we don't have GC info.
  425. if (SectionVal.empty()) return;
  426. StringRef Segment, Section;
  427. unsigned TAA = 0, StubSize = 0;
  428. bool TAAParsed;
  429. std::string ErrorCode =
  430. MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
  431. TAA, TAAParsed, StubSize);
  432. if (!ErrorCode.empty())
  433. // If invalid, report the error with report_fatal_error.
  434. report_fatal_error("Invalid section specifier '" + Section + "': " +
  435. ErrorCode + ".");
  436. // Get the section.
  437. MCSectionMachO *S = getContext().getMachOSection(
  438. Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
  439. Streamer.SwitchSection(S);
  440. Streamer.EmitLabel(getContext().
  441. getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  442. Streamer.EmitIntValue(VersionVal, 4);
  443. Streamer.EmitIntValue(ImageInfoFlags, 4);
  444. Streamer.AddBlankLine();
  445. }
  446. static void checkMachOComdat(const GlobalValue *GV) {
  447. const Comdat *C = GV->getComdat();
  448. if (!C)
  449. return;
  450. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  451. "' cannot be lowered.");
  452. }
  453. MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  454. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  455. const TargetMachine &TM) const {
  456. // Parse the section specifier and create it if valid.
  457. StringRef Segment, Section;
  458. unsigned TAA = 0, StubSize = 0;
  459. bool TAAParsed;
  460. checkMachOComdat(GV);
  461. std::string ErrorCode =
  462. MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
  463. TAA, TAAParsed, StubSize);
  464. if (!ErrorCode.empty()) {
  465. // If invalid, report the error with report_fatal_error.
  466. report_fatal_error("Global variable '" + GV->getName() +
  467. "' has an invalid section specifier '" +
  468. GV->getSection() + "': " + ErrorCode + ".");
  469. }
  470. // Get the section.
  471. MCSectionMachO *S =
  472. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  473. // If TAA wasn't set by ParseSectionSpecifier() above,
  474. // use the value returned by getMachOSection() as a default.
  475. if (!TAAParsed)
  476. TAA = S->getTypeAndAttributes();
  477. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  478. // If the user declared multiple globals with different section flags, we need
  479. // to reject it here.
  480. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  481. // If invalid, report the error with report_fatal_error.
  482. report_fatal_error("Global variable '" + GV->getName() +
  483. "' section type or attributes does not match previous"
  484. " section specifier");
  485. }
  486. return S;
  487. }
  488. MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
  489. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  490. const TargetMachine &TM) const {
  491. checkMachOComdat(GV);
  492. // Handle thread local data.
  493. if (Kind.isThreadBSS()) return TLSBSSSection;
  494. if (Kind.isThreadData()) return TLSDataSection;
  495. if (Kind.isText())
  496. return GV->isWeakForLinker() ? TextCoalSection : TextSection;
  497. // If this is weak/linkonce, put this in a coalescable section, either in text
  498. // or data depending on if it is writable.
  499. if (GV->isWeakForLinker()) {
  500. if (Kind.isReadOnly())
  501. return ConstTextCoalSection;
  502. return DataCoalSection;
  503. }
  504. // FIXME: Alignment check should be handled by section classifier.
  505. if (Kind.isMergeable1ByteCString() &&
  506. TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
  507. return CStringSection;
  508. // Do not put 16-bit arrays in the UString section if they have an
  509. // externally visible label, this runs into issues with certain linker
  510. // versions.
  511. if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
  512. TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
  513. return UStringSection;
  514. // With MachO only variables whose corresponding symbol starts with 'l' or
  515. // 'L' can be merged, so we only try merging GVs with private linkage.
  516. if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
  517. if (Kind.isMergeableConst4())
  518. return FourByteConstantSection;
  519. if (Kind.isMergeableConst8())
  520. return EightByteConstantSection;
  521. if (Kind.isMergeableConst16())
  522. return SixteenByteConstantSection;
  523. }
  524. // Otherwise, if it is readonly, but not something we can specially optimize,
  525. // just drop it in .const.
  526. if (Kind.isReadOnly())
  527. return ReadOnlySection;
  528. // If this is marked const, put it into a const section. But if the dynamic
  529. // linker needs to write to it, put it in the data segment.
  530. if (Kind.isReadOnlyWithRel())
  531. return ConstDataSection;
  532. // Put zero initialized globals with strong external linkage in the
  533. // DATA, __common section with the .zerofill directive.
  534. if (Kind.isBSSExtern())
  535. return DataCommonSection;
  536. // Put zero initialized globals with local linkage in __DATA,__bss directive
  537. // with the .zerofill directive (aka .lcomm).
  538. if (Kind.isBSSLocal())
  539. return DataBSSSection;
  540. // Otherwise, just drop the variable in the normal data section.
  541. return DataSection;
  542. }
  543. MCSection *
  544. TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
  545. const Constant *C) const {
  546. // If this constant requires a relocation, we have to put it in the data
  547. // segment, not in the text segment.
  548. if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
  549. return ConstDataSection;
  550. if (Kind.isMergeableConst4())
  551. return FourByteConstantSection;
  552. if (Kind.isMergeableConst8())
  553. return EightByteConstantSection;
  554. if (Kind.isMergeableConst16())
  555. return SixteenByteConstantSection;
  556. return ReadOnlySection; // .const
  557. }
  558. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  559. const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
  560. const TargetMachine &TM, MachineModuleInfo *MMI,
  561. MCStreamer &Streamer) const {
  562. // The mach-o version of this method defaults to returning a stub reference.
  563. if (Encoding & DW_EH_PE_indirect) {
  564. MachineModuleInfoMachO &MachOMMI =
  565. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  566. MCSymbol *SSym =
  567. getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
  568. // Add information about the stub reference to MachOMMI so that the stub
  569. // gets emitted by the asmprinter.
  570. MachineModuleInfoImpl::StubValueTy &StubSym =
  571. GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
  572. MachOMMI.getGVStubEntry(SSym);
  573. if (!StubSym.getPointer()) {
  574. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  575. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  576. }
  577. return TargetLoweringObjectFile::
  578. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  579. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  580. }
  581. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
  582. TM, MMI, Streamer);
  583. }
  584. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  585. const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
  586. MachineModuleInfo *MMI) const {
  587. // The mach-o version of this method defaults to returning a stub reference.
  588. MachineModuleInfoMachO &MachOMMI =
  589. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  590. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
  591. // Add information about the stub reference to MachOMMI so that the stub
  592. // gets emitted by the asmprinter.
  593. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  594. if (!StubSym.getPointer()) {
  595. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  596. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  597. }
  598. return SSym;
  599. }
  600. const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
  601. const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
  602. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  603. // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
  604. // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
  605. // through a non_lazy_ptr stub instead. One advantage is that it allows the
  606. // computation of deltas to final external symbols. Example:
  607. //
  608. // _extgotequiv:
  609. // .long _extfoo
  610. //
  611. // _delta:
  612. // .long _extgotequiv-_delta
  613. //
  614. // is transformed to:
  615. //
  616. // _delta:
  617. // .long L_extfoo$non_lazy_ptr-(_delta+0)
  618. //
  619. // .section __IMPORT,__pointers,non_lazy_symbol_pointers
  620. // L_extfoo$non_lazy_ptr:
  621. // .indirect_symbol _extfoo
  622. // .long 0
  623. //
  624. MachineModuleInfoMachO &MachOMMI =
  625. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  626. MCContext &Ctx = getContext();
  627. // The offset must consider the original displacement from the base symbol
  628. // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
  629. Offset = -MV.getConstant();
  630. const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
  631. // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
  632. // non_lazy_ptr stubs.
  633. SmallString<128> Name;
  634. StringRef Suffix = "$non_lazy_ptr";
  635. Name += DL->getPrivateGlobalPrefix();
  636. Name += Sym->getName();
  637. Name += Suffix;
  638. MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
  639. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
  640. if (!StubSym.getPointer())
  641. StubSym = MachineModuleInfoImpl::
  642. StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
  643. const MCExpr *BSymExpr =
  644. MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
  645. const MCExpr *LHS =
  646. MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
  647. if (!Offset)
  648. return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
  649. const MCExpr *RHS =
  650. MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
  651. return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  652. }
  653. //===----------------------------------------------------------------------===//
  654. // COFF
  655. //===----------------------------------------------------------------------===//
  656. static unsigned
  657. getCOFFSectionFlags(SectionKind K) {
  658. unsigned Flags = 0;
  659. if (K.isMetadata())
  660. Flags |=
  661. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  662. else if (K.isText())
  663. Flags |=
  664. COFF::IMAGE_SCN_MEM_EXECUTE |
  665. COFF::IMAGE_SCN_MEM_READ |
  666. COFF::IMAGE_SCN_CNT_CODE;
  667. else if (K.isBSS())
  668. Flags |=
  669. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  670. COFF::IMAGE_SCN_MEM_READ |
  671. COFF::IMAGE_SCN_MEM_WRITE;
  672. else if (K.isThreadLocal())
  673. Flags |=
  674. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  675. COFF::IMAGE_SCN_MEM_READ |
  676. COFF::IMAGE_SCN_MEM_WRITE;
  677. else if (K.isReadOnly() || K.isReadOnlyWithRel())
  678. Flags |=
  679. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  680. COFF::IMAGE_SCN_MEM_READ;
  681. else if (K.isWriteable())
  682. Flags |=
  683. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  684. COFF::IMAGE_SCN_MEM_READ |
  685. COFF::IMAGE_SCN_MEM_WRITE;
  686. return Flags;
  687. }
  688. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  689. const Comdat *C = GV->getComdat();
  690. assert(C && "expected GV to have a Comdat!");
  691. StringRef ComdatGVName = C->getName();
  692. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  693. if (!ComdatGV)
  694. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  695. "' does not exist.");
  696. if (ComdatGV->getComdat() != C)
  697. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  698. "' is not a key for its COMDAT.");
  699. return ComdatGV;
  700. }
  701. static int getSelectionForCOFF(const GlobalValue *GV) {
  702. if (const Comdat *C = GV->getComdat()) {
  703. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  704. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  705. ComdatKey = GA->getBaseObject();
  706. if (ComdatKey == GV) {
  707. switch (C->getSelectionKind()) {
  708. case Comdat::Any:
  709. return COFF::IMAGE_COMDAT_SELECT_ANY;
  710. case Comdat::ExactMatch:
  711. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  712. case Comdat::Largest:
  713. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  714. case Comdat::NoDuplicates:
  715. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  716. case Comdat::SameSize:
  717. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  718. }
  719. } else {
  720. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  721. }
  722. }
  723. return 0;
  724. }
  725. MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  726. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  727. const TargetMachine &TM) const {
  728. int Selection = 0;
  729. unsigned Characteristics = getCOFFSectionFlags(Kind);
  730. StringRef Name = GV->getSection();
  731. StringRef COMDATSymName = "";
  732. if (GV->hasComdat()) {
  733. Selection = getSelectionForCOFF(GV);
  734. const GlobalValue *ComdatGV;
  735. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  736. ComdatGV = getComdatGVForCOFF(GV);
  737. else
  738. ComdatGV = GV;
  739. if (!ComdatGV->hasPrivateLinkage()) {
  740. MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
  741. COMDATSymName = Sym->getName();
  742. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  743. } else {
  744. Selection = 0;
  745. }
  746. }
  747. return getContext().getCOFFSection(Name,
  748. Characteristics,
  749. Kind,
  750. COMDATSymName,
  751. Selection);
  752. }
  753. static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  754. if (Kind.isText())
  755. return ".text";
  756. if (Kind.isBSS())
  757. return ".bss";
  758. if (Kind.isThreadLocal())
  759. return ".tls$";
  760. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  761. return ".rdata";
  762. return ".data";
  763. }
  764. MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
  765. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  766. const TargetMachine &TM) const {
  767. // If we have -ffunction-sections then we should emit the global value to a
  768. // uniqued section specifically for it.
  769. bool EmitUniquedSection;
  770. if (Kind.isText())
  771. EmitUniquedSection = TM.getFunctionSections();
  772. else
  773. EmitUniquedSection = TM.getDataSections();
  774. if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
  775. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  776. unsigned Characteristics = getCOFFSectionFlags(Kind);
  777. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  778. int Selection = getSelectionForCOFF(GV);
  779. if (!Selection)
  780. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  781. const GlobalValue *ComdatGV;
  782. if (GV->hasComdat())
  783. ComdatGV = getComdatGVForCOFF(GV);
  784. else
  785. ComdatGV = GV;
  786. if (!ComdatGV->hasPrivateLinkage()) {
  787. MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
  788. StringRef COMDATSymName = Sym->getName();
  789. return getContext().getCOFFSection(Name, Characteristics, Kind,
  790. COMDATSymName, Selection);
  791. } else {
  792. SmallString<256> TmpData;
  793. getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
  794. return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
  795. Selection);
  796. }
  797. }
  798. if (Kind.isText())
  799. return TextSection;
  800. if (Kind.isThreadLocal())
  801. return TLSDataSection;
  802. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  803. return ReadOnlySection;
  804. // Note: we claim that common symbols are put in BSSSection, but they are
  805. // really emitted with the magic .comm directive, which creates a symbol table
  806. // entry but not a section.
  807. if (Kind.isBSS() || Kind.isCommon())
  808. return BSSSection;
  809. return DataSection;
  810. }
  811. void TargetLoweringObjectFileCOFF::getNameWithPrefix(
  812. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  813. bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
  814. if (GV->hasPrivateLinkage() &&
  815. ((isa<Function>(GV) && TM.getFunctionSections()) ||
  816. (isa<GlobalVariable>(GV) && TM.getDataSections())))
  817. CannotUsePrivateLabel = true;
  818. Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  819. }
  820. MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
  821. const Function &F, Mangler &Mang, const TargetMachine &TM) const {
  822. // If the function can be removed, produce a unique section so that
  823. // the table doesn't prevent the removal.
  824. const Comdat *C = F.getComdat();
  825. bool EmitUniqueSection = TM.getFunctionSections() || C;
  826. if (!EmitUniqueSection)
  827. return ReadOnlySection;
  828. // FIXME: we should produce a symbol for F instead.
  829. if (F.hasPrivateLinkage())
  830. return ReadOnlySection;
  831. MCSymbol *Sym = TM.getSymbol(&F, Mang);
  832. StringRef COMDATSymName = Sym->getName();
  833. SectionKind Kind = SectionKind::getReadOnly();
  834. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  835. unsigned Characteristics = getCOFFSectionFlags(Kind);
  836. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  837. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  838. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
  839. }
  840. void TargetLoweringObjectFileCOFF::
  841. emitModuleFlags(MCStreamer &Streamer,
  842. ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  843. Mangler &Mang, const TargetMachine &TM) const {
  844. MDNode *LinkerOptions = nullptr;
  845. // Look for the "Linker Options" flag, since it's the only one we support.
  846. for (ArrayRef<Module::ModuleFlagEntry>::iterator
  847. i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
  848. const Module::ModuleFlagEntry &MFE = *i;
  849. StringRef Key = MFE.Key->getString();
  850. Metadata *Val = MFE.Val;
  851. if (Key == "Linker Options") {
  852. LinkerOptions = cast<MDNode>(Val);
  853. break;
  854. }
  855. }
  856. if (!LinkerOptions)
  857. return;
  858. // Emit the linker options to the linker .drectve section. According to the
  859. // spec, this section is a space-separated string containing flags for linker.
  860. MCSection *Sec = getDrectveSection();
  861. Streamer.SwitchSection(Sec);
  862. for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
  863. MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
  864. for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
  865. MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
  866. // Lead with a space for consistency with our dllexport implementation.
  867. std::string Directive(" ");
  868. Directive.append(MDOption->getString());
  869. Streamer.EmitBytes(Directive);
  870. }
  871. }
  872. }
  873. MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  874. unsigned Priority, const MCSymbol *KeySym) const {
  875. return getContext().getAssociativeCOFFSection(
  876. cast<MCSectionCOFF>(StaticCtorSection), KeySym);
  877. }
  878. MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  879. unsigned Priority, const MCSymbol *KeySym) const {
  880. return getContext().getAssociativeCOFFSection(
  881. cast<MCSectionCOFF>(StaticDtorSection), KeySym);
  882. }
  883. void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
  884. raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
  885. if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
  886. return;
  887. const Triple &TT = getTargetTriple();
  888. if (TT.isKnownWindowsMSVCEnvironment())
  889. OS << " /EXPORT:";
  890. else
  891. OS << " -export:";
  892. if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
  893. std::string Flag;
  894. raw_string_ostream FlagOS(Flag);
  895. Mang.getNameWithPrefix(FlagOS, GV, false);
  896. FlagOS.flush();
  897. if (Flag[0] == DL->getGlobalPrefix())
  898. OS << Flag.substr(1);
  899. else
  900. OS << Flag;
  901. } else {
  902. Mang.getNameWithPrefix(OS, GV, false);
  903. }
  904. if (!GV->getValueType()->isFunctionTy()) {
  905. if (TT.isKnownWindowsMSVCEnvironment())
  906. OS << ",DATA";
  907. else
  908. OS << ",data";
  909. }
  910. }