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/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSectionELF.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbolELF.h"
35 #include "llvm/MC/MCValue.h"
36 #include "llvm/Support/COFF.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ELF.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
45 using namespace dwarf;
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
52 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
53 MachineModuleInfo *MMI) const {
54 unsigned Encoding = getPersonalityEncoding();
55 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
56 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
57 TM.getSymbol(GV, Mang)->getName());
58 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
59 return TM.getSymbol(GV, Mang);
60 report_fatal_error("We do not support this DWARF encoding yet!");
63 void TargetLoweringObjectFileELF::emitPersonalityValue(
64 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
65 SmallString<64> NameData("DW.ref.");
66 NameData += Sym->getName();
68 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
69 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
70 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
71 StringRef Prefix = ".data.";
72 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
73 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
74 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
75 Flags, 0, Label->getName());
76 unsigned Size = DL.getPointerSize();
77 Streamer.SwitchSection(Sec);
78 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
79 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
80 const MCExpr *E = MCConstantExpr::create(Size, getContext());
81 Streamer.emitELFSize(Label, E);
82 Streamer.EmitLabel(Label);
84 Streamer.EmitSymbolValue(Sym, Size);
87 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
88 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
89 const TargetMachine &TM, MachineModuleInfo *MMI,
90 MCStreamer &Streamer) const {
92 if (Encoding & dwarf::DW_EH_PE_indirect) {
93 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
95 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
97 // Add information about the stub reference to ELFMMI so that the stub
98 // gets emitted by the asmprinter.
99 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
100 if (!StubSym.getPointer()) {
101 MCSymbol *Sym = TM.getSymbol(GV, Mang);
102 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
105 return TargetLoweringObjectFile::
106 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
107 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
110 return TargetLoweringObjectFile::
111 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
115 getELFKindForNamedSection(StringRef Name, SectionKind K) {
116 // N.B.: The defaults used in here are no the same ones used in MC.
117 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
118 // both gas and MC will produce a section with no flags. Given
119 // section(".eh_frame") gcc will produce:
121 // .section .eh_frame,"a",@progbits
122 if (Name.empty() || Name[0] != '.') return K;
124 // Some lame default implementation based on some magic section names.
125 if (Name == ".bss" ||
126 Name.startswith(".bss.") ||
127 Name.startswith(".gnu.linkonce.b.") ||
128 Name.startswith(".llvm.linkonce.b.") ||
130 Name.startswith(".sbss.") ||
131 Name.startswith(".gnu.linkonce.sb.") ||
132 Name.startswith(".llvm.linkonce.sb."))
133 return SectionKind::getBSS();
135 if (Name == ".tdata" ||
136 Name.startswith(".tdata.") ||
137 Name.startswith(".gnu.linkonce.td.") ||
138 Name.startswith(".llvm.linkonce.td."))
139 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();
151 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
153 if (Name == ".init_array")
154 return ELF::SHT_INIT_ARRAY;
156 if (Name == ".fini_array")
157 return ELF::SHT_FINI_ARRAY;
159 if (Name == ".preinit_array")
160 return ELF::SHT_PREINIT_ARRAY;
162 if (K.isBSS() || K.isThreadBSS())
163 return ELF::SHT_NOBITS;
165 return ELF::SHT_PROGBITS;
168 static unsigned getELFSectionFlags(SectionKind K) {
172 Flags |= ELF::SHF_ALLOC;
175 Flags |= ELF::SHF_EXECINSTR;
178 Flags |= ELF::SHF_WRITE;
180 if (K.isThreadLocal())
181 Flags |= ELF::SHF_TLS;
183 if (K.isMergeableCString() || K.isMergeableConst())
184 Flags |= ELF::SHF_MERGE;
186 if (K.isMergeableCString())
187 Flags |= ELF::SHF_STRINGS;
192 static const Comdat *getELFComdat(const GlobalValue *GV) {
193 const Comdat *C = GV->getComdat();
197 if (C->getSelectionKind() != Comdat::Any)
198 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
199 C->getName() + "' cannot be lowered.");
204 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
205 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
206 const TargetMachine &TM) const {
207 StringRef SectionName = GV->getSection();
209 // Infer section flags from the section name if we can.
210 Kind = getELFKindForNamedSection(SectionName, Kind);
212 StringRef Group = "";
213 unsigned Flags = getELFSectionFlags(Kind);
214 if (const Comdat *C = getELFComdat(GV)) {
215 Group = C->getName();
216 Flags |= ELF::SHF_GROUP;
218 return getContext().getELFSection(SectionName,
219 getELFSectionType(SectionName, Kind), Flags,
220 /*EntrySize=*/0, Group);
223 /// Return the section prefix name used by options FunctionsSections and
225 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
228 if (Kind.isReadOnly())
232 if (Kind.isThreadData())
234 if (Kind.isThreadBSS())
236 if (Kind.isDataNoRel())
238 if (Kind.isDataRelLocal())
239 return ".data.rel.local";
240 if (Kind.isDataRel())
242 if (Kind.isReadOnlyWithRelLocal())
243 return ".data.rel.ro.local";
244 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
245 return ".data.rel.ro";
248 static MCSectionELF *
249 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
250 SectionKind Kind, Mangler &Mang,
251 const TargetMachine &TM, bool EmitUniqueSection,
252 unsigned Flags, unsigned *NextUniqueID) {
253 unsigned EntrySize = 0;
254 if (Kind.isMergeableCString()) {
255 if (Kind.isMergeable2ByteCString()) {
257 } else if (Kind.isMergeable4ByteCString()) {
261 assert(Kind.isMergeable1ByteCString() && "unknown string width");
263 } else if (Kind.isMergeableConst()) {
264 if (Kind.isMergeableConst4()) {
266 } else if (Kind.isMergeableConst8()) {
269 assert(Kind.isMergeableConst16() && "unknown data width");
274 StringRef Group = "";
275 if (const Comdat *C = getELFComdat(GV)) {
276 Flags |= ELF::SHF_GROUP;
277 Group = C->getName();
280 bool UniqueSectionNames = TM.getUniqueSectionNames();
281 SmallString<128> Name;
282 if (Kind.isMergeableCString()) {
283 // We also need alignment here.
284 // FIXME: this is getting the alignment of the character, not the
285 // alignment of the global!
286 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
287 cast<GlobalVariable>(GV));
289 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
290 Name = SizeSpec + utostr(Align);
291 } else if (Kind.isMergeableConst()) {
292 Name = ".rodata.cst";
293 Name += utostr(EntrySize);
295 Name = getSectionPrefixForGlobal(Kind);
298 if (EmitUniqueSection && UniqueSectionNames) {
300 TM.getNameWithPrefix(Name, GV, Mang, true);
302 unsigned UniqueID = ~0;
303 if (EmitUniqueSection && !UniqueSectionNames) {
304 UniqueID = *NextUniqueID;
307 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
308 EntrySize, Group, UniqueID);
311 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
312 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
313 const TargetMachine &TM) const {
314 unsigned Flags = getELFSectionFlags(Kind);
316 // If we have -ffunction-section or -fdata-section then we should emit the
317 // global value to a uniqued section specifically for it.
318 bool EmitUniqueSection = false;
319 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
321 EmitUniqueSection = TM.getFunctionSections();
323 EmitUniqueSection = TM.getDataSections();
325 EmitUniqueSection |= GV->hasComdat();
327 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
328 EmitUniqueSection, Flags, &NextUniqueID);
331 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
332 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
333 // If the function can be removed, produce a unique section so that
334 // the table doesn't prevent the removal.
335 const Comdat *C = F.getComdat();
336 bool EmitUniqueSection = TM.getFunctionSections() || C;
337 if (!EmitUniqueSection)
338 return ReadOnlySection;
340 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
341 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
345 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
346 bool UsesLabelDifference, const Function &F) const {
347 // We can always create relative relocations, so use another section
348 // that can be marked non-executable.
352 /// Given a mergeable constant with the specified size and relocation
353 /// information, return a section that it should be placed in.
354 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
355 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
356 if (Kind.isMergeableConst4() && MergeableConst4Section)
357 return MergeableConst4Section;
358 if (Kind.isMergeableConst8() && MergeableConst8Section)
359 return MergeableConst8Section;
360 if (Kind.isMergeableConst16() && MergeableConst16Section)
361 return MergeableConst16Section;
362 if (Kind.isReadOnly())
363 return ReadOnlySection;
365 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
366 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
367 return DataRelROSection;
370 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
371 bool IsCtor, unsigned Priority,
372 const MCSymbol *KeySym) {
375 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
376 StringRef COMDAT = KeySym ? KeySym->getName() : "";
379 Flags |= ELF::SHF_GROUP;
383 Type = ELF::SHT_INIT_ARRAY;
384 Name = ".init_array";
386 Type = ELF::SHT_FINI_ARRAY;
387 Name = ".fini_array";
389 if (Priority != 65535) {
391 Name += utostr(Priority);
394 // The default scheme is .ctor / .dtor, so we have to invert the priority
400 if (Priority != 65535) {
402 Name += utostr(65535 - Priority);
404 Type = ELF::SHT_PROGBITS;
407 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
410 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
411 unsigned Priority, const MCSymbol *KeySym) const {
412 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
416 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
417 unsigned Priority, const MCSymbol *KeySym) const {
418 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
423 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
424 UseInitArray = UseInitArray_;
428 StaticCtorSection = getContext().getELFSection(
429 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
430 StaticDtorSection = getContext().getELFSection(
431 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
434 //===----------------------------------------------------------------------===//
436 //===----------------------------------------------------------------------===//
438 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
439 : TargetLoweringObjectFile() {
440 SupportIndirectSymViaGOTPCRel = true;
443 /// emitModuleFlags - Perform code emission for module flags.
444 void TargetLoweringObjectFileMachO::
445 emitModuleFlags(MCStreamer &Streamer,
446 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
447 Mangler &Mang, const TargetMachine &TM) const {
448 unsigned VersionVal = 0;
449 unsigned ImageInfoFlags = 0;
450 MDNode *LinkerOptions = nullptr;
451 StringRef SectionVal;
453 for (ArrayRef<Module::ModuleFlagEntry>::iterator
454 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
455 const Module::ModuleFlagEntry &MFE = *i;
457 // Ignore flags with 'Require' behavior.
458 if (MFE.Behavior == Module::Require)
461 StringRef Key = MFE.Key->getString();
462 Metadata *Val = MFE.Val;
464 if (Key == "Objective-C Image Info Version") {
465 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
466 } else if (Key == "Objective-C Garbage Collection" ||
467 Key == "Objective-C GC Only" ||
468 Key == "Objective-C Is Simulated" ||
469 Key == "Objective-C Image Swift Version") {
470 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
471 } else if (Key == "Objective-C Image Info Section") {
472 SectionVal = cast<MDString>(Val)->getString();
473 } else if (Key == "Linker Options") {
474 LinkerOptions = cast<MDNode>(Val);
478 // Emit the linker options if present.
480 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
481 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
482 SmallVector<std::string, 4> StrOptions;
484 // Convert to strings.
485 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
486 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
487 StrOptions.push_back(MDOption->getString());
490 Streamer.EmitLinkerOptions(StrOptions);
494 // The section is mandatory. If we don't have it, then we don't have GC info.
495 if (SectionVal.empty()) return;
497 StringRef Segment, Section;
498 unsigned TAA = 0, StubSize = 0;
500 std::string ErrorCode =
501 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
502 TAA, TAAParsed, StubSize);
503 if (!ErrorCode.empty())
504 // If invalid, report the error with report_fatal_error.
505 report_fatal_error("Invalid section specifier '" + Section + "': " +
509 MCSectionMachO *S = getContext().getMachOSection(
510 Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
511 Streamer.SwitchSection(S);
512 Streamer.EmitLabel(getContext().
513 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
514 Streamer.EmitIntValue(VersionVal, 4);
515 Streamer.EmitIntValue(ImageInfoFlags, 4);
516 Streamer.AddBlankLine();
519 static void checkMachOComdat(const GlobalValue *GV) {
520 const Comdat *C = GV->getComdat();
524 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
525 "' cannot be lowered.");
528 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
529 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
530 const TargetMachine &TM) const {
531 // Parse the section specifier and create it if valid.
532 StringRef Segment, Section;
533 unsigned TAA = 0, StubSize = 0;
536 checkMachOComdat(GV);
538 std::string ErrorCode =
539 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
540 TAA, TAAParsed, StubSize);
541 if (!ErrorCode.empty()) {
542 // If invalid, report the error with report_fatal_error.
543 report_fatal_error("Global variable '" + GV->getName() +
544 "' has an invalid section specifier '" +
545 GV->getSection() + "': " + ErrorCode + ".");
550 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
552 // If TAA wasn't set by ParseSectionSpecifier() above,
553 // use the value returned by getMachOSection() as a default.
555 TAA = S->getTypeAndAttributes();
557 // Okay, now that we got the section, verify that the TAA & StubSize agree.
558 // If the user declared multiple globals with different section flags, we need
559 // to reject it here.
560 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
561 // If invalid, report the error with report_fatal_error.
562 report_fatal_error("Global variable '" + GV->getName() +
563 "' section type or attributes does not match previous"
564 " section specifier");
570 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
571 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
572 const TargetMachine &TM) const {
573 checkMachOComdat(GV);
575 // Handle thread local data.
576 if (Kind.isThreadBSS()) return TLSBSSSection;
577 if (Kind.isThreadData()) return TLSDataSection;
580 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
582 // If this is weak/linkonce, put this in a coalescable section, either in text
583 // or data depending on if it is writable.
584 if (GV->isWeakForLinker()) {
585 if (Kind.isReadOnly())
586 return ConstTextCoalSection;
587 return DataCoalSection;
590 // FIXME: Alignment check should be handled by section classifier.
591 if (Kind.isMergeable1ByteCString() &&
592 GV->getParent()->getDataLayout().getPreferredAlignment(
593 cast<GlobalVariable>(GV)) < 32)
594 return CStringSection;
596 // Do not put 16-bit arrays in the UString section if they have an
597 // externally visible label, this runs into issues with certain linker
599 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
600 GV->getParent()->getDataLayout().getPreferredAlignment(
601 cast<GlobalVariable>(GV)) < 32)
602 return UStringSection;
604 // With MachO only variables whose corresponding symbol starts with 'l' or
605 // 'L' can be merged, so we only try merging GVs with private linkage.
606 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
607 if (Kind.isMergeableConst4())
608 return FourByteConstantSection;
609 if (Kind.isMergeableConst8())
610 return EightByteConstantSection;
611 if (Kind.isMergeableConst16())
612 return SixteenByteConstantSection;
615 // Otherwise, if it is readonly, but not something we can specially optimize,
616 // just drop it in .const.
617 if (Kind.isReadOnly())
618 return ReadOnlySection;
620 // If this is marked const, put it into a const section. But if the dynamic
621 // linker needs to write to it, put it in the data segment.
622 if (Kind.isReadOnlyWithRel())
623 return ConstDataSection;
625 // Put zero initialized globals with strong external linkage in the
626 // DATA, __common section with the .zerofill directive.
627 if (Kind.isBSSExtern())
628 return DataCommonSection;
630 // Put zero initialized globals with local linkage in __DATA,__bss directive
631 // with the .zerofill directive (aka .lcomm).
632 if (Kind.isBSSLocal())
633 return DataBSSSection;
635 // Otherwise, just drop the variable in the normal data section.
639 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
640 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
641 // If this constant requires a relocation, we have to put it in the data
642 // segment, not in the text segment.
643 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
644 return ConstDataSection;
646 if (Kind.isMergeableConst4())
647 return FourByteConstantSection;
648 if (Kind.isMergeableConst8())
649 return EightByteConstantSection;
650 if (Kind.isMergeableConst16())
651 return SixteenByteConstantSection;
652 return ReadOnlySection; // .const
655 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
656 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
657 const TargetMachine &TM, MachineModuleInfo *MMI,
658 MCStreamer &Streamer) const {
659 // The mach-o version of this method defaults to returning a stub reference.
661 if (Encoding & DW_EH_PE_indirect) {
662 MachineModuleInfoMachO &MachOMMI =
663 MMI->getObjFileInfo<MachineModuleInfoMachO>();
666 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
668 // Add information about the stub reference to MachOMMI so that the stub
669 // gets emitted by the asmprinter.
670 MachineModuleInfoImpl::StubValueTy &StubSym =
671 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
672 MachOMMI.getGVStubEntry(SSym);
673 if (!StubSym.getPointer()) {
674 MCSymbol *Sym = TM.getSymbol(GV, Mang);
675 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
678 return TargetLoweringObjectFile::
679 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
680 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
683 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
687 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
688 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
689 MachineModuleInfo *MMI) const {
690 // The mach-o version of this method defaults to returning a stub reference.
691 MachineModuleInfoMachO &MachOMMI =
692 MMI->getObjFileInfo<MachineModuleInfoMachO>();
694 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
696 // Add information about the stub reference to MachOMMI so that the stub
697 // gets emitted by the asmprinter.
698 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
699 if (!StubSym.getPointer()) {
700 MCSymbol *Sym = TM.getSymbol(GV, Mang);
701 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
707 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
708 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
709 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
710 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
711 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
712 // through a non_lazy_ptr stub instead. One advantage is that it allows the
713 // computation of deltas to final external symbols. Example:
719 // .long _extgotequiv-_delta
721 // is transformed to:
724 // .long L_extfoo$non_lazy_ptr-(_delta+0)
726 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
727 // L_extfoo$non_lazy_ptr:
728 // .indirect_symbol _extfoo
731 MachineModuleInfoMachO &MachOMMI =
732 MMI->getObjFileInfo<MachineModuleInfoMachO>();
733 MCContext &Ctx = getContext();
735 // The offset must consider the original displacement from the base symbol
736 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
737 Offset = -MV.getConstant();
738 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
740 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
741 // non_lazy_ptr stubs.
742 SmallString<128> Name;
743 StringRef Suffix = "$non_lazy_ptr";
744 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
745 Name += Sym->getName();
747 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
749 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
750 if (!StubSym.getPointer())
751 StubSym = MachineModuleInfoImpl::
752 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
754 const MCExpr *BSymExpr =
755 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
757 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
760 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
763 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
764 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
767 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
768 const MCSection &Section) {
769 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
772 // If it is not dead stripped, it is safe to use private labels.
773 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
774 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
780 void TargetLoweringObjectFileMachO::getNameWithPrefix(
781 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
782 const TargetMachine &TM) const {
783 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
784 const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
785 bool CannotUsePrivateLabel =
786 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
787 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
790 //===----------------------------------------------------------------------===//
792 //===----------------------------------------------------------------------===//
795 getCOFFSectionFlags(SectionKind K) {
800 COFF::IMAGE_SCN_MEM_DISCARDABLE;
803 COFF::IMAGE_SCN_MEM_EXECUTE |
804 COFF::IMAGE_SCN_MEM_READ |
805 COFF::IMAGE_SCN_CNT_CODE;
808 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
809 COFF::IMAGE_SCN_MEM_READ |
810 COFF::IMAGE_SCN_MEM_WRITE;
811 else if (K.isThreadLocal())
813 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
814 COFF::IMAGE_SCN_MEM_READ |
815 COFF::IMAGE_SCN_MEM_WRITE;
816 else if (K.isReadOnly() || K.isReadOnlyWithRel())
818 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
819 COFF::IMAGE_SCN_MEM_READ;
820 else if (K.isWriteable())
822 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
823 COFF::IMAGE_SCN_MEM_READ |
824 COFF::IMAGE_SCN_MEM_WRITE;
829 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
830 const Comdat *C = GV->getComdat();
831 assert(C && "expected GV to have a Comdat!");
833 StringRef ComdatGVName = C->getName();
834 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
836 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
837 "' does not exist.");
839 if (ComdatGV->getComdat() != C)
840 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
841 "' is not a key for its COMDAT.");
846 static int getSelectionForCOFF(const GlobalValue *GV) {
847 if (const Comdat *C = GV->getComdat()) {
848 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
849 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
850 ComdatKey = GA->getBaseObject();
851 if (ComdatKey == GV) {
852 switch (C->getSelectionKind()) {
854 return COFF::IMAGE_COMDAT_SELECT_ANY;
855 case Comdat::ExactMatch:
856 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
857 case Comdat::Largest:
858 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
859 case Comdat::NoDuplicates:
860 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
861 case Comdat::SameSize:
862 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
865 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
871 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
872 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
873 const TargetMachine &TM) const {
875 unsigned Characteristics = getCOFFSectionFlags(Kind);
876 StringRef Name = GV->getSection();
877 StringRef COMDATSymName = "";
878 if (GV->hasComdat()) {
879 Selection = getSelectionForCOFF(GV);
880 const GlobalValue *ComdatGV;
881 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
882 ComdatGV = getComdatGVForCOFF(GV);
886 if (!ComdatGV->hasPrivateLinkage()) {
887 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
888 COMDATSymName = Sym->getName();
889 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
894 return getContext().getCOFFSection(Name,
901 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
906 if (Kind.isThreadLocal())
908 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
913 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
914 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
915 const TargetMachine &TM) const {
916 // If we have -ffunction-sections then we should emit the global value to a
917 // uniqued section specifically for it.
918 bool EmitUniquedSection;
920 EmitUniquedSection = TM.getFunctionSections();
922 EmitUniquedSection = TM.getDataSections();
924 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
925 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
926 unsigned Characteristics = getCOFFSectionFlags(Kind);
928 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
929 int Selection = getSelectionForCOFF(GV);
931 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
932 const GlobalValue *ComdatGV;
934 ComdatGV = getComdatGVForCOFF(GV);
938 if (!ComdatGV->hasPrivateLinkage()) {
939 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
940 StringRef COMDATSymName = Sym->getName();
941 return getContext().getCOFFSection(Name, Characteristics, Kind,
942 COMDATSymName, Selection);
944 SmallString<256> TmpData;
945 Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
946 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
954 if (Kind.isThreadLocal())
955 return TLSDataSection;
957 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
958 return ReadOnlySection;
960 // Note: we claim that common symbols are put in BSSSection, but they are
961 // really emitted with the magic .comm directive, which creates a symbol table
962 // entry but not a section.
963 if (Kind.isBSS() || Kind.isCommon())
969 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
970 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
971 const TargetMachine &TM) const {
972 bool CannotUsePrivateLabel = false;
973 if (GV->hasPrivateLinkage() &&
974 ((isa<Function>(GV) && TM.getFunctionSections()) ||
975 (isa<GlobalVariable>(GV) && TM.getDataSections())))
976 CannotUsePrivateLabel = true;
978 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
981 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
982 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
983 // If the function can be removed, produce a unique section so that
984 // the table doesn't prevent the removal.
985 const Comdat *C = F.getComdat();
986 bool EmitUniqueSection = TM.getFunctionSections() || C;
987 if (!EmitUniqueSection)
988 return ReadOnlySection;
990 // FIXME: we should produce a symbol for F instead.
991 if (F.hasPrivateLinkage())
992 return ReadOnlySection;
994 MCSymbol *Sym = TM.getSymbol(&F, Mang);
995 StringRef COMDATSymName = Sym->getName();
997 SectionKind Kind = SectionKind::getReadOnly();
998 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
999 unsigned Characteristics = getCOFFSectionFlags(Kind);
1000 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1002 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1003 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
1006 void TargetLoweringObjectFileCOFF::
1007 emitModuleFlags(MCStreamer &Streamer,
1008 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1009 Mangler &Mang, const TargetMachine &TM) const {
1010 MDNode *LinkerOptions = nullptr;
1012 // Look for the "Linker Options" flag, since it's the only one we support.
1013 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1014 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1015 const Module::ModuleFlagEntry &MFE = *i;
1016 StringRef Key = MFE.Key->getString();
1017 Metadata *Val = MFE.Val;
1018 if (Key == "Linker Options") {
1019 LinkerOptions = cast<MDNode>(Val);
1026 // Emit the linker options to the linker .drectve section. According to the
1027 // spec, this section is a space-separated string containing flags for linker.
1028 MCSection *Sec = getDrectveSection();
1029 Streamer.SwitchSection(Sec);
1030 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1031 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1032 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1033 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1034 // Lead with a space for consistency with our dllexport implementation.
1035 std::string Directive(" ");
1036 Directive.append(MDOption->getString());
1037 Streamer.EmitBytes(Directive);
1042 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1043 unsigned Priority, const MCSymbol *KeySym) const {
1044 return getContext().getAssociativeCOFFSection(
1045 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1048 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1049 unsigned Priority, const MCSymbol *KeySym) const {
1050 return getContext().getAssociativeCOFFSection(
1051 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
1054 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1055 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1056 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1059 const Triple &TT = getTargetTriple();
1061 if (TT.isKnownWindowsMSVCEnvironment())
1066 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1068 raw_string_ostream FlagOS(Flag);
1069 Mang.getNameWithPrefix(FlagOS, GV, false);
1071 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1072 OS << Flag.substr(1);
1076 Mang.getNameWithPrefix(OS, GV, false);
1079 if (!GV->getValueType()->isFunctionTy()) {
1080 if (TT.isKnownWindowsMSVCEnvironment())