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/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCValue.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/ELF.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
43 using namespace dwarf;
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
50 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
51 MachineModuleInfo *MMI) const {
52 unsigned Encoding = getPersonalityEncoding();
53 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
54 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
55 TM.getSymbol(GV, Mang)->getName());
56 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
57 return TM.getSymbol(GV, Mang);
58 report_fatal_error("We do not support this DWARF encoding yet!");
61 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
62 const TargetMachine &TM,
63 const MCSymbol *Sym) const {
64 SmallString<64> NameData("DW.ref.");
65 NameData += Sym->getName();
66 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
68 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
69 StringRef Prefix = ".data.";
70 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
71 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
72 const MCSection *Sec = getContext().getELFSection(NameData,
76 unsigned Size = TM.getDataLayout()->getPointerSize();
77 Streamer.SwitchSection(Sec);
78 Streamer.EmitValueToAlignment(TM.getDataLayout()->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 const 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 const MCSectionELF *selectELFSectionForGlobal(
249 MCContext &Ctx, const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
250 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags) {
251 unsigned EntrySize = 0;
252 if (Kind.isMergeableCString()) {
253 if (Kind.isMergeable2ByteCString()) {
255 } else if (Kind.isMergeable4ByteCString()) {
259 assert(Kind.isMergeable1ByteCString() && "unknown string width");
261 } else if (Kind.isMergeableConst()) {
262 if (Kind.isMergeableConst4()) {
264 } else if (Kind.isMergeableConst8()) {
267 assert(Kind.isMergeableConst16() && "unknown data width");
272 StringRef Group = "";
273 if (const Comdat *C = getELFComdat(GV)) {
274 Flags |= ELF::SHF_GROUP;
275 Group = C->getName();
278 bool UniqueSectionNames = TM.getUniqueSectionNames();
279 SmallString<128> Name;
280 if (Kind.isMergeableCString()) {
281 // We also need alignment here.
282 // FIXME: this is getting the alignment of the character, not the
283 // alignment of the global!
285 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
287 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
288 Name = SizeSpec + utostr(Align);
289 } else if (Kind.isMergeableConst()) {
290 Name = ".rodata.cst";
291 Name += utostr(EntrySize);
293 Name = getSectionPrefixForGlobal(Kind);
296 if (EmitUniqueSection && UniqueSectionNames) {
298 TM.getNameWithPrefix(Name, GV, Mang, true);
300 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
302 EmitUniqueSection && !UniqueSectionNames);
305 const 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);
325 const 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);
338 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
339 bool UsesLabelDifference, const Function &F) const {
340 // We can always create relative relocations, so use another section
341 // that can be marked non-executable.
345 /// getSectionForConstant - Given a mergeable constant with the
346 /// specified size and relocation information, return a section that it
347 /// should be placed in.
349 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
350 const Constant *C) const {
351 if (Kind.isMergeableConst4() && MergeableConst4Section)
352 return MergeableConst4Section;
353 if (Kind.isMergeableConst8() && MergeableConst8Section)
354 return MergeableConst8Section;
355 if (Kind.isMergeableConst16() && MergeableConst16Section)
356 return MergeableConst16Section;
357 if (Kind.isReadOnly())
358 return ReadOnlySection;
360 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
361 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
362 return DataRelROSection;
365 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
369 const MCSymbol *KeySym) {
372 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
373 StringRef COMDAT = KeySym ? KeySym->getName() : "";
376 Flags |= ELF::SHF_GROUP;
380 Type = ELF::SHT_INIT_ARRAY;
381 Name = ".init_array";
383 Type = ELF::SHT_FINI_ARRAY;
384 Name = ".fini_array";
386 if (Priority != 65535) {
388 Name += utostr(Priority);
391 // The default scheme is .ctor / .dtor, so we have to invert the priority
397 if (Priority != 65535) {
399 Name += utostr(65535 - Priority);
401 Type = ELF::SHT_PROGBITS;
404 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
407 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
408 unsigned Priority, const MCSymbol *KeySym) const {
409 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
413 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
414 unsigned Priority, const MCSymbol *KeySym) const {
415 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
420 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
421 UseInitArray = UseInitArray_;
425 StaticCtorSection = getContext().getELFSection(
426 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
427 StaticDtorSection = getContext().getELFSection(
428 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
431 //===----------------------------------------------------------------------===//
433 //===----------------------------------------------------------------------===//
435 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
436 : TargetLoweringObjectFile() {
437 SupportIndirectSymViaGOTPCRel = true;
440 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
441 /// option string. Returns StringRef() if the option does not specify a library.
442 StringRef TargetLoweringObjectFileMachO::
443 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
444 const char *LibCmd = "-l";
445 if (LinkerOption.startswith(LibCmd))
446 return LinkerOption.substr(strlen(LibCmd));
450 /// emitModuleFlags - Perform code emission for module flags.
451 void TargetLoweringObjectFileMachO::
452 emitModuleFlags(MCStreamer &Streamer,
453 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
454 Mangler &Mang, const TargetMachine &TM) const {
455 unsigned VersionVal = 0;
456 unsigned ImageInfoFlags = 0;
457 MDNode *LinkerOptions = nullptr;
458 StringRef SectionVal;
460 for (ArrayRef<Module::ModuleFlagEntry>::iterator
461 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
462 const Module::ModuleFlagEntry &MFE = *i;
464 // Ignore flags with 'Require' behavior.
465 if (MFE.Behavior == Module::Require)
468 StringRef Key = MFE.Key->getString();
469 Metadata *Val = MFE.Val;
471 if (Key == "Objective-C Image Info Version") {
472 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
473 } else if (Key == "Objective-C Garbage Collection" ||
474 Key == "Objective-C GC Only" ||
475 Key == "Objective-C Is Simulated" ||
476 Key == "Objective-C Image Swift Version") {
477 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
478 } else if (Key == "Objective-C Image Info Section") {
479 SectionVal = cast<MDString>(Val)->getString();
480 } else if (Key == "Linker Options") {
481 LinkerOptions = cast<MDNode>(Val);
485 // Emit the linker options if present.
487 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
488 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
489 SmallVector<std::string, 4> StrOptions;
491 // Convert to strings.
492 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
493 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
494 StrOptions.push_back(MDOption->getString());
497 Streamer.EmitLinkerOptions(StrOptions);
501 // The section is mandatory. If we don't have it, then we don't have GC info.
502 if (SectionVal.empty()) return;
504 StringRef Segment, Section;
505 unsigned TAA = 0, StubSize = 0;
507 std::string ErrorCode =
508 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
509 TAA, TAAParsed, StubSize);
510 if (!ErrorCode.empty())
511 // If invalid, report the error with report_fatal_error.
512 report_fatal_error("Invalid section specifier '" + Section + "': " +
516 const MCSectionMachO *S =
517 getContext().getMachOSection(Segment, Section, TAA, StubSize,
518 SectionKind::getDataNoRel());
519 Streamer.SwitchSection(S);
520 Streamer.EmitLabel(getContext().
521 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
522 Streamer.EmitIntValue(VersionVal, 4);
523 Streamer.EmitIntValue(ImageInfoFlags, 4);
524 Streamer.AddBlankLine();
527 static void checkMachOComdat(const GlobalValue *GV) {
528 const Comdat *C = GV->getComdat();
532 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
533 "' cannot be lowered.");
536 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
537 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
538 const TargetMachine &TM) const {
539 // Parse the section specifier and create it if valid.
540 StringRef Segment, Section;
541 unsigned TAA = 0, StubSize = 0;
544 checkMachOComdat(GV);
546 std::string ErrorCode =
547 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
548 TAA, TAAParsed, StubSize);
549 if (!ErrorCode.empty()) {
550 // If invalid, report the error with report_fatal_error.
551 report_fatal_error("Global variable '" + GV->getName() +
552 "' has an invalid section specifier '" +
553 GV->getSection() + "': " + ErrorCode + ".");
557 const MCSectionMachO *S =
558 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
560 // If TAA wasn't set by ParseSectionSpecifier() above,
561 // use the value returned by getMachOSection() as a default.
563 TAA = S->getTypeAndAttributes();
565 // Okay, now that we got the section, verify that the TAA & StubSize agree.
566 // If the user declared multiple globals with different section flags, we need
567 // to reject it here.
568 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
569 // If invalid, report the error with report_fatal_error.
570 report_fatal_error("Global variable '" + GV->getName() +
571 "' section type or attributes does not match previous"
572 " section specifier");
578 const MCSection *TargetLoweringObjectFileMachO::
579 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
580 Mangler &Mang, const TargetMachine &TM) const {
581 checkMachOComdat(GV);
583 // Handle thread local data.
584 if (Kind.isThreadBSS()) return TLSBSSSection;
585 if (Kind.isThreadData()) return TLSDataSection;
588 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
590 // If this is weak/linkonce, put this in a coalescable section, either in text
591 // or data depending on if it is writable.
592 if (GV->isWeakForLinker()) {
593 if (Kind.isReadOnly())
594 return ConstTextCoalSection;
595 return DataCoalSection;
598 // FIXME: Alignment check should be handled by section classifier.
599 if (Kind.isMergeable1ByteCString() &&
600 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
601 return CStringSection;
603 // Do not put 16-bit arrays in the UString section if they have an
604 // externally visible label, this runs into issues with certain linker
606 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
607 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
608 return UStringSection;
610 // With MachO only variables whose corresponding symbol starts with 'l' or
611 // 'L' can be merged, so we only try merging GVs with private linkage.
612 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
613 if (Kind.isMergeableConst4())
614 return FourByteConstantSection;
615 if (Kind.isMergeableConst8())
616 return EightByteConstantSection;
617 if (Kind.isMergeableConst16())
618 return SixteenByteConstantSection;
621 // Otherwise, if it is readonly, but not something we can specially optimize,
622 // just drop it in .const.
623 if (Kind.isReadOnly())
624 return ReadOnlySection;
626 // If this is marked const, put it into a const section. But if the dynamic
627 // linker needs to write to it, put it in the data segment.
628 if (Kind.isReadOnlyWithRel())
629 return ConstDataSection;
631 // Put zero initialized globals with strong external linkage in the
632 // DATA, __common section with the .zerofill directive.
633 if (Kind.isBSSExtern())
634 return DataCommonSection;
636 // Put zero initialized globals with local linkage in __DATA,__bss directive
637 // with the .zerofill directive (aka .lcomm).
638 if (Kind.isBSSLocal())
639 return DataBSSSection;
641 // Otherwise, just drop the variable in the normal data section.
646 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
647 const Constant *C) const {
648 // If this constant requires a relocation, we have to put it in the data
649 // segment, not in the text segment.
650 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
651 return ConstDataSection;
653 if (Kind.isMergeableConst4())
654 return FourByteConstantSection;
655 if (Kind.isMergeableConst8())
656 return EightByteConstantSection;
657 if (Kind.isMergeableConst16())
658 return SixteenByteConstantSection;
659 return ReadOnlySection; // .const
662 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
663 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
664 const TargetMachine &TM, MachineModuleInfo *MMI,
665 MCStreamer &Streamer) const {
666 // The mach-o version of this method defaults to returning a stub reference.
668 if (Encoding & DW_EH_PE_indirect) {
669 MachineModuleInfoMachO &MachOMMI =
670 MMI->getObjFileInfo<MachineModuleInfoMachO>();
673 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
675 // Add information about the stub reference to MachOMMI so that the stub
676 // gets emitted by the asmprinter.
677 MachineModuleInfoImpl::StubValueTy &StubSym =
678 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
679 MachOMMI.getGVStubEntry(SSym);
680 if (!StubSym.getPointer()) {
681 MCSymbol *Sym = TM.getSymbol(GV, Mang);
682 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
685 return TargetLoweringObjectFile::
686 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
687 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
690 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
694 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
695 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
696 MachineModuleInfo *MMI) const {
697 // The mach-o version of this method defaults to returning a stub reference.
698 MachineModuleInfoMachO &MachOMMI =
699 MMI->getObjFileInfo<MachineModuleInfoMachO>();
701 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
703 // Add information about the stub reference to MachOMMI so that the stub
704 // gets emitted by the asmprinter.
705 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
706 if (!StubSym.getPointer()) {
707 MCSymbol *Sym = TM.getSymbol(GV, Mang);
708 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
714 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
715 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
716 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
717 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
718 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
719 // through a non_lazy_ptr stub instead. One advantage is that it allows the
720 // computation of deltas to final external symbols. Example:
726 // .long _extgotequiv-_delta
728 // is transformed to:
731 // .long L_extfoo$non_lazy_ptr-(_delta+0)
733 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
734 // L_extfoo$non_lazy_ptr:
735 // .indirect_symbol _extfoo
738 MachineModuleInfoMachO &MachOMMI =
739 MMI->getObjFileInfo<MachineModuleInfoMachO>();
740 MCContext &Ctx = getContext();
742 // The offset must consider the original displacement from the base symbol
743 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
744 Offset = -MV.getConstant();
745 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
747 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
748 // non_lazy_ptr stubs.
749 SmallString<128> Name;
750 StringRef Suffix = "$non_lazy_ptr";
751 Name += DL->getPrivateGlobalPrefix();
752 Name += Sym->getName();
754 MCSymbol *Stub = Ctx.GetOrCreateSymbol(Name);
756 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
757 if (!StubSym.getPointer())
758 StubSym = MachineModuleInfoImpl::
759 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
761 const MCExpr *BSymExpr =
762 MCSymbolRefExpr::Create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
764 MCSymbolRefExpr::Create(Stub, MCSymbolRefExpr::VK_None, Ctx);
767 return MCBinaryExpr::CreateSub(LHS, BSymExpr, Ctx);
770 MCBinaryExpr::CreateAdd(BSymExpr, MCConstantExpr::Create(Offset, Ctx), Ctx);
771 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
774 //===----------------------------------------------------------------------===//
776 //===----------------------------------------------------------------------===//
779 getCOFFSectionFlags(SectionKind K) {
784 COFF::IMAGE_SCN_MEM_DISCARDABLE;
787 COFF::IMAGE_SCN_MEM_EXECUTE |
788 COFF::IMAGE_SCN_MEM_READ |
789 COFF::IMAGE_SCN_CNT_CODE;
792 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
793 COFF::IMAGE_SCN_MEM_READ |
794 COFF::IMAGE_SCN_MEM_WRITE;
795 else if (K.isThreadLocal())
797 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
798 COFF::IMAGE_SCN_MEM_READ |
799 COFF::IMAGE_SCN_MEM_WRITE;
800 else if (K.isReadOnly() || K.isReadOnlyWithRel())
802 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
803 COFF::IMAGE_SCN_MEM_READ;
804 else if (K.isWriteable())
806 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
807 COFF::IMAGE_SCN_MEM_READ |
808 COFF::IMAGE_SCN_MEM_WRITE;
813 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
814 const Comdat *C = GV->getComdat();
815 assert(C && "expected GV to have a Comdat!");
817 StringRef ComdatGVName = C->getName();
818 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
820 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
821 "' does not exist.");
823 if (ComdatGV->getComdat() != C)
824 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
825 "' is not a key for its COMDAT.");
830 static int getSelectionForCOFF(const GlobalValue *GV) {
831 if (const Comdat *C = GV->getComdat()) {
832 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
833 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
834 ComdatKey = GA->getBaseObject();
835 if (ComdatKey == GV) {
836 switch (C->getSelectionKind()) {
838 return COFF::IMAGE_COMDAT_SELECT_ANY;
839 case Comdat::ExactMatch:
840 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
841 case Comdat::Largest:
842 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
843 case Comdat::NoDuplicates:
844 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
845 case Comdat::SameSize:
846 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
849 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
851 } else if (GV->isWeakForLinker()) {
852 return COFF::IMAGE_COMDAT_SELECT_ANY;
857 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
858 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
859 const TargetMachine &TM) const {
861 unsigned Characteristics = getCOFFSectionFlags(Kind);
862 StringRef Name = GV->getSection();
863 StringRef COMDATSymName = "";
864 if (GV->hasComdat()) {
865 Selection = getSelectionForCOFF(GV);
866 const GlobalValue *ComdatGV;
867 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
868 ComdatGV = getComdatGVForCOFF(GV);
872 if (!ComdatGV->hasPrivateLinkage()) {
873 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
874 COMDATSymName = Sym->getName();
875 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
880 return getContext().getCOFFSection(Name,
887 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
892 if (Kind.isThreadLocal())
894 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
900 const MCSection *TargetLoweringObjectFileCOFF::
901 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
902 Mangler &Mang, const TargetMachine &TM) const {
903 // If we have -ffunction-sections then we should emit the global value to a
904 // uniqued section specifically for it.
905 bool EmitUniquedSection;
907 EmitUniquedSection = TM.getFunctionSections();
909 EmitUniquedSection = TM.getDataSections();
911 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
912 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
913 unsigned Characteristics = getCOFFSectionFlags(Kind);
915 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
916 int Selection = getSelectionForCOFF(GV);
918 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
919 const GlobalValue *ComdatGV;
921 ComdatGV = getComdatGVForCOFF(GV);
925 if (!ComdatGV->hasPrivateLinkage()) {
926 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
927 StringRef COMDATSymName = Sym->getName();
928 return getContext().getCOFFSection(Name, Characteristics, Kind,
929 COMDATSymName, Selection);
936 if (Kind.isThreadLocal())
937 return TLSDataSection;
939 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
940 return ReadOnlySection;
942 // Note: we claim that common symbols are put in BSSSection, but they are
943 // really emitted with the magic .comm directive, which creates a symbol table
944 // entry but not a section.
945 if (Kind.isBSS() || Kind.isCommon())
951 StringRef TargetLoweringObjectFileCOFF::
952 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
953 const char *LibCmd = "/DEFAULTLIB:";
954 if (LinkerOption.startswith(LibCmd))
955 return LinkerOption.substr(strlen(LibCmd));
959 void TargetLoweringObjectFileCOFF::
960 emitModuleFlags(MCStreamer &Streamer,
961 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
962 Mangler &Mang, const TargetMachine &TM) const {
963 MDNode *LinkerOptions = nullptr;
965 // Look for the "Linker Options" flag, since it's the only one we support.
966 for (ArrayRef<Module::ModuleFlagEntry>::iterator
967 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
968 const Module::ModuleFlagEntry &MFE = *i;
969 StringRef Key = MFE.Key->getString();
970 Metadata *Val = MFE.Val;
971 if (Key == "Linker Options") {
972 LinkerOptions = cast<MDNode>(Val);
979 // Emit the linker options to the linker .drectve section. According to the
980 // spec, this section is a space-separated string containing flags for linker.
981 const MCSection *Sec = getDrectveSection();
982 Streamer.SwitchSection(Sec);
983 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
984 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
985 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
986 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
987 // Lead with a space for consistency with our dllexport implementation.
988 std::string Directive(" ");
989 Directive.append(MDOption->getString());
990 Streamer.EmitBytes(Directive);
995 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
996 unsigned Priority, const MCSymbol *KeySym) const {
997 return getContext().getAssociativeCOFFSection(
998 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1001 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1002 unsigned Priority, const MCSymbol *KeySym) const {
1003 return getContext().getAssociativeCOFFSection(
1004 cast<MCSectionCOFF>(StaticDtorSection), KeySym);