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())
238 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
239 return ".data.rel.ro";
242 static MCSectionELF *
243 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
244 SectionKind Kind, Mangler &Mang,
245 const TargetMachine &TM, bool EmitUniqueSection,
246 unsigned Flags, unsigned *NextUniqueID) {
247 unsigned EntrySize = 0;
248 if (Kind.isMergeableCString()) {
249 if (Kind.isMergeable2ByteCString()) {
251 } else if (Kind.isMergeable4ByteCString()) {
255 assert(Kind.isMergeable1ByteCString() && "unknown string width");
257 } else if (Kind.isMergeableConst()) {
258 if (Kind.isMergeableConst4()) {
260 } else if (Kind.isMergeableConst8()) {
263 assert(Kind.isMergeableConst16() && "unknown data width");
268 StringRef Group = "";
269 if (const Comdat *C = getELFComdat(GV)) {
270 Flags |= ELF::SHF_GROUP;
271 Group = C->getName();
274 bool UniqueSectionNames = TM.getUniqueSectionNames();
275 SmallString<128> Name;
276 if (Kind.isMergeableCString()) {
277 // We also need alignment here.
278 // FIXME: this is getting the alignment of the character, not the
279 // alignment of the global!
280 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
281 cast<GlobalVariable>(GV));
283 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
284 Name = SizeSpec + utostr(Align);
285 } else if (Kind.isMergeableConst()) {
286 Name = ".rodata.cst";
287 Name += utostr(EntrySize);
289 Name = getSectionPrefixForGlobal(Kind);
292 if (EmitUniqueSection && UniqueSectionNames) {
294 TM.getNameWithPrefix(Name, GV, Mang, true);
296 unsigned UniqueID = ~0;
297 if (EmitUniqueSection && !UniqueSectionNames) {
298 UniqueID = *NextUniqueID;
301 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
302 EntrySize, Group, UniqueID);
305 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
306 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
307 const TargetMachine &TM) const {
308 unsigned Flags = getELFSectionFlags(Kind);
310 // If we have -ffunction-section or -fdata-section then we should emit the
311 // global value to a uniqued section specifically for it.
312 bool EmitUniqueSection = false;
313 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
315 EmitUniqueSection = TM.getFunctionSections();
317 EmitUniqueSection = TM.getDataSections();
319 EmitUniqueSection |= GV->hasComdat();
321 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
322 EmitUniqueSection, Flags, &NextUniqueID);
325 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
326 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
327 // If the function can be removed, produce a unique section so that
328 // the table doesn't prevent the removal.
329 const Comdat *C = F.getComdat();
330 bool EmitUniqueSection = TM.getFunctionSections() || C;
331 if (!EmitUniqueSection)
332 return ReadOnlySection;
334 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
335 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
339 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
340 bool UsesLabelDifference, const Function &F) const {
341 // We can always create relative relocations, so use another section
342 // that can be marked non-executable.
346 /// Given a mergeable constant with the specified size and relocation
347 /// information, return a section that it should be placed in.
348 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
349 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
350 if (Kind.isMergeableConst4() && MergeableConst4Section)
351 return MergeableConst4Section;
352 if (Kind.isMergeableConst8() && MergeableConst8Section)
353 return MergeableConst8Section;
354 if (Kind.isMergeableConst16() && MergeableConst16Section)
355 return MergeableConst16Section;
356 if (Kind.isReadOnly())
357 return ReadOnlySection;
359 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
360 return DataRelROSection;
363 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
364 bool IsCtor, unsigned Priority,
365 const MCSymbol *KeySym) {
368 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
369 StringRef COMDAT = KeySym ? KeySym->getName() : "";
372 Flags |= ELF::SHF_GROUP;
376 Type = ELF::SHT_INIT_ARRAY;
377 Name = ".init_array";
379 Type = ELF::SHT_FINI_ARRAY;
380 Name = ".fini_array";
382 if (Priority != 65535) {
384 Name += utostr(Priority);
387 // The default scheme is .ctor / .dtor, so we have to invert the priority
393 if (Priority != 65535) {
395 Name += utostr(65535 - Priority);
397 Type = ELF::SHT_PROGBITS;
400 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
403 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
404 unsigned Priority, const MCSymbol *KeySym) const {
405 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
409 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
410 unsigned Priority, const MCSymbol *KeySym) const {
411 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
416 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
417 UseInitArray = UseInitArray_;
421 StaticCtorSection = getContext().getELFSection(
422 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
423 StaticDtorSection = getContext().getELFSection(
424 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
427 //===----------------------------------------------------------------------===//
429 //===----------------------------------------------------------------------===//
431 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
432 : TargetLoweringObjectFile() {
433 SupportIndirectSymViaGOTPCRel = true;
436 /// emitModuleFlags - Perform code emission for module flags.
437 void TargetLoweringObjectFileMachO::
438 emitModuleFlags(MCStreamer &Streamer,
439 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
440 Mangler &Mang, const TargetMachine &TM) const {
441 unsigned VersionVal = 0;
442 unsigned ImageInfoFlags = 0;
443 MDNode *LinkerOptions = nullptr;
444 StringRef SectionVal;
446 for (ArrayRef<Module::ModuleFlagEntry>::iterator
447 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
448 const Module::ModuleFlagEntry &MFE = *i;
450 // Ignore flags with 'Require' behavior.
451 if (MFE.Behavior == Module::Require)
454 StringRef Key = MFE.Key->getString();
455 Metadata *Val = MFE.Val;
457 if (Key == "Objective-C Image Info Version") {
458 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
459 } else if (Key == "Objective-C Garbage Collection" ||
460 Key == "Objective-C GC Only" ||
461 Key == "Objective-C Is Simulated" ||
462 Key == "Objective-C Image Swift Version") {
463 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
464 } else if (Key == "Objective-C Image Info Section") {
465 SectionVal = cast<MDString>(Val)->getString();
466 } else if (Key == "Linker Options") {
467 LinkerOptions = cast<MDNode>(Val);
471 // Emit the linker options if present.
473 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
474 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
475 SmallVector<std::string, 4> StrOptions;
477 // Convert to strings.
478 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
479 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
480 StrOptions.push_back(MDOption->getString());
483 Streamer.EmitLinkerOptions(StrOptions);
487 // The section is mandatory. If we don't have it, then we don't have GC info.
488 if (SectionVal.empty()) return;
490 StringRef Segment, Section;
491 unsigned TAA = 0, StubSize = 0;
493 std::string ErrorCode =
494 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
495 TAA, TAAParsed, StubSize);
496 if (!ErrorCode.empty())
497 // If invalid, report the error with report_fatal_error.
498 report_fatal_error("Invalid section specifier '" + Section + "': " +
502 MCSectionMachO *S = getContext().getMachOSection(
503 Segment, Section, TAA, StubSize, SectionKind::getData());
504 Streamer.SwitchSection(S);
505 Streamer.EmitLabel(getContext().
506 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
507 Streamer.EmitIntValue(VersionVal, 4);
508 Streamer.EmitIntValue(ImageInfoFlags, 4);
509 Streamer.AddBlankLine();
512 static void checkMachOComdat(const GlobalValue *GV) {
513 const Comdat *C = GV->getComdat();
517 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
518 "' cannot be lowered.");
521 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
522 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
523 const TargetMachine &TM) const {
524 // Parse the section specifier and create it if valid.
525 StringRef Segment, Section;
526 unsigned TAA = 0, StubSize = 0;
529 checkMachOComdat(GV);
531 std::string ErrorCode =
532 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
533 TAA, TAAParsed, StubSize);
534 if (!ErrorCode.empty()) {
535 // If invalid, report the error with report_fatal_error.
536 report_fatal_error("Global variable '" + GV->getName() +
537 "' has an invalid section specifier '" +
538 GV->getSection() + "': " + ErrorCode + ".");
543 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
545 // If TAA wasn't set by ParseSectionSpecifier() above,
546 // use the value returned by getMachOSection() as a default.
548 TAA = S->getTypeAndAttributes();
550 // Okay, now that we got the section, verify that the TAA & StubSize agree.
551 // If the user declared multiple globals with different section flags, we need
552 // to reject it here.
553 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
554 // If invalid, report the error with report_fatal_error.
555 report_fatal_error("Global variable '" + GV->getName() +
556 "' section type or attributes does not match previous"
557 " section specifier");
563 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
564 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
565 const TargetMachine &TM) const {
566 checkMachOComdat(GV);
568 // Handle thread local data.
569 if (Kind.isThreadBSS()) return TLSBSSSection;
570 if (Kind.isThreadData()) return TLSDataSection;
573 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
575 // If this is weak/linkonce, put this in a coalescable section, either in text
576 // or data depending on if it is writable.
577 if (GV->isWeakForLinker()) {
578 if (Kind.isReadOnly())
579 return ConstTextCoalSection;
580 return DataCoalSection;
583 // FIXME: Alignment check should be handled by section classifier.
584 if (Kind.isMergeable1ByteCString() &&
585 GV->getParent()->getDataLayout().getPreferredAlignment(
586 cast<GlobalVariable>(GV)) < 32)
587 return CStringSection;
589 // Do not put 16-bit arrays in the UString section if they have an
590 // externally visible label, this runs into issues with certain linker
592 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
593 GV->getParent()->getDataLayout().getPreferredAlignment(
594 cast<GlobalVariable>(GV)) < 32)
595 return UStringSection;
597 // With MachO only variables whose corresponding symbol starts with 'l' or
598 // 'L' can be merged, so we only try merging GVs with private linkage.
599 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
600 if (Kind.isMergeableConst4())
601 return FourByteConstantSection;
602 if (Kind.isMergeableConst8())
603 return EightByteConstantSection;
604 if (Kind.isMergeableConst16())
605 return SixteenByteConstantSection;
608 // Otherwise, if it is readonly, but not something we can specially optimize,
609 // just drop it in .const.
610 if (Kind.isReadOnly())
611 return ReadOnlySection;
613 // If this is marked const, put it into a const section. But if the dynamic
614 // linker needs to write to it, put it in the data segment.
615 if (Kind.isReadOnlyWithRel())
616 return ConstDataSection;
618 // Put zero initialized globals with strong external linkage in the
619 // DATA, __common section with the .zerofill directive.
620 if (Kind.isBSSExtern())
621 return DataCommonSection;
623 // Put zero initialized globals with local linkage in __DATA,__bss directive
624 // with the .zerofill directive (aka .lcomm).
625 if (Kind.isBSSLocal())
626 return DataBSSSection;
628 // Otherwise, just drop the variable in the normal data section.
632 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
633 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
634 // If this constant requires a relocation, we have to put it in the data
635 // segment, not in the text segment.
636 if (Kind.isData() || Kind.isReadOnlyWithRel())
637 return ConstDataSection;
639 if (Kind.isMergeableConst4())
640 return FourByteConstantSection;
641 if (Kind.isMergeableConst8())
642 return EightByteConstantSection;
643 if (Kind.isMergeableConst16())
644 return SixteenByteConstantSection;
645 return ReadOnlySection; // .const
648 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
649 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
650 const TargetMachine &TM, MachineModuleInfo *MMI,
651 MCStreamer &Streamer) const {
652 // The mach-o version of this method defaults to returning a stub reference.
654 if (Encoding & DW_EH_PE_indirect) {
655 MachineModuleInfoMachO &MachOMMI =
656 MMI->getObjFileInfo<MachineModuleInfoMachO>();
659 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
661 // Add information about the stub reference to MachOMMI so that the stub
662 // gets emitted by the asmprinter.
663 MachineModuleInfoImpl::StubValueTy &StubSym =
664 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
665 MachOMMI.getGVStubEntry(SSym);
666 if (!StubSym.getPointer()) {
667 MCSymbol *Sym = TM.getSymbol(GV, Mang);
668 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
671 return TargetLoweringObjectFile::
672 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
673 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
676 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
680 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
681 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
682 MachineModuleInfo *MMI) const {
683 // The mach-o version of this method defaults to returning a stub reference.
684 MachineModuleInfoMachO &MachOMMI =
685 MMI->getObjFileInfo<MachineModuleInfoMachO>();
687 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
689 // Add information about the stub reference to MachOMMI so that the stub
690 // gets emitted by the asmprinter.
691 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
692 if (!StubSym.getPointer()) {
693 MCSymbol *Sym = TM.getSymbol(GV, Mang);
694 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
700 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
701 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
702 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
703 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
704 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
705 // through a non_lazy_ptr stub instead. One advantage is that it allows the
706 // computation of deltas to final external symbols. Example:
712 // .long _extgotequiv-_delta
714 // is transformed to:
717 // .long L_extfoo$non_lazy_ptr-(_delta+0)
719 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
720 // L_extfoo$non_lazy_ptr:
721 // .indirect_symbol _extfoo
724 MachineModuleInfoMachO &MachOMMI =
725 MMI->getObjFileInfo<MachineModuleInfoMachO>();
726 MCContext &Ctx = getContext();
728 // The offset must consider the original displacement from the base symbol
729 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
730 Offset = -MV.getConstant();
731 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
733 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
734 // non_lazy_ptr stubs.
735 SmallString<128> Name;
736 StringRef Suffix = "$non_lazy_ptr";
737 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
738 Name += Sym->getName();
740 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
742 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
743 if (!StubSym.getPointer())
744 StubSym = MachineModuleInfoImpl::
745 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
747 const MCExpr *BSymExpr =
748 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
750 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
753 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
756 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
757 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
760 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
761 const MCSection &Section) {
762 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
765 // If it is not dead stripped, it is safe to use private labels.
766 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
767 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
773 void TargetLoweringObjectFileMachO::getNameWithPrefix(
774 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
775 const TargetMachine &TM) const {
776 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
777 const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
778 bool CannotUsePrivateLabel =
779 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
780 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
783 //===----------------------------------------------------------------------===//
785 //===----------------------------------------------------------------------===//
788 getCOFFSectionFlags(SectionKind K) {
793 COFF::IMAGE_SCN_MEM_DISCARDABLE;
796 COFF::IMAGE_SCN_MEM_EXECUTE |
797 COFF::IMAGE_SCN_MEM_READ |
798 COFF::IMAGE_SCN_CNT_CODE;
801 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
802 COFF::IMAGE_SCN_MEM_READ |
803 COFF::IMAGE_SCN_MEM_WRITE;
804 else if (K.isThreadLocal())
806 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
807 COFF::IMAGE_SCN_MEM_READ |
808 COFF::IMAGE_SCN_MEM_WRITE;
809 else if (K.isReadOnly() || K.isReadOnlyWithRel())
811 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
812 COFF::IMAGE_SCN_MEM_READ;
813 else if (K.isWriteable())
815 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
816 COFF::IMAGE_SCN_MEM_READ |
817 COFF::IMAGE_SCN_MEM_WRITE;
822 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
823 const Comdat *C = GV->getComdat();
824 assert(C && "expected GV to have a Comdat!");
826 StringRef ComdatGVName = C->getName();
827 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
829 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
830 "' does not exist.");
832 if (ComdatGV->getComdat() != C)
833 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
834 "' is not a key for its COMDAT.");
839 static int getSelectionForCOFF(const GlobalValue *GV) {
840 if (const Comdat *C = GV->getComdat()) {
841 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
842 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
843 ComdatKey = GA->getBaseObject();
844 if (ComdatKey == GV) {
845 switch (C->getSelectionKind()) {
847 return COFF::IMAGE_COMDAT_SELECT_ANY;
848 case Comdat::ExactMatch:
849 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
850 case Comdat::Largest:
851 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
852 case Comdat::NoDuplicates:
853 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
854 case Comdat::SameSize:
855 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
858 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
864 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
865 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
866 const TargetMachine &TM) const {
868 unsigned Characteristics = getCOFFSectionFlags(Kind);
869 StringRef Name = GV->getSection();
870 StringRef COMDATSymName = "";
871 if (GV->hasComdat()) {
872 Selection = getSelectionForCOFF(GV);
873 const GlobalValue *ComdatGV;
874 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
875 ComdatGV = getComdatGVForCOFF(GV);
879 if (!ComdatGV->hasPrivateLinkage()) {
880 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
881 COMDATSymName = Sym->getName();
882 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
887 return getContext().getCOFFSection(Name,
894 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
899 if (Kind.isThreadLocal())
901 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
906 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
907 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
908 const TargetMachine &TM) const {
909 // If we have -ffunction-sections then we should emit the global value to a
910 // uniqued section specifically for it.
911 bool EmitUniquedSection;
913 EmitUniquedSection = TM.getFunctionSections();
915 EmitUniquedSection = TM.getDataSections();
917 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
918 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
919 unsigned Characteristics = getCOFFSectionFlags(Kind);
921 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
922 int Selection = getSelectionForCOFF(GV);
924 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
925 const GlobalValue *ComdatGV;
927 ComdatGV = getComdatGVForCOFF(GV);
931 if (!ComdatGV->hasPrivateLinkage()) {
932 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
933 StringRef COMDATSymName = Sym->getName();
934 return getContext().getCOFFSection(Name, Characteristics, Kind,
935 COMDATSymName, Selection);
937 SmallString<256> TmpData;
938 Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
939 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
947 if (Kind.isThreadLocal())
948 return TLSDataSection;
950 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
951 return ReadOnlySection;
953 // Note: we claim that common symbols are put in BSSSection, but they are
954 // really emitted with the magic .comm directive, which creates a symbol table
955 // entry but not a section.
956 if (Kind.isBSS() || Kind.isCommon())
962 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
963 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
964 const TargetMachine &TM) const {
965 bool CannotUsePrivateLabel = false;
966 if (GV->hasPrivateLinkage() &&
967 ((isa<Function>(GV) && TM.getFunctionSections()) ||
968 (isa<GlobalVariable>(GV) && TM.getDataSections())))
969 CannotUsePrivateLabel = true;
971 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
974 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
975 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
976 // If the function can be removed, produce a unique section so that
977 // the table doesn't prevent the removal.
978 const Comdat *C = F.getComdat();
979 bool EmitUniqueSection = TM.getFunctionSections() || C;
980 if (!EmitUniqueSection)
981 return ReadOnlySection;
983 // FIXME: we should produce a symbol for F instead.
984 if (F.hasPrivateLinkage())
985 return ReadOnlySection;
987 MCSymbol *Sym = TM.getSymbol(&F, Mang);
988 StringRef COMDATSymName = Sym->getName();
990 SectionKind Kind = SectionKind::getReadOnly();
991 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
992 unsigned Characteristics = getCOFFSectionFlags(Kind);
993 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
995 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
996 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
999 void TargetLoweringObjectFileCOFF::
1000 emitModuleFlags(MCStreamer &Streamer,
1001 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1002 Mangler &Mang, const TargetMachine &TM) const {
1003 MDNode *LinkerOptions = nullptr;
1005 // Look for the "Linker Options" flag, since it's the only one we support.
1006 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1007 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1008 const Module::ModuleFlagEntry &MFE = *i;
1009 StringRef Key = MFE.Key->getString();
1010 Metadata *Val = MFE.Val;
1011 if (Key == "Linker Options") {
1012 LinkerOptions = cast<MDNode>(Val);
1019 // Emit the linker options to the linker .drectve section. According to the
1020 // spec, this section is a space-separated string containing flags for linker.
1021 MCSection *Sec = getDrectveSection();
1022 Streamer.SwitchSection(Sec);
1023 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1024 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1025 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1026 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1027 // Lead with a space for consistency with our dllexport implementation.
1028 std::string Directive(" ");
1029 Directive.append(MDOption->getString());
1030 Streamer.EmitBytes(Directive);
1035 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1036 unsigned Priority, const MCSymbol *KeySym) const {
1037 return getContext().getAssociativeCOFFSection(
1038 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1041 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1042 unsigned Priority, const MCSymbol *KeySym) const {
1043 return getContext().getAssociativeCOFFSection(
1044 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
1047 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1048 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1049 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1052 const Triple &TT = getTargetTriple();
1054 if (TT.isKnownWindowsMSVCEnvironment())
1059 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1061 raw_string_ostream FlagOS(Flag);
1062 Mang.getNameWithPrefix(FlagOS, GV, false);
1064 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1065 OS << Flag.substr(1);
1069 Mang.getNameWithPrefix(OS, GV, false);
1072 if (!GV->getValueType()->isFunctionTy()) {
1073 if (TT.isKnownWindowsMSVCEnvironment())