TargetLoweringObjectFileImpl.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  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/ADT/SmallString.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/CodeGen/MachineModuleInfo.h"
  20. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  21. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  22. #include "llvm/IR/Comdat.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/DerivedTypes.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/GlobalAlias.h"
  28. #include "llvm/IR/GlobalObject.h"
  29. #include "llvm/IR/GlobalValue.h"
  30. #include "llvm/IR/GlobalVariable.h"
  31. #include "llvm/IR/Mangler.h"
  32. #include "llvm/IR/Metadata.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/Type.h"
  35. #include "llvm/MC/MCAsmInfo.h"
  36. #include "llvm/MC/MCContext.h"
  37. #include "llvm/MC/MCExpr.h"
  38. #include "llvm/MC/MCSectionCOFF.h"
  39. #include "llvm/MC/MCSectionELF.h"
  40. #include "llvm/MC/MCSectionMachO.h"
  41. #include "llvm/MC/MCSectionWasm.h"
  42. #include "llvm/MC/MCStreamer.h"
  43. #include "llvm/MC/MCSymbol.h"
  44. #include "llvm/MC/MCSymbolELF.h"
  45. #include "llvm/MC/MCValue.h"
  46. #include "llvm/MC/SectionKind.h"
  47. #include "llvm/ProfileData/InstrProf.h"
  48. #include "llvm/Support/Casting.h"
  49. #include "llvm/Support/CodeGen.h"
  50. #include "llvm/Support/COFF.h"
  51. #include "llvm/Support/Dwarf.h"
  52. #include "llvm/Support/ELF.h"
  53. #include "llvm/Support/ErrorHandling.h"
  54. #include "llvm/Support/MachO.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include "llvm/Target/TargetMachine.h"
  57. #include <cassert>
  58. #include <string>
  59. using namespace llvm;
  60. using namespace dwarf;
  61. //===----------------------------------------------------------------------===//
  62. // ELF
  63. //===----------------------------------------------------------------------===//
  64. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  65. const GlobalValue *GV, const TargetMachine &TM,
  66. MachineModuleInfo *MMI) const {
  67. unsigned Encoding = getPersonalityEncoding();
  68. if ((Encoding & 0x80) == DW_EH_PE_indirect)
  69. return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
  70. TM.getSymbol(GV)->getName());
  71. if ((Encoding & 0x70) == DW_EH_PE_absptr)
  72. return TM.getSymbol(GV);
  73. report_fatal_error("We do not support this DWARF encoding yet!");
  74. }
  75. void TargetLoweringObjectFileELF::emitPersonalityValue(
  76. MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
  77. SmallString<64> NameData("DW.ref.");
  78. NameData += Sym->getName();
  79. MCSymbolELF *Label =
  80. cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
  81. Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
  82. Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
  83. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  84. MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
  85. ELF::SHT_PROGBITS, Flags, 0);
  86. unsigned Size = DL.getPointerSize();
  87. Streamer.SwitchSection(Sec);
  88. Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
  89. Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
  90. const MCExpr *E = MCConstantExpr::create(Size, getContext());
  91. Streamer.emitELFSize(Label, E);
  92. Streamer.EmitLabel(Label);
  93. Streamer.EmitSymbolValue(Sym, Size);
  94. }
  95. const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
  96. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  97. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  98. if (Encoding & DW_EH_PE_indirect) {
  99. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  100. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
  101. // Add information about the stub reference to ELFMMI so that the stub
  102. // gets emitted by the asmprinter.
  103. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  104. if (!StubSym.getPointer()) {
  105. MCSymbol *Sym = TM.getSymbol(GV);
  106. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  107. }
  108. return TargetLoweringObjectFile::
  109. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  110. Encoding & ~DW_EH_PE_indirect, Streamer);
  111. }
  112. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  113. MMI, Streamer);
  114. }
  115. static SectionKind
  116. getELFKindForNamedSection(StringRef Name, SectionKind K) {
  117. // N.B.: The defaults used in here are no the same ones used in MC.
  118. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  119. // both gas and MC will produce a section with no flags. Given
  120. // section(".eh_frame") gcc will produce:
  121. //
  122. // .section .eh_frame,"a",@progbits
  123. if (Name == getInstrProfCoverageSectionName(false))
  124. return SectionKind::getMetadata();
  125. if (Name.empty() || Name[0] != '.') return K;
  126. // Some lame default implementation based on some magic section names.
  127. if (Name == ".bss" ||
  128. Name.startswith(".bss.") ||
  129. Name.startswith(".gnu.linkonce.b.") ||
  130. Name.startswith(".llvm.linkonce.b.") ||
  131. Name == ".sbss" ||
  132. Name.startswith(".sbss.") ||
  133. Name.startswith(".gnu.linkonce.sb.") ||
  134. Name.startswith(".llvm.linkonce.sb."))
  135. return SectionKind::getBSS();
  136. if (Name == ".tdata" ||
  137. Name.startswith(".tdata.") ||
  138. Name.startswith(".gnu.linkonce.td.") ||
  139. Name.startswith(".llvm.linkonce.td."))
  140. return SectionKind::getThreadData();
  141. if (Name == ".tbss" ||
  142. Name.startswith(".tbss.") ||
  143. Name.startswith(".gnu.linkonce.tb.") ||
  144. Name.startswith(".llvm.linkonce.tb."))
  145. return SectionKind::getThreadBSS();
  146. return K;
  147. }
  148. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  149. // Use SHT_NOTE for section whose name starts with ".note" to allow
  150. // emitting ELF notes from C variable declaration.
  151. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
  152. if (Name.startswith(".note"))
  153. return ELF::SHT_NOTE;
  154. if (Name == ".init_array")
  155. return ELF::SHT_INIT_ARRAY;
  156. if (Name == ".fini_array")
  157. return ELF::SHT_FINI_ARRAY;
  158. if (Name == ".preinit_array")
  159. return ELF::SHT_PREINIT_ARRAY;
  160. if (K.isBSS() || K.isThreadBSS())
  161. return ELF::SHT_NOBITS;
  162. return ELF::SHT_PROGBITS;
  163. }
  164. static unsigned getELFSectionFlags(SectionKind K) {
  165. unsigned Flags = 0;
  166. if (!K.isMetadata())
  167. Flags |= ELF::SHF_ALLOC;
  168. if (K.isText())
  169. Flags |= ELF::SHF_EXECINSTR;
  170. if (K.isExecuteOnly())
  171. Flags |= ELF::SHF_ARM_PURECODE;
  172. if (K.isWriteable())
  173. Flags |= ELF::SHF_WRITE;
  174. if (K.isThreadLocal())
  175. Flags |= ELF::SHF_TLS;
  176. if (K.isMergeableCString() || K.isMergeableConst())
  177. Flags |= ELF::SHF_MERGE;
  178. if (K.isMergeableCString())
  179. Flags |= ELF::SHF_STRINGS;
  180. return Flags;
  181. }
  182. static const Comdat *getELFComdat(const GlobalValue *GV) {
  183. const Comdat *C = GV->getComdat();
  184. if (!C)
  185. return nullptr;
  186. if (C->getSelectionKind() != Comdat::Any)
  187. report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
  188. C->getName() + "' cannot be lowered.");
  189. return C;
  190. }
  191. MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  192. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  193. StringRef SectionName = GO->getSection();
  194. // Infer section flags from the section name if we can.
  195. Kind = getELFKindForNamedSection(SectionName, Kind);
  196. StringRef Group = "";
  197. unsigned Flags = getELFSectionFlags(Kind);
  198. if (const Comdat *C = getELFComdat(GO)) {
  199. Group = C->getName();
  200. Flags |= ELF::SHF_GROUP;
  201. }
  202. return getContext().getELFSection(SectionName,
  203. getELFSectionType(SectionName, Kind), Flags,
  204. /*EntrySize=*/0, Group);
  205. }
  206. /// Return the section prefix name used by options FunctionsSections and
  207. /// DataSections.
  208. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  209. if (Kind.isText())
  210. return ".text";
  211. if (Kind.isReadOnly())
  212. return ".rodata";
  213. if (Kind.isBSS())
  214. return ".bss";
  215. if (Kind.isThreadData())
  216. return ".tdata";
  217. if (Kind.isThreadBSS())
  218. return ".tbss";
  219. if (Kind.isData())
  220. return ".data";
  221. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  222. return ".data.rel.ro";
  223. }
  224. static MCSectionELF *
  225. selectELFSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
  226. SectionKind Kind, Mangler &Mang,
  227. const TargetMachine &TM, bool EmitUniqueSection,
  228. unsigned Flags, unsigned *NextUniqueID) {
  229. unsigned EntrySize = 0;
  230. if (Kind.isMergeableCString()) {
  231. if (Kind.isMergeable2ByteCString()) {
  232. EntrySize = 2;
  233. } else if (Kind.isMergeable4ByteCString()) {
  234. EntrySize = 4;
  235. } else {
  236. EntrySize = 1;
  237. assert(Kind.isMergeable1ByteCString() && "unknown string width");
  238. }
  239. } else if (Kind.isMergeableConst()) {
  240. if (Kind.isMergeableConst4()) {
  241. EntrySize = 4;
  242. } else if (Kind.isMergeableConst8()) {
  243. EntrySize = 8;
  244. } else if (Kind.isMergeableConst16()) {
  245. EntrySize = 16;
  246. } else {
  247. assert(Kind.isMergeableConst32() && "unknown data width");
  248. EntrySize = 32;
  249. }
  250. }
  251. StringRef Group = "";
  252. if (const Comdat *C = getELFComdat(GO)) {
  253. Flags |= ELF::SHF_GROUP;
  254. Group = C->getName();
  255. }
  256. bool UniqueSectionNames = TM.getUniqueSectionNames();
  257. SmallString<128> Name;
  258. if (Kind.isMergeableCString()) {
  259. // We also need alignment here.
  260. // FIXME: this is getting the alignment of the character, not the
  261. // alignment of the global!
  262. unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
  263. cast<GlobalVariable>(GO));
  264. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  265. Name = SizeSpec + utostr(Align);
  266. } else if (Kind.isMergeableConst()) {
  267. Name = ".rodata.cst";
  268. Name += utostr(EntrySize);
  269. } else {
  270. Name = getSectionPrefixForGlobal(Kind);
  271. }
  272. if (const auto *F = dyn_cast<Function>(GO)) {
  273. const auto &OptionalPrefix = F->getSectionPrefix();
  274. if (OptionalPrefix)
  275. Name += *OptionalPrefix;
  276. }
  277. if (EmitUniqueSection && UniqueSectionNames) {
  278. Name.push_back('.');
  279. TM.getNameWithPrefix(Name, GO, Mang, true);
  280. }
  281. unsigned UniqueID = MCContext::GenericSectionID;
  282. if (EmitUniqueSection && !UniqueSectionNames) {
  283. UniqueID = *NextUniqueID;
  284. (*NextUniqueID)++;
  285. }
  286. // Use 0 as the unique ID for execute-only text
  287. if (Kind.isExecuteOnly())
  288. UniqueID = 0;
  289. return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
  290. EntrySize, Group, UniqueID);
  291. }
  292. MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
  293. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  294. unsigned Flags = getELFSectionFlags(Kind);
  295. // If we have -ffunction-section or -fdata-section then we should emit the
  296. // global value to a uniqued section specifically for it.
  297. bool EmitUniqueSection = false;
  298. if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
  299. if (Kind.isText())
  300. EmitUniqueSection = TM.getFunctionSections();
  301. else
  302. EmitUniqueSection = TM.getDataSections();
  303. }
  304. EmitUniqueSection |= GO->hasComdat();
  305. return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
  306. EmitUniqueSection, Flags, &NextUniqueID);
  307. }
  308. MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
  309. const Function &F, const TargetMachine &TM) const {
  310. // If the function can be removed, produce a unique section so that
  311. // the table doesn't prevent the removal.
  312. const Comdat *C = F.getComdat();
  313. bool EmitUniqueSection = TM.getFunctionSections() || C;
  314. if (!EmitUniqueSection)
  315. return ReadOnlySection;
  316. return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
  317. getMangler(), TM, EmitUniqueSection, ELF::SHF_ALLOC,
  318. &NextUniqueID);
  319. }
  320. bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
  321. bool UsesLabelDifference, const Function &F) const {
  322. // We can always create relative relocations, so use another section
  323. // that can be marked non-executable.
  324. return false;
  325. }
  326. /// Given a mergeable constant with the specified size and relocation
  327. /// information, return a section that it should be placed in.
  328. MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
  329. const DataLayout &DL, SectionKind Kind, const Constant *C,
  330. unsigned &Align) const {
  331. if (Kind.isMergeableConst4() && MergeableConst4Section)
  332. return MergeableConst4Section;
  333. if (Kind.isMergeableConst8() && MergeableConst8Section)
  334. return MergeableConst8Section;
  335. if (Kind.isMergeableConst16() && MergeableConst16Section)
  336. return MergeableConst16Section;
  337. if (Kind.isMergeableConst32() && MergeableConst32Section)
  338. return MergeableConst32Section;
  339. if (Kind.isReadOnly())
  340. return ReadOnlySection;
  341. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  342. return DataRelROSection;
  343. }
  344. static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
  345. bool IsCtor, unsigned Priority,
  346. const MCSymbol *KeySym) {
  347. std::string Name;
  348. unsigned Type;
  349. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  350. StringRef COMDAT = KeySym ? KeySym->getName() : "";
  351. if (KeySym)
  352. Flags |= ELF::SHF_GROUP;
  353. if (UseInitArray) {
  354. if (IsCtor) {
  355. Type = ELF::SHT_INIT_ARRAY;
  356. Name = ".init_array";
  357. } else {
  358. Type = ELF::SHT_FINI_ARRAY;
  359. Name = ".fini_array";
  360. }
  361. if (Priority != 65535) {
  362. Name += '.';
  363. Name += utostr(Priority);
  364. }
  365. } else {
  366. // The default scheme is .ctor / .dtor, so we have to invert the priority
  367. // numbering.
  368. if (IsCtor)
  369. Name = ".ctors";
  370. else
  371. Name = ".dtors";
  372. if (Priority != 65535) {
  373. Name += '.';
  374. Name += utostr(65535 - Priority);
  375. }
  376. Type = ELF::SHT_PROGBITS;
  377. }
  378. return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
  379. }
  380. MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  381. unsigned Priority, const MCSymbol *KeySym) const {
  382. return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
  383. KeySym);
  384. }
  385. MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  386. unsigned Priority, const MCSymbol *KeySym) const {
  387. return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
  388. KeySym);
  389. }
  390. const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
  391. const GlobalValue *LHS, const GlobalValue *RHS,
  392. const TargetMachine &TM) const {
  393. // We may only use a PLT-relative relocation to refer to unnamed_addr
  394. // functions.
  395. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  396. return nullptr;
  397. // Basic sanity checks.
  398. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  399. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  400. RHS->isThreadLocal())
  401. return nullptr;
  402. return MCBinaryExpr::createSub(
  403. MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
  404. getContext()),
  405. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  406. }
  407. void
  408. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  409. UseInitArray = UseInitArray_;
  410. MCContext &Ctx = getContext();
  411. if (!UseInitArray) {
  412. StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
  413. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  414. StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
  415. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  416. return;
  417. }
  418. StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  419. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  420. StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  421. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  422. }
  423. //===----------------------------------------------------------------------===//
  424. // MachO
  425. //===----------------------------------------------------------------------===//
  426. TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
  427. : TargetLoweringObjectFile() {
  428. SupportIndirectSymViaGOTPCRel = true;
  429. }
  430. void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
  431. const TargetMachine &TM) {
  432. TargetLoweringObjectFile::Initialize(Ctx, TM);
  433. if (TM.getRelocationModel() == Reloc::Static) {
  434. StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
  435. SectionKind::getData());
  436. StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
  437. SectionKind::getData());
  438. } else {
  439. StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
  440. MachO::S_MOD_INIT_FUNC_POINTERS,
  441. SectionKind::getData());
  442. StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
  443. MachO::S_MOD_TERM_FUNC_POINTERS,
  444. SectionKind::getData());
  445. }
  446. }
  447. /// emitModuleFlags - Perform code emission for module flags.
  448. void TargetLoweringObjectFileMachO::emitModuleFlags(
  449. MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  450. const TargetMachine &TM) const {
  451. unsigned VersionVal = 0;
  452. unsigned ImageInfoFlags = 0;
  453. MDNode *LinkerOptions = nullptr;
  454. StringRef SectionVal;
  455. for (const auto &MFE : ModuleFlags) {
  456. // Ignore flags with 'Require' behavior.
  457. if (MFE.Behavior == Module::Require)
  458. continue;
  459. StringRef Key = MFE.Key->getString();
  460. Metadata *Val = MFE.Val;
  461. if (Key == "Objective-C Image Info Version") {
  462. VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
  463. } else if (Key == "Objective-C Garbage Collection" ||
  464. Key == "Objective-C GC Only" ||
  465. Key == "Objective-C Is Simulated" ||
  466. Key == "Objective-C Class Properties" ||
  467. Key == "Objective-C Image Swift Version") {
  468. ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
  469. } else if (Key == "Objective-C Image Info Section") {
  470. SectionVal = cast<MDString>(Val)->getString();
  471. } else if (Key == "Linker Options") {
  472. LinkerOptions = cast<MDNode>(Val);
  473. }
  474. }
  475. // Emit the linker options if present.
  476. if (LinkerOptions) {
  477. for (const auto &Option : LinkerOptions->operands()) {
  478. SmallVector<std::string, 4> StrOptions;
  479. for (const auto &Piece : cast<MDNode>(Option)->operands())
  480. StrOptions.push_back(cast<MDString>(Piece)->getString());
  481. Streamer.EmitLinkerOptions(StrOptions);
  482. }
  483. }
  484. // The section is mandatory. If we don't have it, then we don't have GC info.
  485. if (SectionVal.empty()) return;
  486. StringRef Segment, Section;
  487. unsigned TAA = 0, StubSize = 0;
  488. bool TAAParsed;
  489. std::string ErrorCode =
  490. MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
  491. TAA, TAAParsed, StubSize);
  492. if (!ErrorCode.empty())
  493. // If invalid, report the error with report_fatal_error.
  494. report_fatal_error("Invalid section specifier '" + Section + "': " +
  495. ErrorCode + ".");
  496. // Get the section.
  497. MCSectionMachO *S = getContext().getMachOSection(
  498. Segment, Section, TAA, StubSize, SectionKind::getData());
  499. Streamer.SwitchSection(S);
  500. Streamer.EmitLabel(getContext().
  501. getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  502. Streamer.EmitIntValue(VersionVal, 4);
  503. Streamer.EmitIntValue(ImageInfoFlags, 4);
  504. Streamer.AddBlankLine();
  505. }
  506. static void checkMachOComdat(const GlobalValue *GV) {
  507. const Comdat *C = GV->getComdat();
  508. if (!C)
  509. return;
  510. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  511. "' cannot be lowered.");
  512. }
  513. MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  514. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  515. // Parse the section specifier and create it if valid.
  516. StringRef Segment, Section;
  517. unsigned TAA = 0, StubSize = 0;
  518. bool TAAParsed;
  519. checkMachOComdat(GO);
  520. std::string ErrorCode =
  521. MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
  522. TAA, TAAParsed, StubSize);
  523. if (!ErrorCode.empty()) {
  524. // If invalid, report the error with report_fatal_error.
  525. report_fatal_error("Global variable '" + GO->getName() +
  526. "' has an invalid section specifier '" +
  527. GO->getSection() + "': " + ErrorCode + ".");
  528. }
  529. // Get the section.
  530. MCSectionMachO *S =
  531. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  532. // If TAA wasn't set by ParseSectionSpecifier() above,
  533. // use the value returned by getMachOSection() as a default.
  534. if (!TAAParsed)
  535. TAA = S->getTypeAndAttributes();
  536. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  537. // If the user declared multiple globals with different section flags, we need
  538. // to reject it here.
  539. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  540. // If invalid, report the error with report_fatal_error.
  541. report_fatal_error("Global variable '" + GO->getName() +
  542. "' section type or attributes does not match previous"
  543. " section specifier");
  544. }
  545. return S;
  546. }
  547. MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
  548. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  549. checkMachOComdat(GO);
  550. // Handle thread local data.
  551. if (Kind.isThreadBSS()) return TLSBSSSection;
  552. if (Kind.isThreadData()) return TLSDataSection;
  553. if (Kind.isText())
  554. return GO->isWeakForLinker() ? TextCoalSection : TextSection;
  555. // If this is weak/linkonce, put this in a coalescable section, either in text
  556. // or data depending on if it is writable.
  557. if (GO->isWeakForLinker()) {
  558. if (Kind.isReadOnly())
  559. return ConstTextCoalSection;
  560. return DataCoalSection;
  561. }
  562. // FIXME: Alignment check should be handled by section classifier.
  563. if (Kind.isMergeable1ByteCString() &&
  564. GO->getParent()->getDataLayout().getPreferredAlignment(
  565. cast<GlobalVariable>(GO)) < 32)
  566. return CStringSection;
  567. // Do not put 16-bit arrays in the UString section if they have an
  568. // externally visible label, this runs into issues with certain linker
  569. // versions.
  570. if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
  571. GO->getParent()->getDataLayout().getPreferredAlignment(
  572. cast<GlobalVariable>(GO)) < 32)
  573. return UStringSection;
  574. // With MachO only variables whose corresponding symbol starts with 'l' or
  575. // 'L' can be merged, so we only try merging GVs with private linkage.
  576. if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
  577. if (Kind.isMergeableConst4())
  578. return FourByteConstantSection;
  579. if (Kind.isMergeableConst8())
  580. return EightByteConstantSection;
  581. if (Kind.isMergeableConst16())
  582. return SixteenByteConstantSection;
  583. }
  584. // Otherwise, if it is readonly, but not something we can specially optimize,
  585. // just drop it in .const.
  586. if (Kind.isReadOnly())
  587. return ReadOnlySection;
  588. // If this is marked const, put it into a const section. But if the dynamic
  589. // linker needs to write to it, put it in the data segment.
  590. if (Kind.isReadOnlyWithRel())
  591. return ConstDataSection;
  592. // Put zero initialized globals with strong external linkage in the
  593. // DATA, __common section with the .zerofill directive.
  594. if (Kind.isBSSExtern())
  595. return DataCommonSection;
  596. // Put zero initialized globals with local linkage in __DATA,__bss directive
  597. // with the .zerofill directive (aka .lcomm).
  598. if (Kind.isBSSLocal())
  599. return DataBSSSection;
  600. // Otherwise, just drop the variable in the normal data section.
  601. return DataSection;
  602. }
  603. MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
  604. const DataLayout &DL, SectionKind Kind, const Constant *C,
  605. unsigned &Align) const {
  606. // If this constant requires a relocation, we have to put it in the data
  607. // segment, not in the text segment.
  608. if (Kind.isData() || Kind.isReadOnlyWithRel())
  609. return ConstDataSection;
  610. if (Kind.isMergeableConst4())
  611. return FourByteConstantSection;
  612. if (Kind.isMergeableConst8())
  613. return EightByteConstantSection;
  614. if (Kind.isMergeableConst16())
  615. return SixteenByteConstantSection;
  616. return ReadOnlySection; // .const
  617. }
  618. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  619. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  620. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  621. // The mach-o version of this method defaults to returning a stub reference.
  622. if (Encoding & DW_EH_PE_indirect) {
  623. MachineModuleInfoMachO &MachOMMI =
  624. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  625. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  626. // Add information about the stub reference to MachOMMI so that the stub
  627. // gets emitted by the asmprinter.
  628. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  629. if (!StubSym.getPointer()) {
  630. MCSymbol *Sym = TM.getSymbol(GV);
  631. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  632. }
  633. return TargetLoweringObjectFile::
  634. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  635. Encoding & ~DW_EH_PE_indirect, Streamer);
  636. }
  637. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  638. MMI, Streamer);
  639. }
  640. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  641. const GlobalValue *GV, const TargetMachine &TM,
  642. MachineModuleInfo *MMI) const {
  643. // The mach-o version of this method defaults to returning a stub reference.
  644. MachineModuleInfoMachO &MachOMMI =
  645. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  646. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  647. // Add information about the stub reference to MachOMMI so that the stub
  648. // gets emitted by the asmprinter.
  649. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  650. if (!StubSym.getPointer()) {
  651. MCSymbol *Sym = TM.getSymbol(GV);
  652. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  653. }
  654. return SSym;
  655. }
  656. const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
  657. const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
  658. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  659. // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
  660. // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
  661. // through a non_lazy_ptr stub instead. One advantage is that it allows the
  662. // computation of deltas to final external symbols. Example:
  663. //
  664. // _extgotequiv:
  665. // .long _extfoo
  666. //
  667. // _delta:
  668. // .long _extgotequiv-_delta
  669. //
  670. // is transformed to:
  671. //
  672. // _delta:
  673. // .long L_extfoo$non_lazy_ptr-(_delta+0)
  674. //
  675. // .section __IMPORT,__pointers,non_lazy_symbol_pointers
  676. // L_extfoo$non_lazy_ptr:
  677. // .indirect_symbol _extfoo
  678. // .long 0
  679. //
  680. MachineModuleInfoMachO &MachOMMI =
  681. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  682. MCContext &Ctx = getContext();
  683. // The offset must consider the original displacement from the base symbol
  684. // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
  685. Offset = -MV.getConstant();
  686. const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
  687. // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
  688. // non_lazy_ptr stubs.
  689. SmallString<128> Name;
  690. StringRef Suffix = "$non_lazy_ptr";
  691. Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
  692. Name += Sym->getName();
  693. Name += Suffix;
  694. MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
  695. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
  696. if (!StubSym.getPointer())
  697. StubSym = MachineModuleInfoImpl::
  698. StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
  699. const MCExpr *BSymExpr =
  700. MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
  701. const MCExpr *LHS =
  702. MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
  703. if (!Offset)
  704. return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
  705. const MCExpr *RHS =
  706. MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
  707. return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  708. }
  709. static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
  710. const MCSection &Section) {
  711. if (!AsmInfo.isSectionAtomizableBySymbols(Section))
  712. return true;
  713. // If it is not dead stripped, it is safe to use private labels.
  714. const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
  715. if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
  716. return true;
  717. return false;
  718. }
  719. void TargetLoweringObjectFileMachO::getNameWithPrefix(
  720. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  721. const TargetMachine &TM) const {
  722. bool CannotUsePrivateLabel = true;
  723. if (auto *GO = GV->getBaseObject()) {
  724. SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
  725. const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
  726. CannotUsePrivateLabel =
  727. !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
  728. }
  729. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  730. }
  731. //===----------------------------------------------------------------------===//
  732. // COFF
  733. //===----------------------------------------------------------------------===//
  734. static unsigned
  735. getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
  736. unsigned Flags = 0;
  737. bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
  738. if (K.isMetadata())
  739. Flags |=
  740. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  741. else if (K.isText())
  742. Flags |=
  743. COFF::IMAGE_SCN_MEM_EXECUTE |
  744. COFF::IMAGE_SCN_MEM_READ |
  745. COFF::IMAGE_SCN_CNT_CODE |
  746. (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
  747. else if (K.isBSS())
  748. Flags |=
  749. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  750. COFF::IMAGE_SCN_MEM_READ |
  751. COFF::IMAGE_SCN_MEM_WRITE;
  752. else if (K.isThreadLocal())
  753. Flags |=
  754. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  755. COFF::IMAGE_SCN_MEM_READ |
  756. COFF::IMAGE_SCN_MEM_WRITE;
  757. else if (K.isReadOnly() || K.isReadOnlyWithRel())
  758. Flags |=
  759. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  760. COFF::IMAGE_SCN_MEM_READ;
  761. else if (K.isWriteable())
  762. Flags |=
  763. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  764. COFF::IMAGE_SCN_MEM_READ |
  765. COFF::IMAGE_SCN_MEM_WRITE;
  766. return Flags;
  767. }
  768. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  769. const Comdat *C = GV->getComdat();
  770. assert(C && "expected GV to have a Comdat!");
  771. StringRef ComdatGVName = C->getName();
  772. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  773. if (!ComdatGV)
  774. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  775. "' does not exist.");
  776. if (ComdatGV->getComdat() != C)
  777. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  778. "' is not a key for its COMDAT.");
  779. return ComdatGV;
  780. }
  781. static int getSelectionForCOFF(const GlobalValue *GV) {
  782. if (const Comdat *C = GV->getComdat()) {
  783. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  784. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  785. ComdatKey = GA->getBaseObject();
  786. if (ComdatKey == GV) {
  787. switch (C->getSelectionKind()) {
  788. case Comdat::Any:
  789. return COFF::IMAGE_COMDAT_SELECT_ANY;
  790. case Comdat::ExactMatch:
  791. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  792. case Comdat::Largest:
  793. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  794. case Comdat::NoDuplicates:
  795. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  796. case Comdat::SameSize:
  797. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  798. }
  799. } else {
  800. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  801. }
  802. }
  803. return 0;
  804. }
  805. void llvm::emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV,
  806. const Triple &TT, Mangler &Mangler) {
  807. if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
  808. return;
  809. if (TT.isKnownWindowsMSVCEnvironment())
  810. OS << " /EXPORT:";
  811. else
  812. OS << " -export:";
  813. if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
  814. std::string Flag;
  815. raw_string_ostream FlagOS(Flag);
  816. Mangler.getNameWithPrefix(FlagOS, GV, false);
  817. FlagOS.flush();
  818. if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
  819. OS << Flag.substr(1);
  820. else
  821. OS << Flag;
  822. } else {
  823. Mangler.getNameWithPrefix(OS, GV, false);
  824. }
  825. if (!GV->getValueType()->isFunctionTy()) {
  826. if (TT.isKnownWindowsMSVCEnvironment())
  827. OS << ",DATA";
  828. else
  829. OS << ",data";
  830. }
  831. }
  832. MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  833. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  834. int Selection = 0;
  835. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  836. StringRef Name = GO->getSection();
  837. StringRef COMDATSymName = "";
  838. if (GO->hasComdat()) {
  839. Selection = getSelectionForCOFF(GO);
  840. const GlobalValue *ComdatGV;
  841. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  842. ComdatGV = getComdatGVForCOFF(GO);
  843. else
  844. ComdatGV = GO;
  845. if (!ComdatGV->hasPrivateLinkage()) {
  846. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  847. COMDATSymName = Sym->getName();
  848. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  849. } else {
  850. Selection = 0;
  851. }
  852. }
  853. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  854. Selection);
  855. }
  856. static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  857. if (Kind.isText())
  858. return ".text";
  859. if (Kind.isBSS())
  860. return ".bss";
  861. if (Kind.isThreadLocal())
  862. return ".tls$";
  863. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  864. return ".rdata";
  865. return ".data";
  866. }
  867. MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
  868. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  869. // If we have -ffunction-sections then we should emit the global value to a
  870. // uniqued section specifically for it.
  871. bool EmitUniquedSection;
  872. if (Kind.isText())
  873. EmitUniquedSection = TM.getFunctionSections();
  874. else
  875. EmitUniquedSection = TM.getDataSections();
  876. if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
  877. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  878. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  879. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  880. int Selection = getSelectionForCOFF(GO);
  881. if (!Selection)
  882. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  883. const GlobalValue *ComdatGV;
  884. if (GO->hasComdat())
  885. ComdatGV = getComdatGVForCOFF(GO);
  886. else
  887. ComdatGV = GO;
  888. unsigned UniqueID = MCContext::GenericSectionID;
  889. if (EmitUniquedSection)
  890. UniqueID = NextUniqueID++;
  891. if (!ComdatGV->hasPrivateLinkage()) {
  892. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  893. StringRef COMDATSymName = Sym->getName();
  894. return getContext().getCOFFSection(Name, Characteristics, Kind,
  895. COMDATSymName, Selection, UniqueID);
  896. } else {
  897. SmallString<256> TmpData;
  898. getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
  899. return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
  900. Selection, UniqueID);
  901. }
  902. }
  903. if (Kind.isText())
  904. return TextSection;
  905. if (Kind.isThreadLocal())
  906. return TLSDataSection;
  907. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  908. return ReadOnlySection;
  909. // Note: we claim that common symbols are put in BSSSection, but they are
  910. // really emitted with the magic .comm directive, which creates a symbol table
  911. // entry but not a section.
  912. if (Kind.isBSS() || Kind.isCommon())
  913. return BSSSection;
  914. return DataSection;
  915. }
  916. void TargetLoweringObjectFileCOFF::getNameWithPrefix(
  917. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  918. const TargetMachine &TM) const {
  919. bool CannotUsePrivateLabel = false;
  920. if (GV->hasPrivateLinkage() &&
  921. ((isa<Function>(GV) && TM.getFunctionSections()) ||
  922. (isa<GlobalVariable>(GV) && TM.getDataSections())))
  923. CannotUsePrivateLabel = true;
  924. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  925. }
  926. MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
  927. const Function &F, const TargetMachine &TM) const {
  928. // If the function can be removed, produce a unique section so that
  929. // the table doesn't prevent the removal.
  930. const Comdat *C = F.getComdat();
  931. bool EmitUniqueSection = TM.getFunctionSections() || C;
  932. if (!EmitUniqueSection)
  933. return ReadOnlySection;
  934. // FIXME: we should produce a symbol for F instead.
  935. if (F.hasPrivateLinkage())
  936. return ReadOnlySection;
  937. MCSymbol *Sym = TM.getSymbol(&F);
  938. StringRef COMDATSymName = Sym->getName();
  939. SectionKind Kind = SectionKind::getReadOnly();
  940. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  941. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  942. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  943. unsigned UniqueID = NextUniqueID++;
  944. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  945. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
  946. }
  947. void TargetLoweringObjectFileCOFF::emitModuleFlags(
  948. MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  949. const TargetMachine &TM) const {
  950. MDNode *LinkerOptions = nullptr;
  951. for (const auto &MFE : ModuleFlags) {
  952. StringRef Key = MFE.Key->getString();
  953. if (Key == "Linker Options")
  954. LinkerOptions = cast<MDNode>(MFE.Val);
  955. }
  956. if (LinkerOptions) {
  957. // Emit the linker options to the linker .drectve section. According to the
  958. // spec, this section is a space-separated string containing flags for
  959. // linker.
  960. MCSection *Sec = getDrectveSection();
  961. Streamer.SwitchSection(Sec);
  962. for (const auto &Option : LinkerOptions->operands()) {
  963. for (const auto &Piece : cast<MDNode>(Option)->operands()) {
  964. // Lead with a space for consistency with our dllexport implementation.
  965. std::string Directive(" ");
  966. Directive.append(cast<MDString>(Piece)->getString());
  967. Streamer.EmitBytes(Directive);
  968. }
  969. }
  970. }
  971. }
  972. void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
  973. const TargetMachine &TM) {
  974. TargetLoweringObjectFile::Initialize(Ctx, TM);
  975. const Triple &T = TM.getTargetTriple();
  976. if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  977. StaticCtorSection =
  978. Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  979. COFF::IMAGE_SCN_MEM_READ,
  980. SectionKind::getReadOnly());
  981. StaticDtorSection =
  982. Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  983. COFF::IMAGE_SCN_MEM_READ,
  984. SectionKind::getReadOnly());
  985. } else {
  986. StaticCtorSection = Ctx.getCOFFSection(
  987. ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  988. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  989. SectionKind::getData());
  990. StaticDtorSection = Ctx.getCOFFSection(
  991. ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  992. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  993. SectionKind::getData());
  994. }
  995. }
  996. MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  997. unsigned Priority, const MCSymbol *KeySym) const {
  998. return getContext().getAssociativeCOFFSection(
  999. cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
  1000. }
  1001. MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  1002. unsigned Priority, const MCSymbol *KeySym) const {
  1003. return getContext().getAssociativeCOFFSection(
  1004. cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
  1005. }
  1006. void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
  1007. raw_ostream &OS, const GlobalValue *GV) const {
  1008. emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
  1009. }
  1010. //===----------------------------------------------------------------------===//
  1011. // Wasm
  1012. //===----------------------------------------------------------------------===//
  1013. static const Comdat *getWasmComdat(const GlobalValue *GV) {
  1014. const Comdat *C = GV->getComdat();
  1015. if (!C)
  1016. return nullptr;
  1017. if (C->getSelectionKind() != Comdat::Any)
  1018. report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
  1019. C->getName() + "' cannot be lowered.");
  1020. return C;
  1021. }
  1022. MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
  1023. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1024. llvm_unreachable("getExplicitSectionGlobal not yet implemented");
  1025. return nullptr;
  1026. }
  1027. static MCSectionWasm *
  1028. selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
  1029. SectionKind Kind, Mangler &Mang,
  1030. const TargetMachine &TM, bool EmitUniqueSection,
  1031. unsigned Flags, unsigned *NextUniqueID) {
  1032. StringRef Group = "";
  1033. if (getWasmComdat(GO))
  1034. llvm_unreachable("comdat not yet supported for wasm");
  1035. bool UniqueSectionNames = TM.getUniqueSectionNames();
  1036. SmallString<128> Name = getSectionPrefixForGlobal(Kind);
  1037. if (const auto *F = dyn_cast<Function>(GO)) {
  1038. const auto &OptionalPrefix = F->getSectionPrefix();
  1039. if (OptionalPrefix)
  1040. Name += *OptionalPrefix;
  1041. }
  1042. if (EmitUniqueSection && UniqueSectionNames) {
  1043. Name.push_back('.');
  1044. TM.getNameWithPrefix(Name, GO, Mang, true);
  1045. }
  1046. unsigned UniqueID = MCContext::GenericSectionID;
  1047. if (EmitUniqueSection && !UniqueSectionNames) {
  1048. UniqueID = *NextUniqueID;
  1049. (*NextUniqueID)++;
  1050. }
  1051. return Ctx.getWasmSection(Name, /*Type=*/0, Flags,
  1052. Group, UniqueID);
  1053. }
  1054. MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
  1055. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1056. if (Kind.isCommon())
  1057. report_fatal_error("mergable sections not supported yet on wasm");
  1058. // If we have -ffunction-section or -fdata-section then we should emit the
  1059. // global value to a uniqued section specifically for it.
  1060. bool EmitUniqueSection = false;
  1061. if (Kind.isText())
  1062. EmitUniqueSection = TM.getFunctionSections();
  1063. else
  1064. EmitUniqueSection = TM.getDataSections();
  1065. EmitUniqueSection |= GO->hasComdat();
  1066. return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
  1067. EmitUniqueSection, /*Flags=*/0,
  1068. &NextUniqueID);
  1069. }
  1070. bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
  1071. bool UsesLabelDifference, const Function &F) const {
  1072. // We can always create relative relocations, so use another section
  1073. // that can be marked non-executable.
  1074. return false;
  1075. }
  1076. const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
  1077. const GlobalValue *LHS, const GlobalValue *RHS,
  1078. const TargetMachine &TM) const {
  1079. // We may only use a PLT-relative relocation to refer to unnamed_addr
  1080. // functions.
  1081. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  1082. return nullptr;
  1083. // Basic sanity checks.
  1084. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1085. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  1086. RHS->isThreadLocal())
  1087. return nullptr;
  1088. return MCBinaryExpr::createSub(
  1089. MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
  1090. getContext()),
  1091. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  1092. }
  1093. void
  1094. TargetLoweringObjectFileWasm::InitializeWasm() {
  1095. // TODO: Initialize StaticCtorSection and StaticDtorSection.
  1096. }