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/Support/Dwarf.h"
35 #include "llvm/Support/ELF.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
42 using namespace dwarf;
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
49 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
50 MachineModuleInfo *MMI) const {
51 unsigned Encoding = getPersonalityEncoding();
52 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
53 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
54 TM.getSymbol(GV, Mang)->getName());
55 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
56 return TM.getSymbol(GV, Mang);
57 report_fatal_error("We do not support this DWARF encoding yet!");
60 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
61 const TargetMachine &TM,
62 const MCSymbol *Sym) const {
63 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
65 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
66 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
68 StringRef Prefix = ".data.";
69 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
70 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
71 const MCSection *Sec = getContext().getELFSection(NameData,
75 unsigned Size = TM.getDataLayout()->getPointerSize();
76 Streamer.SwitchSection(Sec);
77 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
78 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
79 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
80 Streamer.EmitELFSize(Label, E);
81 Streamer.EmitLabel(Label);
83 Streamer.EmitSymbolValue(Sym, Size);
86 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
87 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
88 const TargetMachine &TM, MachineModuleInfo *MMI,
89 MCStreamer &Streamer) const {
91 if (Encoding & dwarf::DW_EH_PE_indirect) {
92 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
94 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
96 // Add information about the stub reference to ELFMMI so that the stub
97 // gets emitted by the asmprinter.
98 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
99 if (!StubSym.getPointer()) {
100 MCSymbol *Sym = TM.getSymbol(GV, Mang);
101 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
104 return TargetLoweringObjectFile::
105 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
106 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
109 return TargetLoweringObjectFile::
110 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
114 getELFKindForNamedSection(StringRef Name, SectionKind K) {
115 // N.B.: The defaults used in here are no the same ones used in MC.
116 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
117 // both gas and MC will produce a section with no flags. Given
118 // section(".eh_frame") gcc will produce:
120 // .section .eh_frame,"a",@progbits
121 if (Name.empty() || Name[0] != '.') return K;
123 // Some lame default implementation based on some magic section names.
124 if (Name == ".bss" ||
125 Name.startswith(".bss.") ||
126 Name.startswith(".gnu.linkonce.b.") ||
127 Name.startswith(".llvm.linkonce.b.") ||
129 Name.startswith(".sbss.") ||
130 Name.startswith(".gnu.linkonce.sb.") ||
131 Name.startswith(".llvm.linkonce.sb."))
132 return SectionKind::getBSS();
134 if (Name == ".tdata" ||
135 Name.startswith(".tdata.") ||
136 Name.startswith(".gnu.linkonce.td.") ||
137 Name.startswith(".llvm.linkonce.td."))
138 return SectionKind::getThreadData();
140 if (Name == ".tbss" ||
141 Name.startswith(".tbss.") ||
142 Name.startswith(".gnu.linkonce.tb.") ||
143 Name.startswith(".llvm.linkonce.tb."))
144 return SectionKind::getThreadBSS();
150 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
152 if (Name == ".init_array")
153 return ELF::SHT_INIT_ARRAY;
155 if (Name == ".fini_array")
156 return ELF::SHT_FINI_ARRAY;
158 if (Name == ".preinit_array")
159 return ELF::SHT_PREINIT_ARRAY;
161 if (K.isBSS() || K.isThreadBSS())
162 return ELF::SHT_NOBITS;
164 return ELF::SHT_PROGBITS;
167 static unsigned getELFSectionFlags(SectionKind K) {
171 Flags |= ELF::SHF_ALLOC;
174 Flags |= ELF::SHF_EXECINSTR;
177 Flags |= ELF::SHF_WRITE;
179 if (K.isThreadLocal())
180 Flags |= ELF::SHF_TLS;
182 if (K.isMergeableCString() || K.isMergeableConst())
183 Flags |= ELF::SHF_MERGE;
185 if (K.isMergeableCString())
186 Flags |= ELF::SHF_STRINGS;
191 static const Comdat *getELFComdat(const GlobalValue *GV) {
192 const Comdat *C = GV->getComdat();
196 if (C->getSelectionKind() != Comdat::Any)
197 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
198 C->getName() + "' cannot be lowered.");
203 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
204 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
205 const TargetMachine &TM) const {
206 StringRef SectionName = GV->getSection();
208 // Infer section flags from the section name if we can.
209 Kind = getELFKindForNamedSection(SectionName, Kind);
211 StringRef Group = "";
212 unsigned Flags = getELFSectionFlags(Kind);
213 if (const Comdat *C = getELFComdat(GV)) {
214 Group = C->getName();
215 Flags |= ELF::SHF_GROUP;
217 return getContext().getELFSection(SectionName,
218 getELFSectionType(SectionName, Kind), Flags,
219 /*EntrySize=*/0, Group);
222 /// Return the section prefix name used by options FunctionsSections and
224 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
227 if (Kind.isReadOnly())
231 if (Kind.isThreadData())
233 if (Kind.isThreadBSS())
235 if (Kind.isDataNoRel())
237 if (Kind.isDataRelLocal())
238 return ".data.rel.local";
239 if (Kind.isDataRel())
241 if (Kind.isReadOnlyWithRelLocal())
242 return ".data.rel.ro.local";
243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
244 return ".data.rel.ro";
247 const MCSection *TargetLoweringObjectFileELF::
248 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
249 Mangler &Mang, const TargetMachine &TM) const {
250 unsigned Flags = getELFSectionFlags(Kind);
252 // If we have -ffunction-section or -fdata-section then we should emit the
253 // global value to a uniqued section specifically for it.
254 bool EmitUniqueSection = false;
255 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
257 EmitUniqueSection = TM.getFunctionSections();
259 EmitUniqueSection = TM.getDataSections();
261 EmitUniqueSection |= GV->hasComdat();
263 unsigned EntrySize = 0;
264 if (Kind.isMergeableCString()) {
265 if (Kind.isMergeable2ByteCString()) {
267 } else if (Kind.isMergeable4ByteCString()) {
271 assert(Kind.isMergeable1ByteCString() && "unknown string width");
273 } else if (Kind.isMergeableConst()) {
274 if (Kind.isMergeableConst4()) {
276 } else if (Kind.isMergeableConst8()) {
279 assert(Kind.isMergeableConst16() && "unknown data width");
284 StringRef Group = "";
285 if (const Comdat *C = getELFComdat(GV)) {
286 Flags |= ELF::SHF_GROUP;
287 Group = C->getName();
290 bool UniqueSectionNames = TM.getUniqueSectionNames();
291 SmallString<128> Name;
292 if (Kind.isMergeableCString()) {
293 // We also need alignment here.
294 // FIXME: this is getting the alignment of the character, not the
295 // alignment of the global!
297 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
299 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
300 Name = SizeSpec + utostr(Align);
301 } else if (Kind.isMergeableConst()) {
302 Name = ".rodata.cst";
303 Name += utostr(EntrySize);
305 Name = getSectionPrefixForGlobal(Kind);
308 if (EmitUniqueSection && UniqueSectionNames) {
310 TM.getNameWithPrefix(Name, GV, Mang, true);
312 return getContext().getELFSection(Name, getELFSectionType(Name, Kind), Flags,
314 EmitUniqueSection && !UniqueSectionNames);
317 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
318 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
319 // If the function can be removed, produce a unique section so that
320 // the table doesn't prevent the removal.
321 const Comdat *C = F.getComdat();
322 bool EmitUniqueSection = TM.getFunctionSections() || C;
323 if (!EmitUniqueSection)
324 return ReadOnlySection;
326 return SelectSectionForGlobal(&F, SectionKind::getReadOnly(), Mang, TM);
329 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
330 bool UsesLabelDifference, const Function &F) const {
331 // We can always create relative relocations, so use another section
332 // that can be marked non-executable.
336 /// getSectionForConstant - Given a mergeable constant with the
337 /// specified size and relocation information, return a section that it
338 /// should be placed in.
340 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
341 const Constant *C) const {
342 if (Kind.isMergeableConst4() && MergeableConst4Section)
343 return MergeableConst4Section;
344 if (Kind.isMergeableConst8() && MergeableConst8Section)
345 return MergeableConst8Section;
346 if (Kind.isMergeableConst16() && MergeableConst16Section)
347 return MergeableConst16Section;
348 if (Kind.isReadOnly())
349 return ReadOnlySection;
351 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
352 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
353 return DataRelROSection;
356 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
360 const MCSymbol *KeySym) {
363 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
364 StringRef COMDAT = KeySym ? KeySym->getName() : "";
367 Flags |= ELF::SHF_GROUP;
371 Type = ELF::SHT_INIT_ARRAY;
372 Name = ".init_array";
374 Type = ELF::SHT_FINI_ARRAY;
375 Name = ".fini_array";
377 if (Priority != 65535) {
379 Name += utostr(Priority);
382 // The default scheme is .ctor / .dtor, so we have to invert the priority
388 if (Priority != 65535) {
390 Name += utostr(65535 - Priority);
392 Type = ELF::SHT_PROGBITS;
395 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
398 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
399 unsigned Priority, const MCSymbol *KeySym) const {
400 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
404 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
405 unsigned Priority, const MCSymbol *KeySym) const {
406 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
411 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
412 UseInitArray = UseInitArray_;
416 StaticCtorSection = getContext().getELFSection(
417 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
418 StaticDtorSection = getContext().getELFSection(
419 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
422 //===----------------------------------------------------------------------===//
424 //===----------------------------------------------------------------------===//
426 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
427 /// option string. Returns StringRef() if the option does not specify a library.
428 StringRef TargetLoweringObjectFileMachO::
429 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
430 const char *LibCmd = "-l";
431 if (LinkerOption.startswith(LibCmd))
432 return LinkerOption.substr(strlen(LibCmd));
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 const MCSectionMachO *S =
503 getContext().getMachOSection(Segment, Section, TAA, StubSize,
504 SectionKind::getDataNoRel());
505 Streamer.SwitchSection(S);
506 Streamer.EmitLabel(getContext().
507 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
508 Streamer.EmitIntValue(VersionVal, 4);
509 Streamer.EmitIntValue(ImageInfoFlags, 4);
510 Streamer.AddBlankLine();
513 static void checkMachOComdat(const GlobalValue *GV) {
514 const Comdat *C = GV->getComdat();
518 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
519 "' cannot be lowered.");
522 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
523 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
524 const TargetMachine &TM) const {
525 // Parse the section specifier and create it if valid.
526 StringRef Segment, Section;
527 unsigned TAA = 0, StubSize = 0;
530 checkMachOComdat(GV);
532 std::string ErrorCode =
533 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
534 TAA, TAAParsed, StubSize);
535 if (!ErrorCode.empty()) {
536 // If invalid, report the error with report_fatal_error.
537 report_fatal_error("Global variable '" + GV->getName() +
538 "' has an invalid section specifier '" +
539 GV->getSection() + "': " + ErrorCode + ".");
543 const MCSectionMachO *S =
544 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
546 // If TAA wasn't set by ParseSectionSpecifier() above,
547 // use the value returned by getMachOSection() as a default.
549 TAA = S->getTypeAndAttributes();
551 // Okay, now that we got the section, verify that the TAA & StubSize agree.
552 // If the user declared multiple globals with different section flags, we need
553 // to reject it here.
554 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
555 // If invalid, report the error with report_fatal_error.
556 report_fatal_error("Global variable '" + GV->getName() +
557 "' section type or attributes does not match previous"
558 " section specifier");
564 const MCSection *TargetLoweringObjectFileMachO::
565 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
566 Mangler &Mang, const TargetMachine &TM) const {
567 checkMachOComdat(GV);
569 // Handle thread local data.
570 if (Kind.isThreadBSS()) return TLSBSSSection;
571 if (Kind.isThreadData()) return TLSDataSection;
574 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
576 // If this is weak/linkonce, put this in a coalescable section, either in text
577 // or data depending on if it is writable.
578 if (GV->isWeakForLinker()) {
579 if (Kind.isReadOnly())
580 return ConstTextCoalSection;
581 return DataCoalSection;
584 // FIXME: Alignment check should be handled by section classifier.
585 if (Kind.isMergeable1ByteCString() &&
586 TM.getDataLayout()->getPreferredAlignment(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 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
594 return UStringSection;
596 // With MachO only variables whose corresponding symbol starts with 'l' or
597 // 'L' can be merged, so we only try merging GVs with private linkage.
598 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
599 if (Kind.isMergeableConst4())
600 return FourByteConstantSection;
601 if (Kind.isMergeableConst8())
602 return EightByteConstantSection;
603 if (Kind.isMergeableConst16())
604 return SixteenByteConstantSection;
607 // Otherwise, if it is readonly, but not something we can specially optimize,
608 // just drop it in .const.
609 if (Kind.isReadOnly())
610 return ReadOnlySection;
612 // If this is marked const, put it into a const section. But if the dynamic
613 // linker needs to write to it, put it in the data segment.
614 if (Kind.isReadOnlyWithRel())
615 return ConstDataSection;
617 // Put zero initialized globals with strong external linkage in the
618 // DATA, __common section with the .zerofill directive.
619 if (Kind.isBSSExtern())
620 return DataCommonSection;
622 // Put zero initialized globals with local linkage in __DATA,__bss directive
623 // with the .zerofill directive (aka .lcomm).
624 if (Kind.isBSSLocal())
625 return DataBSSSection;
627 // Otherwise, just drop the variable in the normal data section.
632 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
633 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.isDataRel() || 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 //===----------------------------------------------------------------------===//
702 //===----------------------------------------------------------------------===//
705 getCOFFSectionFlags(SectionKind K) {
710 COFF::IMAGE_SCN_MEM_DISCARDABLE;
713 COFF::IMAGE_SCN_MEM_EXECUTE |
714 COFF::IMAGE_SCN_MEM_READ |
715 COFF::IMAGE_SCN_CNT_CODE;
718 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
719 COFF::IMAGE_SCN_MEM_READ |
720 COFF::IMAGE_SCN_MEM_WRITE;
721 else if (K.isThreadLocal())
723 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
724 COFF::IMAGE_SCN_MEM_READ |
725 COFF::IMAGE_SCN_MEM_WRITE;
726 else if (K.isReadOnly() || K.isReadOnlyWithRel())
728 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
729 COFF::IMAGE_SCN_MEM_READ;
730 else if (K.isWriteable())
732 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
733 COFF::IMAGE_SCN_MEM_READ |
734 COFF::IMAGE_SCN_MEM_WRITE;
739 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
740 const Comdat *C = GV->getComdat();
741 assert(C && "expected GV to have a Comdat!");
743 StringRef ComdatGVName = C->getName();
744 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
746 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
747 "' does not exist.");
749 if (ComdatGV->getComdat() != C)
750 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
751 "' is not a key for its COMDAT.");
756 static int getSelectionForCOFF(const GlobalValue *GV) {
757 if (const Comdat *C = GV->getComdat()) {
758 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
759 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
760 ComdatKey = GA->getBaseObject();
761 if (ComdatKey == GV) {
762 switch (C->getSelectionKind()) {
764 return COFF::IMAGE_COMDAT_SELECT_ANY;
765 case Comdat::ExactMatch:
766 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
767 case Comdat::Largest:
768 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
769 case Comdat::NoDuplicates:
770 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
771 case Comdat::SameSize:
772 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
775 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
777 } else if (GV->isWeakForLinker()) {
778 return COFF::IMAGE_COMDAT_SELECT_ANY;
783 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
784 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
785 const TargetMachine &TM) const {
787 unsigned Characteristics = getCOFFSectionFlags(Kind);
788 StringRef Name = GV->getSection();
789 StringRef COMDATSymName = "";
790 if (GV->hasComdat()) {
791 Selection = getSelectionForCOFF(GV);
792 const GlobalValue *ComdatGV;
793 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
794 ComdatGV = getComdatGVForCOFF(GV);
798 if (!ComdatGV->hasPrivateLinkage()) {
799 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
800 COMDATSymName = Sym->getName();
801 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
806 return getContext().getCOFFSection(Name,
813 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
818 if (Kind.isThreadLocal())
820 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
826 const MCSection *TargetLoweringObjectFileCOFF::
827 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
828 Mangler &Mang, const TargetMachine &TM) const {
829 // If we have -ffunction-sections then we should emit the global value to a
830 // uniqued section specifically for it.
831 bool EmitUniquedSection;
833 EmitUniquedSection = TM.getFunctionSections();
835 EmitUniquedSection = TM.getDataSections();
837 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
838 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
839 unsigned Characteristics = getCOFFSectionFlags(Kind);
841 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
842 int Selection = getSelectionForCOFF(GV);
844 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
845 const GlobalValue *ComdatGV;
847 ComdatGV = getComdatGVForCOFF(GV);
851 if (!ComdatGV->hasPrivateLinkage()) {
852 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
853 StringRef COMDATSymName = Sym->getName();
854 return getContext().getCOFFSection(Name, Characteristics, Kind,
855 COMDATSymName, Selection);
862 if (Kind.isThreadLocal())
863 return TLSDataSection;
865 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
866 return ReadOnlySection;
868 // Note: we claim that common symbols are put in BSSSection, but they are
869 // really emitted with the magic .comm directive, which creates a symbol table
870 // entry but not a section.
871 if (Kind.isBSS() || Kind.isCommon())
877 StringRef TargetLoweringObjectFileCOFF::
878 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
879 const char *LibCmd = "/DEFAULTLIB:";
880 if (LinkerOption.startswith(LibCmd))
881 return LinkerOption.substr(strlen(LibCmd));
885 void TargetLoweringObjectFileCOFF::
886 emitModuleFlags(MCStreamer &Streamer,
887 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
888 Mangler &Mang, const TargetMachine &TM) const {
889 MDNode *LinkerOptions = nullptr;
891 // Look for the "Linker Options" flag, since it's the only one we support.
892 for (ArrayRef<Module::ModuleFlagEntry>::iterator
893 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
894 const Module::ModuleFlagEntry &MFE = *i;
895 StringRef Key = MFE.Key->getString();
896 Metadata *Val = MFE.Val;
897 if (Key == "Linker Options") {
898 LinkerOptions = cast<MDNode>(Val);
905 // Emit the linker options to the linker .drectve section. According to the
906 // spec, this section is a space-separated string containing flags for linker.
907 const MCSection *Sec = getDrectveSection();
908 Streamer.SwitchSection(Sec);
909 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
910 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
911 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
912 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
913 // Lead with a space for consistency with our dllexport implementation.
914 std::string Directive(" ");
915 Directive.append(MDOption->getString());
916 Streamer.EmitBytes(Directive);
921 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
922 unsigned Priority, const MCSymbol *KeySym) const {
923 return getContext().getAssociativeCOFFSection(
924 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
927 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
928 unsigned Priority, const MCSymbol *KeySym) const {
929 return getContext().getAssociativeCOFFSection(
930 cast<MCSectionCOFF>(StaticDtorSection), KeySym);