1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/BinaryFormat/Dwarf.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/BinaryFormat/MachO.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
27 #include "llvm/IR/Comdat.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCContext.h"
42 #include "llvm/MC/MCExpr.h"
43 #include "llvm/MC/MCSectionCOFF.h"
44 #include "llvm/MC/MCSectionELF.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/MC/MCSectionWasm.h"
47 #include "llvm/MC/MCStreamer.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/MC/MCSymbolELF.h"
50 #include "llvm/MC/MCValue.h"
51 #include "llvm/MC/SectionKind.h"
52 #include "llvm/ProfileData/InstrProf.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetMachine.h"
63 using namespace dwarf;
65 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
67 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
68 M.getModuleFlagsMetadata(ModuleFlags);
70 for (const auto &MFE: ModuleFlags) {
71 // Ignore flags with 'Require' behaviour.
72 if (MFE.Behavior == Module::Require)
75 StringRef Key = MFE.Key->getString();
76 if (Key == "Objective-C Image Info Version") {
77 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
78 } else if (Key == "Objective-C Garbage Collection" ||
79 Key == "Objective-C GC Only" ||
80 Key == "Objective-C Is Simulated" ||
81 Key == "Objective-C Class Properties" ||
82 Key == "Objective-C Image Swift Version") {
83 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84 } else if (Key == "Objective-C Image Info Section") {
85 Section = cast<MDString>(MFE.Val)->getString();
90 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
94 void TargetLoweringObjectFileELF::emitModuleMetadata(
95 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
100 GetObjCImageInfo(M, Version, Flags, Section);
104 auto &C = getContext();
105 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
106 Streamer.SwitchSection(S);
107 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
108 Streamer.EmitIntValue(Version, 4);
109 Streamer.EmitIntValue(Flags, 4);
110 Streamer.AddBlankLine();
113 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
114 const GlobalValue *GV, const TargetMachine &TM,
115 MachineModuleInfo *MMI) const {
116 unsigned Encoding = getPersonalityEncoding();
117 if ((Encoding & 0x80) == DW_EH_PE_indirect)
118 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
119 TM.getSymbol(GV)->getName());
120 if ((Encoding & 0x70) == DW_EH_PE_absptr)
121 return TM.getSymbol(GV);
122 report_fatal_error("We do not support this DWARF encoding yet!");
125 void TargetLoweringObjectFileELF::emitPersonalityValue(
126 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
127 SmallString<64> NameData("DW.ref.");
128 NameData += Sym->getName();
130 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
131 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
132 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
133 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
134 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
135 ELF::SHT_PROGBITS, Flags, 0);
136 unsigned Size = DL.getPointerSize();
137 Streamer.SwitchSection(Sec);
138 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
139 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
140 const MCExpr *E = MCConstantExpr::create(Size, getContext());
141 Streamer.emitELFSize(Label, E);
142 Streamer.EmitLabel(Label);
144 Streamer.EmitSymbolValue(Sym, Size);
147 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
148 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
149 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
150 if (Encoding & DW_EH_PE_indirect) {
151 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
153 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
155 // Add information about the stub reference to ELFMMI so that the stub
156 // gets emitted by the asmprinter.
157 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
158 if (!StubSym.getPointer()) {
159 MCSymbol *Sym = TM.getSymbol(GV);
160 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
163 return TargetLoweringObjectFile::
164 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
165 Encoding & ~DW_EH_PE_indirect, Streamer);
168 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
172 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
173 // N.B.: The defaults used in here are no the same ones used in MC.
174 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
175 // both gas and MC will produce a section with no flags. Given
176 // section(".eh_frame") gcc will produce:
178 // .section .eh_frame,"a",@progbits
180 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
181 /*AddSegmentInfo=*/false))
182 return SectionKind::getMetadata();
184 if (Name.empty() || Name[0] != '.') return K;
186 // Some lame default implementation based on some magic section names.
187 if (Name == ".bss" ||
188 Name.startswith(".bss.") ||
189 Name.startswith(".gnu.linkonce.b.") ||
190 Name.startswith(".llvm.linkonce.b.") ||
192 Name.startswith(".sbss.") ||
193 Name.startswith(".gnu.linkonce.sb.") ||
194 Name.startswith(".llvm.linkonce.sb."))
195 return SectionKind::getBSS();
197 if (Name == ".tdata" ||
198 Name.startswith(".tdata.") ||
199 Name.startswith(".gnu.linkonce.td.") ||
200 Name.startswith(".llvm.linkonce.td."))
201 return SectionKind::getThreadData();
203 if (Name == ".tbss" ||
204 Name.startswith(".tbss.") ||
205 Name.startswith(".gnu.linkonce.tb.") ||
206 Name.startswith(".llvm.linkonce.tb."))
207 return SectionKind::getThreadBSS();
212 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
213 // Use SHT_NOTE for section whose name starts with ".note" to allow
214 // emitting ELF notes from C variable declaration.
215 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
216 if (Name.startswith(".note"))
217 return ELF::SHT_NOTE;
219 if (Name == ".init_array")
220 return ELF::SHT_INIT_ARRAY;
222 if (Name == ".fini_array")
223 return ELF::SHT_FINI_ARRAY;
225 if (Name == ".preinit_array")
226 return ELF::SHT_PREINIT_ARRAY;
228 if (K.isBSS() || K.isThreadBSS())
229 return ELF::SHT_NOBITS;
231 return ELF::SHT_PROGBITS;
234 static unsigned getELFSectionFlags(SectionKind K) {
238 Flags |= ELF::SHF_ALLOC;
241 Flags |= ELF::SHF_EXECINSTR;
243 if (K.isExecuteOnly())
244 Flags |= ELF::SHF_ARM_PURECODE;
247 Flags |= ELF::SHF_WRITE;
249 if (K.isThreadLocal())
250 Flags |= ELF::SHF_TLS;
252 if (K.isMergeableCString() || K.isMergeableConst())
253 Flags |= ELF::SHF_MERGE;
255 if (K.isMergeableCString())
256 Flags |= ELF::SHF_STRINGS;
261 static const Comdat *getELFComdat(const GlobalValue *GV) {
262 const Comdat *C = GV->getComdat();
266 if (C->getSelectionKind() != Comdat::Any)
267 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
268 C->getName() + "' cannot be lowered.");
273 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
274 const TargetMachine &TM) {
275 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
279 const MDOperand &Op = MD->getOperand(0);
283 auto *VM = dyn_cast<ValueAsMetadata>(Op);
285 report_fatal_error("MD_associated operand is not ValueAsMetadata");
287 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
288 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
291 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
292 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
293 StringRef SectionName = GO->getSection();
295 // Check if '#pragma clang section' name is applicable.
296 // Note that pragma directive overrides -ffunction-section, -fdata-section
297 // and so section name is exactly as user specified and not uniqued.
298 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
299 if (GV && GV->hasImplicitSection()) {
300 auto Attrs = GV->getAttributes();
301 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
302 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
303 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
304 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
305 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
306 SectionName = Attrs.getAttribute("data-section").getValueAsString();
309 const Function *F = dyn_cast<Function>(GO);
310 if (F && F->hasFnAttribute("implicit-section-name")) {
311 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
314 // Infer section flags from the section name if we can.
315 Kind = getELFKindForNamedSection(SectionName, Kind);
317 StringRef Group = "";
318 unsigned Flags = getELFSectionFlags(Kind);
319 if (const Comdat *C = getELFComdat(GO)) {
320 Group = C->getName();
321 Flags |= ELF::SHF_GROUP;
324 // A section can have at most one associated section. Put each global with
325 // MD_associated in a unique section.
326 unsigned UniqueID = MCContext::GenericSectionID;
327 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
328 if (AssociatedSymbol) {
329 UniqueID = NextUniqueID++;
330 Flags |= ELF::SHF_LINK_ORDER;
333 MCSectionELF *Section = getContext().getELFSection(
334 SectionName, getELFSectionType(SectionName, Kind), Flags,
335 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
336 // Make sure that we did not get some other section with incompatible sh_link.
337 // This should not be possible due to UniqueID code above.
338 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
342 /// Return the section prefix name used by options FunctionsSections and
344 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
347 if (Kind.isReadOnly())
351 if (Kind.isThreadData())
353 if (Kind.isThreadBSS())
357 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
358 return ".data.rel.ro";
361 static MCSectionELF *selectELFSectionForGlobal(
362 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
363 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
364 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
365 unsigned EntrySize = 0;
366 if (Kind.isMergeableCString()) {
367 if (Kind.isMergeable2ByteCString()) {
369 } else if (Kind.isMergeable4ByteCString()) {
373 assert(Kind.isMergeable1ByteCString() && "unknown string width");
375 } else if (Kind.isMergeableConst()) {
376 if (Kind.isMergeableConst4()) {
378 } else if (Kind.isMergeableConst8()) {
380 } else if (Kind.isMergeableConst16()) {
383 assert(Kind.isMergeableConst32() && "unknown data width");
388 StringRef Group = "";
389 if (const Comdat *C = getELFComdat(GO)) {
390 Flags |= ELF::SHF_GROUP;
391 Group = C->getName();
394 bool UniqueSectionNames = TM.getUniqueSectionNames();
395 SmallString<128> Name;
396 if (Kind.isMergeableCString()) {
397 // We also need alignment here.
398 // FIXME: this is getting the alignment of the character, not the
399 // alignment of the global!
400 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
401 cast<GlobalVariable>(GO));
403 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
404 Name = SizeSpec + utostr(Align);
405 } else if (Kind.isMergeableConst()) {
406 Name = ".rodata.cst";
407 Name += utostr(EntrySize);
409 Name = getSectionPrefixForGlobal(Kind);
412 if (const auto *F = dyn_cast<Function>(GO)) {
413 const auto &OptionalPrefix = F->getSectionPrefix();
415 Name += *OptionalPrefix;
418 if (EmitUniqueSection && UniqueSectionNames) {
420 TM.getNameWithPrefix(Name, GO, Mang, true);
422 unsigned UniqueID = MCContext::GenericSectionID;
423 if (EmitUniqueSection && !UniqueSectionNames) {
424 UniqueID = *NextUniqueID;
427 // Use 0 as the unique ID for execute-only text
428 if (Kind.isExecuteOnly())
430 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
431 EntrySize, Group, UniqueID, AssociatedSymbol);
434 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
435 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
436 unsigned Flags = getELFSectionFlags(Kind);
438 // If we have -ffunction-section or -fdata-section then we should emit the
439 // global value to a uniqued section specifically for it.
440 bool EmitUniqueSection = false;
441 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
443 EmitUniqueSection = TM.getFunctionSections();
445 EmitUniqueSection = TM.getDataSections();
447 EmitUniqueSection |= GO->hasComdat();
449 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
450 if (AssociatedSymbol) {
451 EmitUniqueSection = true;
452 Flags |= ELF::SHF_LINK_ORDER;
455 MCSectionELF *Section = selectELFSectionForGlobal(
456 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
457 &NextUniqueID, AssociatedSymbol);
458 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
462 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
463 const Function &F, const TargetMachine &TM) const {
464 // If the function can be removed, produce a unique section so that
465 // the table doesn't prevent the removal.
466 const Comdat *C = F.getComdat();
467 bool EmitUniqueSection = TM.getFunctionSections() || C;
468 if (!EmitUniqueSection)
469 return ReadOnlySection;
471 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
472 getMangler(), TM, EmitUniqueSection,
473 ELF::SHF_ALLOC, &NextUniqueID,
474 /* AssociatedSymbol */ nullptr);
477 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
478 bool UsesLabelDifference, const Function &F) const {
479 // We can always create relative relocations, so use another section
480 // that can be marked non-executable.
484 /// Given a mergeable constant with the specified size and relocation
485 /// information, return a section that it should be placed in.
486 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
487 const DataLayout &DL, SectionKind Kind, const Constant *C,
488 unsigned &Align) const {
489 if (Kind.isMergeableConst4() && MergeableConst4Section)
490 return MergeableConst4Section;
491 if (Kind.isMergeableConst8() && MergeableConst8Section)
492 return MergeableConst8Section;
493 if (Kind.isMergeableConst16() && MergeableConst16Section)
494 return MergeableConst16Section;
495 if (Kind.isMergeableConst32() && MergeableConst32Section)
496 return MergeableConst32Section;
497 if (Kind.isReadOnly())
498 return ReadOnlySection;
500 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
501 return DataRelROSection;
504 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
505 bool IsCtor, unsigned Priority,
506 const MCSymbol *KeySym) {
509 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
510 StringRef COMDAT = KeySym ? KeySym->getName() : "";
513 Flags |= ELF::SHF_GROUP;
517 Type = ELF::SHT_INIT_ARRAY;
518 Name = ".init_array";
520 Type = ELF::SHT_FINI_ARRAY;
521 Name = ".fini_array";
523 if (Priority != 65535) {
525 Name += utostr(Priority);
528 // The default scheme is .ctor / .dtor, so we have to invert the priority
534 if (Priority != 65535)
535 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
536 Type = ELF::SHT_PROGBITS;
539 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
542 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
543 unsigned Priority, const MCSymbol *KeySym) const {
544 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
548 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
549 unsigned Priority, const MCSymbol *KeySym) const {
550 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
554 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
555 const GlobalValue *LHS, const GlobalValue *RHS,
556 const TargetMachine &TM) const {
557 // We may only use a PLT-relative relocation to refer to unnamed_addr
559 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
562 // Basic sanity checks.
563 if (LHS->getType()->getPointerAddressSpace() != 0 ||
564 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
565 RHS->isThreadLocal())
568 return MCBinaryExpr::createSub(
569 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
571 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
575 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
576 UseInitArray = UseInitArray_;
577 MCContext &Ctx = getContext();
579 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
580 ELF::SHF_ALLOC | ELF::SHF_WRITE);
582 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
583 ELF::SHF_ALLOC | ELF::SHF_WRITE);
587 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
588 ELF::SHF_WRITE | ELF::SHF_ALLOC);
589 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
590 ELF::SHF_WRITE | ELF::SHF_ALLOC);
593 //===----------------------------------------------------------------------===//
595 //===----------------------------------------------------------------------===//
597 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
598 : TargetLoweringObjectFile() {
599 SupportIndirectSymViaGOTPCRel = true;
602 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
603 const TargetMachine &TM) {
604 TargetLoweringObjectFile::Initialize(Ctx, TM);
605 if (TM.getRelocationModel() == Reloc::Static) {
606 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
607 SectionKind::getData());
608 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
609 SectionKind::getData());
611 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
612 MachO::S_MOD_INIT_FUNC_POINTERS,
613 SectionKind::getData());
614 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
615 MachO::S_MOD_TERM_FUNC_POINTERS,
616 SectionKind::getData());
620 void TargetLoweringObjectFileMachO::emitModuleMetadata(
621 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
622 // Emit the linker options if present.
623 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
624 for (const auto &Option : LinkerOptions->operands()) {
625 SmallVector<std::string, 4> StrOptions;
626 for (const auto &Piece : cast<MDNode>(Option)->operands())
627 StrOptions.push_back(cast<MDString>(Piece)->getString());
628 Streamer.EmitLinkerOptions(StrOptions);
632 unsigned VersionVal = 0;
633 unsigned ImageInfoFlags = 0;
634 StringRef SectionVal;
636 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
638 // The section is mandatory. If we don't have it, then we don't have GC info.
639 if (SectionVal.empty())
642 StringRef Segment, Section;
643 unsigned TAA = 0, StubSize = 0;
645 std::string ErrorCode =
646 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
647 TAA, TAAParsed, StubSize);
648 if (!ErrorCode.empty())
649 // If invalid, report the error with report_fatal_error.
650 report_fatal_error("Invalid section specifier '" + Section + "': " +
654 MCSectionMachO *S = getContext().getMachOSection(
655 Segment, Section, TAA, StubSize, SectionKind::getData());
656 Streamer.SwitchSection(S);
657 Streamer.EmitLabel(getContext().
658 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
659 Streamer.EmitIntValue(VersionVal, 4);
660 Streamer.EmitIntValue(ImageInfoFlags, 4);
661 Streamer.AddBlankLine();
664 static void checkMachOComdat(const GlobalValue *GV) {
665 const Comdat *C = GV->getComdat();
669 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
670 "' cannot be lowered.");
673 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
674 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
675 // Parse the section specifier and create it if valid.
676 StringRef Segment, Section;
677 unsigned TAA = 0, StubSize = 0;
680 checkMachOComdat(GO);
682 std::string ErrorCode =
683 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
684 TAA, TAAParsed, StubSize);
685 if (!ErrorCode.empty()) {
686 // If invalid, report the error with report_fatal_error.
687 report_fatal_error("Global variable '" + GO->getName() +
688 "' has an invalid section specifier '" +
689 GO->getSection() + "': " + ErrorCode + ".");
694 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
696 // If TAA wasn't set by ParseSectionSpecifier() above,
697 // use the value returned by getMachOSection() as a default.
699 TAA = S->getTypeAndAttributes();
701 // Okay, now that we got the section, verify that the TAA & StubSize agree.
702 // If the user declared multiple globals with different section flags, we need
703 // to reject it here.
704 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
705 // If invalid, report the error with report_fatal_error.
706 report_fatal_error("Global variable '" + GO->getName() +
707 "' section type or attributes does not match previous"
708 " section specifier");
714 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
715 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
716 checkMachOComdat(GO);
718 // Handle thread local data.
719 if (Kind.isThreadBSS()) return TLSBSSSection;
720 if (Kind.isThreadData()) return TLSDataSection;
723 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
725 // If this is weak/linkonce, put this in a coalescable section, either in text
726 // or data depending on if it is writable.
727 if (GO->isWeakForLinker()) {
728 if (Kind.isReadOnly())
729 return ConstTextCoalSection;
730 return DataCoalSection;
733 // FIXME: Alignment check should be handled by section classifier.
734 if (Kind.isMergeable1ByteCString() &&
735 GO->getParent()->getDataLayout().getPreferredAlignment(
736 cast<GlobalVariable>(GO)) < 32)
737 return CStringSection;
739 // Do not put 16-bit arrays in the UString section if they have an
740 // externally visible label, this runs into issues with certain linker
742 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
743 GO->getParent()->getDataLayout().getPreferredAlignment(
744 cast<GlobalVariable>(GO)) < 32)
745 return UStringSection;
747 // With MachO only variables whose corresponding symbol starts with 'l' or
748 // 'L' can be merged, so we only try merging GVs with private linkage.
749 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
750 if (Kind.isMergeableConst4())
751 return FourByteConstantSection;
752 if (Kind.isMergeableConst8())
753 return EightByteConstantSection;
754 if (Kind.isMergeableConst16())
755 return SixteenByteConstantSection;
758 // Otherwise, if it is readonly, but not something we can specially optimize,
759 // just drop it in .const.
760 if (Kind.isReadOnly())
761 return ReadOnlySection;
763 // If this is marked const, put it into a const section. But if the dynamic
764 // linker needs to write to it, put it in the data segment.
765 if (Kind.isReadOnlyWithRel())
766 return ConstDataSection;
768 // Put zero initialized globals with strong external linkage in the
769 // DATA, __common section with the .zerofill directive.
770 if (Kind.isBSSExtern())
771 return DataCommonSection;
773 // Put zero initialized globals with local linkage in __DATA,__bss directive
774 // with the .zerofill directive (aka .lcomm).
775 if (Kind.isBSSLocal())
776 return DataBSSSection;
778 // Otherwise, just drop the variable in the normal data section.
782 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
783 const DataLayout &DL, SectionKind Kind, const Constant *C,
784 unsigned &Align) const {
785 // If this constant requires a relocation, we have to put it in the data
786 // segment, not in the text segment.
787 if (Kind.isData() || Kind.isReadOnlyWithRel())
788 return ConstDataSection;
790 if (Kind.isMergeableConst4())
791 return FourByteConstantSection;
792 if (Kind.isMergeableConst8())
793 return EightByteConstantSection;
794 if (Kind.isMergeableConst16())
795 return SixteenByteConstantSection;
796 return ReadOnlySection; // .const
799 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
800 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
801 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
802 // The mach-o version of this method defaults to returning a stub reference.
804 if (Encoding & DW_EH_PE_indirect) {
805 MachineModuleInfoMachO &MachOMMI =
806 MMI->getObjFileInfo<MachineModuleInfoMachO>();
808 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
810 // Add information about the stub reference to MachOMMI so that the stub
811 // gets emitted by the asmprinter.
812 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
813 if (!StubSym.getPointer()) {
814 MCSymbol *Sym = TM.getSymbol(GV);
815 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
818 return TargetLoweringObjectFile::
819 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
820 Encoding & ~DW_EH_PE_indirect, Streamer);
823 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
827 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
828 const GlobalValue *GV, const TargetMachine &TM,
829 MachineModuleInfo *MMI) const {
830 // The mach-o version of this method defaults to returning a stub reference.
831 MachineModuleInfoMachO &MachOMMI =
832 MMI->getObjFileInfo<MachineModuleInfoMachO>();
834 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
836 // Add information about the stub reference to MachOMMI so that the stub
837 // gets emitted by the asmprinter.
838 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
839 if (!StubSym.getPointer()) {
840 MCSymbol *Sym = TM.getSymbol(GV);
841 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
847 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
848 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
849 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
850 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
851 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
852 // through a non_lazy_ptr stub instead. One advantage is that it allows the
853 // computation of deltas to final external symbols. Example:
859 // .long _extgotequiv-_delta
861 // is transformed to:
864 // .long L_extfoo$non_lazy_ptr-(_delta+0)
866 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
867 // L_extfoo$non_lazy_ptr:
868 // .indirect_symbol _extfoo
871 MachineModuleInfoMachO &MachOMMI =
872 MMI->getObjFileInfo<MachineModuleInfoMachO>();
873 MCContext &Ctx = getContext();
875 // The offset must consider the original displacement from the base symbol
876 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
877 Offset = -MV.getConstant();
878 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
880 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
881 // non_lazy_ptr stubs.
882 SmallString<128> Name;
883 StringRef Suffix = "$non_lazy_ptr";
884 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
885 Name += Sym->getName();
887 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
889 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
890 if (!StubSym.getPointer())
891 StubSym = MachineModuleInfoImpl::
892 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
894 const MCExpr *BSymExpr =
895 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
897 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
900 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
903 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
904 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
907 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
908 const MCSection &Section) {
909 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
912 // If it is not dead stripped, it is safe to use private labels.
913 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
914 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
920 void TargetLoweringObjectFileMachO::getNameWithPrefix(
921 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
922 const TargetMachine &TM) const {
923 bool CannotUsePrivateLabel = true;
924 if (auto *GO = GV->getBaseObject()) {
925 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
926 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
927 CannotUsePrivateLabel =
928 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
930 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
933 //===----------------------------------------------------------------------===//
935 //===----------------------------------------------------------------------===//
938 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
940 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
944 COFF::IMAGE_SCN_MEM_DISCARDABLE;
947 COFF::IMAGE_SCN_MEM_EXECUTE |
948 COFF::IMAGE_SCN_MEM_READ |
949 COFF::IMAGE_SCN_CNT_CODE |
950 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
953 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
954 COFF::IMAGE_SCN_MEM_READ |
955 COFF::IMAGE_SCN_MEM_WRITE;
956 else if (K.isThreadLocal())
958 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
959 COFF::IMAGE_SCN_MEM_READ |
960 COFF::IMAGE_SCN_MEM_WRITE;
961 else if (K.isReadOnly() || K.isReadOnlyWithRel())
963 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
964 COFF::IMAGE_SCN_MEM_READ;
965 else if (K.isWriteable())
967 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
968 COFF::IMAGE_SCN_MEM_READ |
969 COFF::IMAGE_SCN_MEM_WRITE;
974 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
975 const Comdat *C = GV->getComdat();
976 assert(C && "expected GV to have a Comdat!");
978 StringRef ComdatGVName = C->getName();
979 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
981 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
982 "' does not exist.");
984 if (ComdatGV->getComdat() != C)
985 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
986 "' is not a key for its COMDAT.");
991 static int getSelectionForCOFF(const GlobalValue *GV) {
992 if (const Comdat *C = GV->getComdat()) {
993 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
994 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
995 ComdatKey = GA->getBaseObject();
996 if (ComdatKey == GV) {
997 switch (C->getSelectionKind()) {
999 return COFF::IMAGE_COMDAT_SELECT_ANY;
1000 case Comdat::ExactMatch:
1001 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1002 case Comdat::Largest:
1003 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1004 case Comdat::NoDuplicates:
1005 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1006 case Comdat::SameSize:
1007 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1010 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1016 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1017 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1019 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1020 StringRef Name = GO->getSection();
1021 StringRef COMDATSymName = "";
1022 if (GO->hasComdat()) {
1023 Selection = getSelectionForCOFF(GO);
1024 const GlobalValue *ComdatGV;
1025 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1026 ComdatGV = getComdatGVForCOFF(GO);
1030 if (!ComdatGV->hasPrivateLinkage()) {
1031 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1032 COMDATSymName = Sym->getName();
1033 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1039 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1043 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1048 if (Kind.isThreadLocal())
1050 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1055 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1056 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1057 // If we have -ffunction-sections then we should emit the global value to a
1058 // uniqued section specifically for it.
1059 bool EmitUniquedSection;
1061 EmitUniquedSection = TM.getFunctionSections();
1063 EmitUniquedSection = TM.getDataSections();
1065 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1066 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1067 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1069 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1070 int Selection = getSelectionForCOFF(GO);
1072 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1073 const GlobalValue *ComdatGV;
1074 if (GO->hasComdat())
1075 ComdatGV = getComdatGVForCOFF(GO);
1079 unsigned UniqueID = MCContext::GenericSectionID;
1080 if (EmitUniquedSection)
1081 UniqueID = NextUniqueID++;
1083 if (!ComdatGV->hasPrivateLinkage()) {
1084 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1085 StringRef COMDATSymName = Sym->getName();
1086 return getContext().getCOFFSection(Name, Characteristics, Kind,
1087 COMDATSymName, Selection, UniqueID);
1089 SmallString<256> TmpData;
1090 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1091 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1092 Selection, UniqueID);
1099 if (Kind.isThreadLocal())
1100 return TLSDataSection;
1102 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1103 return ReadOnlySection;
1105 // Note: we claim that common symbols are put in BSSSection, but they are
1106 // really emitted with the magic .comm directive, which creates a symbol table
1107 // entry but not a section.
1108 if (Kind.isBSS() || Kind.isCommon())
1114 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1115 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1116 const TargetMachine &TM) const {
1117 bool CannotUsePrivateLabel = false;
1118 if (GV->hasPrivateLinkage() &&
1119 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1120 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1121 CannotUsePrivateLabel = true;
1123 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1126 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1127 const Function &F, const TargetMachine &TM) const {
1128 // If the function can be removed, produce a unique section so that
1129 // the table doesn't prevent the removal.
1130 const Comdat *C = F.getComdat();
1131 bool EmitUniqueSection = TM.getFunctionSections() || C;
1132 if (!EmitUniqueSection)
1133 return ReadOnlySection;
1135 // FIXME: we should produce a symbol for F instead.
1136 if (F.hasPrivateLinkage())
1137 return ReadOnlySection;
1139 MCSymbol *Sym = TM.getSymbol(&F);
1140 StringRef COMDATSymName = Sym->getName();
1142 SectionKind Kind = SectionKind::getReadOnly();
1143 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1144 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1145 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1146 unsigned UniqueID = NextUniqueID++;
1148 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1149 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1152 void TargetLoweringObjectFileCOFF::emitModuleMetadata(
1153 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
1154 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1155 // Emit the linker options to the linker .drectve section. According to the
1156 // spec, this section is a space-separated string containing flags for
1158 MCSection *Sec = getDrectveSection();
1159 Streamer.SwitchSection(Sec);
1160 for (const auto &Option : LinkerOptions->operands()) {
1161 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1162 // Lead with a space for consistency with our dllexport implementation.
1163 std::string Directive(" ");
1164 Directive.append(cast<MDString>(Piece)->getString());
1165 Streamer.EmitBytes(Directive);
1170 unsigned Version = 0;
1174 GetObjCImageInfo(M, Version, Flags, Section);
1175 if (Section.empty())
1178 auto &C = getContext();
1179 auto *S = C.getCOFFSection(
1180 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1181 SectionKind::getReadOnly());
1182 Streamer.SwitchSection(S);
1183 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1184 Streamer.EmitIntValue(Version, 4);
1185 Streamer.EmitIntValue(Flags, 4);
1186 Streamer.AddBlankLine();
1189 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1190 const TargetMachine &TM) {
1191 TargetLoweringObjectFile::Initialize(Ctx, TM);
1192 const Triple &T = TM.getTargetTriple();
1193 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1195 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1196 COFF::IMAGE_SCN_MEM_READ,
1197 SectionKind::getReadOnly());
1199 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1200 COFF::IMAGE_SCN_MEM_READ,
1201 SectionKind::getReadOnly());
1203 StaticCtorSection = Ctx.getCOFFSection(
1204 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1205 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1206 SectionKind::getData());
1207 StaticDtorSection = Ctx.getCOFFSection(
1208 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1209 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1210 SectionKind::getData());
1214 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1215 const Triple &T, bool IsCtor,
1217 const MCSymbol *KeySym,
1218 MCSectionCOFF *Default) {
1219 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment())
1220 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1222 std::string Name = IsCtor ? ".ctors" : ".dtors";
1223 if (Priority != 65535)
1224 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1226 return Ctx.getAssociativeCOFFSection(
1227 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1228 COFF::IMAGE_SCN_MEM_READ |
1229 COFF::IMAGE_SCN_MEM_WRITE,
1230 SectionKind::getData()),
1234 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1235 unsigned Priority, const MCSymbol *KeySym) const {
1236 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1238 cast<MCSectionCOFF>(StaticCtorSection));
1241 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1242 unsigned Priority, const MCSymbol *KeySym) const {
1243 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1245 cast<MCSectionCOFF>(StaticDtorSection));
1248 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1249 raw_ostream &OS, const GlobalValue *GV) const {
1250 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1253 //===----------------------------------------------------------------------===//
1255 //===----------------------------------------------------------------------===//
1257 static void checkWasmComdat(const GlobalValue *GV) {
1258 const Comdat *C = GV->getComdat();
1262 // TODO(sbc): At some point we may need COMDAT support but currently
1263 // they are not supported.
1264 report_fatal_error("WebAssembly doesn't support COMDATs, '" + C->getName() +
1265 "' cannot be lowered.");
1268 static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
1269 // If we're told we have function data, then use that.
1271 return SectionKind::getText();
1273 // Otherwise, ignore whatever section type the generic impl detected and use
1274 // a plain data section.
1275 return SectionKind::getData();
1278 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1279 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1280 StringRef Name = GO->getSection();
1281 checkWasmComdat(GO);
1282 Kind = getWasmKindForNamedSection(Name, Kind);
1283 return getContext().getWasmSection(Name, Kind);
1286 static MCSectionWasm *selectWasmSectionForGlobal(
1287 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1288 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1289 StringRef Group = "";
1290 checkWasmComdat(GO);
1292 bool UniqueSectionNames = TM.getUniqueSectionNames();
1293 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1295 if (const auto *F = dyn_cast<Function>(GO)) {
1296 const auto &OptionalPrefix = F->getSectionPrefix();
1298 Name += *OptionalPrefix;
1301 if (EmitUniqueSection && UniqueSectionNames) {
1302 Name.push_back('.');
1303 TM.getNameWithPrefix(Name, GO, Mang, true);
1305 unsigned UniqueID = MCContext::GenericSectionID;
1306 if (EmitUniqueSection && !UniqueSectionNames) {
1307 UniqueID = *NextUniqueID;
1310 return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1313 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1314 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1316 if (Kind.isCommon())
1317 report_fatal_error("mergable sections not supported yet on wasm");
1319 // If we have -ffunction-section or -fdata-section then we should emit the
1320 // global value to a uniqued section specifically for it.
1321 bool EmitUniqueSection = false;
1323 EmitUniqueSection = TM.getFunctionSections();
1325 EmitUniqueSection = TM.getDataSections();
1326 EmitUniqueSection |= GO->hasComdat();
1328 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1329 EmitUniqueSection, &NextUniqueID);
1332 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1333 bool UsesLabelDifference, const Function &F) const {
1334 // We can always create relative relocations, so use another section
1335 // that can be marked non-executable.
1339 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1340 const GlobalValue *LHS, const GlobalValue *RHS,
1341 const TargetMachine &TM) const {
1342 // We may only use a PLT-relative relocation to refer to unnamed_addr
1344 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1347 // Basic sanity checks.
1348 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1349 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1350 RHS->isThreadLocal())
1353 return MCBinaryExpr::createSub(
1354 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1356 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1359 void TargetLoweringObjectFileWasm::InitializeWasm() {
1361 getContext().getWasmSection(".init_array", SectionKind::getData());
1364 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1365 unsigned Priority, const MCSymbol *KeySym) const {
1366 return Priority == UINT16_MAX ?
1368 getContext().getWasmSection(".init_array." + utostr(Priority),
1369 SectionKind::getData());
1372 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1373 unsigned Priority, const MCSymbol *KeySym) const {
1374 llvm_unreachable("@llvm.global_dtors should have been lowered already");