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 *
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!
287 TM.getDataLayout()->getPreferredAlignment(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 const 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 const 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 /// getSectionForConstant - Given a mergeable constant with the
353 /// specified size and relocation information, return a section that it
354 /// should be placed in.
356 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
357 const Constant *C) const {
358 if (Kind.isMergeableConst4() && MergeableConst4Section)
359 return MergeableConst4Section;
360 if (Kind.isMergeableConst8() && MergeableConst8Section)
361 return MergeableConst8Section;
362 if (Kind.isMergeableConst16() && MergeableConst16Section)
363 return MergeableConst16Section;
364 if (Kind.isReadOnly())
365 return ReadOnlySection;
367 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
368 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
369 return DataRelROSection;
372 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
376 const MCSymbol *KeySym) {
379 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
380 StringRef COMDAT = KeySym ? KeySym->getName() : "";
383 Flags |= ELF::SHF_GROUP;
387 Type = ELF::SHT_INIT_ARRAY;
388 Name = ".init_array";
390 Type = ELF::SHT_FINI_ARRAY;
391 Name = ".fini_array";
393 if (Priority != 65535) {
395 Name += utostr(Priority);
398 // The default scheme is .ctor / .dtor, so we have to invert the priority
404 if (Priority != 65535) {
406 Name += utostr(65535 - Priority);
408 Type = ELF::SHT_PROGBITS;
411 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
414 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
415 unsigned Priority, const MCSymbol *KeySym) const {
416 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
420 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
421 unsigned Priority, const MCSymbol *KeySym) const {
422 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
427 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
428 UseInitArray = UseInitArray_;
432 StaticCtorSection = getContext().getELFSection(
433 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
434 StaticDtorSection = getContext().getELFSection(
435 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
438 //===----------------------------------------------------------------------===//
440 //===----------------------------------------------------------------------===//
442 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
443 : TargetLoweringObjectFile() {
444 SupportIndirectSymViaGOTPCRel = true;
447 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
448 /// option string. Returns StringRef() if the option does not specify a library.
449 StringRef TargetLoweringObjectFileMachO::
450 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
451 const char *LibCmd = "-l";
452 if (LinkerOption.startswith(LibCmd))
453 return LinkerOption.substr(strlen(LibCmd));
457 /// emitModuleFlags - Perform code emission for module flags.
458 void TargetLoweringObjectFileMachO::
459 emitModuleFlags(MCStreamer &Streamer,
460 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
461 Mangler &Mang, const TargetMachine &TM) const {
462 unsigned VersionVal = 0;
463 unsigned ImageInfoFlags = 0;
464 MDNode *LinkerOptions = nullptr;
465 StringRef SectionVal;
467 for (ArrayRef<Module::ModuleFlagEntry>::iterator
468 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
469 const Module::ModuleFlagEntry &MFE = *i;
471 // Ignore flags with 'Require' behavior.
472 if (MFE.Behavior == Module::Require)
475 StringRef Key = MFE.Key->getString();
476 Metadata *Val = MFE.Val;
478 if (Key == "Objective-C Image Info Version") {
479 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
480 } else if (Key == "Objective-C Garbage Collection" ||
481 Key == "Objective-C GC Only" ||
482 Key == "Objective-C Is Simulated" ||
483 Key == "Objective-C Image Swift Version") {
484 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
485 } else if (Key == "Objective-C Image Info Section") {
486 SectionVal = cast<MDString>(Val)->getString();
487 } else if (Key == "Linker Options") {
488 LinkerOptions = cast<MDNode>(Val);
492 // Emit the linker options if present.
494 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
495 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
496 SmallVector<std::string, 4> StrOptions;
498 // Convert to strings.
499 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
500 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
501 StrOptions.push_back(MDOption->getString());
504 Streamer.EmitLinkerOptions(StrOptions);
508 // The section is mandatory. If we don't have it, then we don't have GC info.
509 if (SectionVal.empty()) return;
511 StringRef Segment, Section;
512 unsigned TAA = 0, StubSize = 0;
514 std::string ErrorCode =
515 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
516 TAA, TAAParsed, StubSize);
517 if (!ErrorCode.empty())
518 // If invalid, report the error with report_fatal_error.
519 report_fatal_error("Invalid section specifier '" + Section + "': " +
523 const MCSectionMachO *S =
524 getContext().getMachOSection(Segment, Section, TAA, StubSize,
525 SectionKind::getDataNoRel());
526 Streamer.SwitchSection(S);
527 Streamer.EmitLabel(getContext().
528 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
529 Streamer.EmitIntValue(VersionVal, 4);
530 Streamer.EmitIntValue(ImageInfoFlags, 4);
531 Streamer.AddBlankLine();
534 static void checkMachOComdat(const GlobalValue *GV) {
535 const Comdat *C = GV->getComdat();
539 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
540 "' cannot be lowered.");
543 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
544 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
545 const TargetMachine &TM) const {
546 // Parse the section specifier and create it if valid.
547 StringRef Segment, Section;
548 unsigned TAA = 0, StubSize = 0;
551 checkMachOComdat(GV);
553 std::string ErrorCode =
554 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
555 TAA, TAAParsed, StubSize);
556 if (!ErrorCode.empty()) {
557 // If invalid, report the error with report_fatal_error.
558 report_fatal_error("Global variable '" + GV->getName() +
559 "' has an invalid section specifier '" +
560 GV->getSection() + "': " + ErrorCode + ".");
564 const MCSectionMachO *S =
565 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
567 // If TAA wasn't set by ParseSectionSpecifier() above,
568 // use the value returned by getMachOSection() as a default.
570 TAA = S->getTypeAndAttributes();
572 // Okay, now that we got the section, verify that the TAA & StubSize agree.
573 // If the user declared multiple globals with different section flags, we need
574 // to reject it here.
575 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
576 // If invalid, report the error with report_fatal_error.
577 report_fatal_error("Global variable '" + GV->getName() +
578 "' section type or attributes does not match previous"
579 " section specifier");
585 const MCSection *TargetLoweringObjectFileMachO::
586 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
587 Mangler &Mang, const TargetMachine &TM) const {
588 checkMachOComdat(GV);
590 // Handle thread local data.
591 if (Kind.isThreadBSS()) return TLSBSSSection;
592 if (Kind.isThreadData()) return TLSDataSection;
595 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
597 // If this is weak/linkonce, put this in a coalescable section, either in text
598 // or data depending on if it is writable.
599 if (GV->isWeakForLinker()) {
600 if (Kind.isReadOnly())
601 return ConstTextCoalSection;
602 return DataCoalSection;
605 // FIXME: Alignment check should be handled by section classifier.
606 if (Kind.isMergeable1ByteCString() &&
607 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
608 return CStringSection;
610 // Do not put 16-bit arrays in the UString section if they have an
611 // externally visible label, this runs into issues with certain linker
613 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
614 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
615 return UStringSection;
617 // With MachO only variables whose corresponding symbol starts with 'l' or
618 // 'L' can be merged, so we only try merging GVs with private linkage.
619 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
620 if (Kind.isMergeableConst4())
621 return FourByteConstantSection;
622 if (Kind.isMergeableConst8())
623 return EightByteConstantSection;
624 if (Kind.isMergeableConst16())
625 return SixteenByteConstantSection;
628 // Otherwise, if it is readonly, but not something we can specially optimize,
629 // just drop it in .const.
630 if (Kind.isReadOnly())
631 return ReadOnlySection;
633 // If this is marked const, put it into a const section. But if the dynamic
634 // linker needs to write to it, put it in the data segment.
635 if (Kind.isReadOnlyWithRel())
636 return ConstDataSection;
638 // Put zero initialized globals with strong external linkage in the
639 // DATA, __common section with the .zerofill directive.
640 if (Kind.isBSSExtern())
641 return DataCommonSection;
643 // Put zero initialized globals with local linkage in __DATA,__bss directive
644 // with the .zerofill directive (aka .lcomm).
645 if (Kind.isBSSLocal())
646 return DataBSSSection;
648 // Otherwise, just drop the variable in the normal data section.
653 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
654 const Constant *C) const {
655 // If this constant requires a relocation, we have to put it in the data
656 // segment, not in the text segment.
657 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
658 return ConstDataSection;
660 if (Kind.isMergeableConst4())
661 return FourByteConstantSection;
662 if (Kind.isMergeableConst8())
663 return EightByteConstantSection;
664 if (Kind.isMergeableConst16())
665 return SixteenByteConstantSection;
666 return ReadOnlySection; // .const
669 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
670 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
671 const TargetMachine &TM, MachineModuleInfo *MMI,
672 MCStreamer &Streamer) const {
673 // The mach-o version of this method defaults to returning a stub reference.
675 if (Encoding & DW_EH_PE_indirect) {
676 MachineModuleInfoMachO &MachOMMI =
677 MMI->getObjFileInfo<MachineModuleInfoMachO>();
680 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
682 // Add information about the stub reference to MachOMMI so that the stub
683 // gets emitted by the asmprinter.
684 MachineModuleInfoImpl::StubValueTy &StubSym =
685 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
686 MachOMMI.getGVStubEntry(SSym);
687 if (!StubSym.getPointer()) {
688 MCSymbol *Sym = TM.getSymbol(GV, Mang);
689 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
692 return TargetLoweringObjectFile::
693 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
694 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
697 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
701 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
702 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
703 MachineModuleInfo *MMI) const {
704 // The mach-o version of this method defaults to returning a stub reference.
705 MachineModuleInfoMachO &MachOMMI =
706 MMI->getObjFileInfo<MachineModuleInfoMachO>();
708 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
710 // Add information about the stub reference to MachOMMI so that the stub
711 // gets emitted by the asmprinter.
712 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
713 if (!StubSym.getPointer()) {
714 MCSymbol *Sym = TM.getSymbol(GV, Mang);
715 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
721 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
722 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
723 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
724 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
725 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
726 // through a non_lazy_ptr stub instead. One advantage is that it allows the
727 // computation of deltas to final external symbols. Example:
733 // .long _extgotequiv-_delta
735 // is transformed to:
738 // .long L_extfoo$non_lazy_ptr-(_delta+0)
740 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
741 // L_extfoo$non_lazy_ptr:
742 // .indirect_symbol _extfoo
745 MachineModuleInfoMachO &MachOMMI =
746 MMI->getObjFileInfo<MachineModuleInfoMachO>();
747 MCContext &Ctx = getContext();
749 // The offset must consider the original displacement from the base symbol
750 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
751 Offset = -MV.getConstant();
752 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
754 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
755 // non_lazy_ptr stubs.
756 SmallString<128> Name;
757 StringRef Suffix = "$non_lazy_ptr";
758 Name += DL->getPrivateGlobalPrefix();
759 Name += Sym->getName();
761 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
763 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
764 if (!StubSym.getPointer())
765 StubSym = MachineModuleInfoImpl::
766 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
768 const MCExpr *BSymExpr =
769 MCSymbolRefExpr::Create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
771 MCSymbolRefExpr::Create(Stub, MCSymbolRefExpr::VK_None, Ctx);
774 return MCBinaryExpr::CreateSub(LHS, BSymExpr, Ctx);
777 MCBinaryExpr::CreateAdd(BSymExpr, MCConstantExpr::Create(Offset, Ctx), Ctx);
778 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
781 //===----------------------------------------------------------------------===//
783 //===----------------------------------------------------------------------===//
786 getCOFFSectionFlags(SectionKind K) {
791 COFF::IMAGE_SCN_MEM_DISCARDABLE;
794 COFF::IMAGE_SCN_MEM_EXECUTE |
795 COFF::IMAGE_SCN_MEM_READ |
796 COFF::IMAGE_SCN_CNT_CODE;
799 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
800 COFF::IMAGE_SCN_MEM_READ |
801 COFF::IMAGE_SCN_MEM_WRITE;
802 else if (K.isThreadLocal())
804 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
805 COFF::IMAGE_SCN_MEM_READ |
806 COFF::IMAGE_SCN_MEM_WRITE;
807 else if (K.isReadOnly() || K.isReadOnlyWithRel())
809 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
810 COFF::IMAGE_SCN_MEM_READ;
811 else if (K.isWriteable())
813 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
814 COFF::IMAGE_SCN_MEM_READ |
815 COFF::IMAGE_SCN_MEM_WRITE;
820 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
821 const Comdat *C = GV->getComdat();
822 assert(C && "expected GV to have a Comdat!");
824 StringRef ComdatGVName = C->getName();
825 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
827 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
828 "' does not exist.");
830 if (ComdatGV->getComdat() != C)
831 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
832 "' is not a key for its COMDAT.");
837 static int getSelectionForCOFF(const GlobalValue *GV) {
838 if (const Comdat *C = GV->getComdat()) {
839 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
840 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
841 ComdatKey = GA->getBaseObject();
842 if (ComdatKey == GV) {
843 switch (C->getSelectionKind()) {
845 return COFF::IMAGE_COMDAT_SELECT_ANY;
846 case Comdat::ExactMatch:
847 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
848 case Comdat::Largest:
849 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
850 case Comdat::NoDuplicates:
851 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
852 case Comdat::SameSize:
853 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
856 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
858 } else if (GV->isWeakForLinker()) {
859 return COFF::IMAGE_COMDAT_SELECT_ANY;
864 const 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())
907 const MCSection *TargetLoweringObjectFileCOFF::
908 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
909 Mangler &Mang, const TargetMachine &TM) const {
910 // If we have -ffunction-sections then we should emit the global value to a
911 // uniqued section specifically for it.
912 bool EmitUniquedSection;
914 EmitUniquedSection = TM.getFunctionSections();
916 EmitUniquedSection = TM.getDataSections();
918 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
919 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
920 unsigned Characteristics = getCOFFSectionFlags(Kind);
922 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
923 int Selection = getSelectionForCOFF(GV);
925 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
926 const GlobalValue *ComdatGV;
928 ComdatGV = getComdatGVForCOFF(GV);
932 if (!ComdatGV->hasPrivateLinkage()) {
933 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
934 StringRef COMDATSymName = Sym->getName();
935 return getContext().getCOFFSection(Name, Characteristics, Kind,
936 COMDATSymName, Selection);
938 SmallString<256> TmpData;
939 getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
940 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
948 if (Kind.isThreadLocal())
949 return TLSDataSection;
951 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
952 return ReadOnlySection;
954 // Note: we claim that common symbols are put in BSSSection, but they are
955 // really emitted with the magic .comm directive, which creates a symbol table
956 // entry but not a section.
957 if (Kind.isBSS() || Kind.isCommon())
963 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
964 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
965 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
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 const 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 StringRef TargetLoweringObjectFileCOFF::
1000 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
1001 const char *LibCmd = "/DEFAULTLIB:";
1002 if (LinkerOption.startswith(LibCmd))
1003 return LinkerOption.substr(strlen(LibCmd));
1007 void TargetLoweringObjectFileCOFF::
1008 emitModuleFlags(MCStreamer &Streamer,
1009 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1010 Mangler &Mang, const TargetMachine &TM) const {
1011 MDNode *LinkerOptions = nullptr;
1013 // Look for the "Linker Options" flag, since it's the only one we support.
1014 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1015 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1016 const Module::ModuleFlagEntry &MFE = *i;
1017 StringRef Key = MFE.Key->getString();
1018 Metadata *Val = MFE.Val;
1019 if (Key == "Linker Options") {
1020 LinkerOptions = cast<MDNode>(Val);
1027 // Emit the linker options to the linker .drectve section. According to the
1028 // spec, this section is a space-separated string containing flags for linker.
1029 const MCSection *Sec = getDrectveSection();
1030 Streamer.SwitchSection(Sec);
1031 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1032 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1033 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1034 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1035 // Lead with a space for consistency with our dllexport implementation.
1036 std::string Directive(" ");
1037 Directive.append(MDOption->getString());
1038 Streamer.EmitBytes(Directive);
1043 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1044 unsigned Priority, const MCSymbol *KeySym) const {
1045 return getContext().getAssociativeCOFFSection(
1046 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1049 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1050 unsigned Priority, const MCSymbol *KeySym) const {
1051 return getContext().getAssociativeCOFFSection(
1052 cast<MCSectionCOFF>(StaticDtorSection), KeySym);