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,
74 SectionKind::getDataRel(),
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;
170 getELFSectionFlags(SectionKind K) {
174 Flags |= ELF::SHF_ALLOC;
177 Flags |= ELF::SHF_EXECINSTR;
180 Flags |= ELF::SHF_WRITE;
182 if (K.isThreadLocal())
183 Flags |= ELF::SHF_TLS;
185 // K.isMergeableConst() is left out to honour PR4650
186 if (K.isMergeableCString() || K.isMergeableConst4() ||
187 K.isMergeableConst8() || K.isMergeableConst16())
188 Flags |= ELF::SHF_MERGE;
190 if (K.isMergeableCString())
191 Flags |= ELF::SHF_STRINGS;
196 static const Comdat *getELFComdat(const GlobalValue *GV) {
197 const Comdat *C = GV->getComdat();
201 if (C->getSelectionKind() != Comdat::Any)
202 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
203 C->getName() + "' cannot be lowered.");
208 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
209 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
210 const TargetMachine &TM) const {
211 StringRef SectionName = GV->getSection();
213 // Infer section flags from the section name if we can.
214 Kind = getELFKindForNamedSection(SectionName, Kind);
216 StringRef Group = "";
217 unsigned Flags = getELFSectionFlags(Kind);
218 if (const Comdat *C = getELFComdat(GV)) {
219 Group = C->getName();
220 Flags |= ELF::SHF_GROUP;
222 return getContext().getELFSection(SectionName,
223 getELFSectionType(SectionName, Kind), Flags,
224 Kind, /*EntrySize=*/0, Group);
227 /// getSectionPrefixForGlobal - Return the section prefix name used by options
228 /// FunctionsSections and DataSections.
229 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
230 if (Kind.isText()) return ".text.";
231 if (Kind.isReadOnly()) return ".rodata.";
232 if (Kind.isBSS()) return ".bss.";
234 if (Kind.isThreadData()) return ".tdata.";
235 if (Kind.isThreadBSS()) return ".tbss.";
237 if (Kind.isDataNoRel()) return ".data.";
238 if (Kind.isDataRelLocal()) return ".data.rel.local.";
239 if (Kind.isDataRel()) return ".data.rel.";
240 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
242 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
243 return ".data.rel.ro.";
246 const MCSection *TargetLoweringObjectFileELF::
247 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
248 Mangler &Mang, const TargetMachine &TM) const {
249 // If we have -ffunction-section or -fdata-section then we should emit the
250 // global value to a uniqued section specifically for it.
251 bool EmitUniquedSection;
253 EmitUniquedSection = TM.getFunctionSections();
255 EmitUniquedSection = TM.getDataSections();
257 // If this global is linkonce/weak and the target handles this by emitting it
258 // into a 'uniqued' section name, create and return the section now.
259 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
260 StringRef Prefix = getSectionPrefixForGlobal(Kind);
262 SmallString<128> Name(Prefix);
263 TM.getNameWithPrefix(Name, GV, Mang, true);
265 StringRef Group = "";
266 unsigned Flags = getELFSectionFlags(Kind);
267 if (const Comdat *C = getELFComdat(GV)) {
268 Flags |= ELF::SHF_GROUP;
269 Group = C->getName();
272 return getContext().getELFSection(Name.str(),
273 getELFSectionType(Name.str(), Kind),
274 Flags, Kind, 0, Group);
277 if (Kind.isText()) return TextSection;
279 if (Kind.isMergeable1ByteCString() ||
280 Kind.isMergeable2ByteCString() ||
281 Kind.isMergeable4ByteCString()) {
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 const char *SizeSpec = ".rodata.str1.";
290 if (Kind.isMergeable2ByteCString())
291 SizeSpec = ".rodata.str2.";
292 else if (Kind.isMergeable4ByteCString())
293 SizeSpec = ".rodata.str4.";
295 assert(Kind.isMergeable1ByteCString() && "unknown string width");
298 std::string Name = SizeSpec + utostr(Align);
299 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
306 if (Kind.isMergeableConst()) {
307 if (Kind.isMergeableConst4() && MergeableConst4Section)
308 return MergeableConst4Section;
309 if (Kind.isMergeableConst8() && MergeableConst8Section)
310 return MergeableConst8Section;
311 if (Kind.isMergeableConst16() && MergeableConst16Section)
312 return MergeableConst16Section;
313 return ReadOnlySection; // .const
316 if (Kind.isReadOnly()) return ReadOnlySection;
318 if (Kind.isThreadData()) return TLSDataSection;
319 if (Kind.isThreadBSS()) return TLSBSSSection;
321 // Note: we claim that common symbols are put in BSSSection, but they are
322 // really emitted with the magic .comm directive, which creates a symbol table
323 // entry but not a section.
324 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
326 if (Kind.isDataNoRel()) return DataSection;
327 if (Kind.isDataRelLocal()) return DataRelLocalSection;
328 if (Kind.isDataRel()) return DataRelSection;
329 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
331 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
332 return DataRelROSection;
335 /// getSectionForConstant - Given a mergeable constant with the
336 /// specified size and relocation information, return a section that it
337 /// should be placed in.
339 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
340 const Constant *C) const {
341 if (Kind.isMergeableConst4() && MergeableConst4Section)
342 return MergeableConst4Section;
343 if (Kind.isMergeableConst8() && MergeableConst8Section)
344 return MergeableConst8Section;
345 if (Kind.isMergeableConst16() && MergeableConst16Section)
346 return MergeableConst16Section;
347 if (Kind.isReadOnly())
348 return ReadOnlySection;
350 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
351 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
352 return DataRelROSection;
355 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
359 const MCSymbol *KeySym) {
362 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
363 SectionKind Kind = SectionKind::getDataRel();
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, Kind, 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_;
417 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
420 SectionKind::getDataRel());
422 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
425 SectionKind::getDataRel());
428 //===----------------------------------------------------------------------===//
430 //===----------------------------------------------------------------------===//
432 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
433 /// option string. Returns StringRef() if the option does not specify a library.
434 StringRef TargetLoweringObjectFileMachO::
435 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
436 const char *LibCmd = "-l";
437 if (LinkerOption.startswith(LibCmd))
438 return LinkerOption.substr(strlen(LibCmd));
442 /// emitModuleFlags - Perform code emission for module flags.
443 void TargetLoweringObjectFileMachO::
444 emitModuleFlags(MCStreamer &Streamer,
445 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
446 Mangler &Mang, const TargetMachine &TM) const {
447 unsigned VersionVal = 0;
448 unsigned ImageInfoFlags = 0;
449 MDNode *LinkerOptions = nullptr;
450 StringRef SectionVal;
452 for (ArrayRef<Module::ModuleFlagEntry>::iterator
453 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
454 const Module::ModuleFlagEntry &MFE = *i;
456 // Ignore flags with 'Require' behavior.
457 if (MFE.Behavior == Module::Require)
460 StringRef Key = MFE.Key->getString();
461 Metadata *Val = MFE.Val;
463 if (Key == "Objective-C Image Info Version") {
464 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
465 } else if (Key == "Objective-C Garbage Collection" ||
466 Key == "Objective-C GC Only" ||
467 Key == "Objective-C Is Simulated" ||
468 Key == "Objective-C Image Swift Version") {
469 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
470 } else if (Key == "Objective-C Image Info Section") {
471 SectionVal = cast<MDString>(Val)->getString();
472 } else if (Key == "Linker Options") {
473 LinkerOptions = cast<MDNode>(Val);
477 // Emit the linker options if present.
479 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
480 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
481 SmallVector<std::string, 4> StrOptions;
483 // Convert to strings.
484 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
485 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
486 StrOptions.push_back(MDOption->getString());
489 Streamer.EmitLinkerOptions(StrOptions);
493 // The section is mandatory. If we don't have it, then we don't have GC info.
494 if (SectionVal.empty()) return;
496 StringRef Segment, Section;
497 unsigned TAA = 0, StubSize = 0;
499 std::string ErrorCode =
500 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
501 TAA, TAAParsed, StubSize);
502 if (!ErrorCode.empty())
503 // If invalid, report the error with report_fatal_error.
504 report_fatal_error("Invalid section specifier '" + Section + "': " +
508 const MCSectionMachO *S =
509 getContext().getMachOSection(Segment, Section, TAA, StubSize,
510 SectionKind::getDataNoRel());
511 Streamer.SwitchSection(S);
512 Streamer.EmitLabel(getContext().
513 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
514 Streamer.EmitIntValue(VersionVal, 4);
515 Streamer.EmitIntValue(ImageInfoFlags, 4);
516 Streamer.AddBlankLine();
519 static void checkMachOComdat(const GlobalValue *GV) {
520 const Comdat *C = GV->getComdat();
524 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
525 "' cannot be lowered.");
528 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
529 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
530 const TargetMachine &TM) const {
531 // Parse the section specifier and create it if valid.
532 StringRef Segment, Section;
533 unsigned TAA = 0, StubSize = 0;
536 checkMachOComdat(GV);
538 std::string ErrorCode =
539 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
540 TAA, TAAParsed, StubSize);
541 if (!ErrorCode.empty()) {
542 // If invalid, report the error with report_fatal_error.
543 report_fatal_error("Global variable '" + GV->getName() +
544 "' has an invalid section specifier '" +
545 GV->getSection() + "': " + ErrorCode + ".");
549 const MCSectionMachO *S =
550 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
552 // If TAA wasn't set by ParseSectionSpecifier() above,
553 // use the value returned by getMachOSection() as a default.
555 TAA = S->getTypeAndAttributes();
557 // Okay, now that we got the section, verify that the TAA & StubSize agree.
558 // If the user declared multiple globals with different section flags, we need
559 // to reject it here.
560 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
561 // If invalid, report the error with report_fatal_error.
562 report_fatal_error("Global variable '" + GV->getName() +
563 "' section type or attributes does not match previous"
564 " section specifier");
570 const MCSection *TargetLoweringObjectFileMachO::
571 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
572 Mangler &Mang, const TargetMachine &TM) const {
573 checkMachOComdat(GV);
575 // Handle thread local data.
576 if (Kind.isThreadBSS()) return TLSBSSSection;
577 if (Kind.isThreadData()) return TLSDataSection;
580 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
582 // If this is weak/linkonce, put this in a coalescable section, either in text
583 // or data depending on if it is writable.
584 if (GV->isWeakForLinker()) {
585 if (Kind.isReadOnly())
586 return ConstTextCoalSection;
587 return DataCoalSection;
590 // FIXME: Alignment check should be handled by section classifier.
591 if (Kind.isMergeable1ByteCString() &&
592 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
593 return CStringSection;
595 // Do not put 16-bit arrays in the UString section if they have an
596 // externally visible label, this runs into issues with certain linker
598 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
599 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
600 return UStringSection;
602 // With MachO only variables whose corresponding symbol starts with 'l' or
603 // 'L' can be merged, so we only try merging GVs with private linkage.
604 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
605 if (Kind.isMergeableConst4())
606 return FourByteConstantSection;
607 if (Kind.isMergeableConst8())
608 return EightByteConstantSection;
609 if (Kind.isMergeableConst16())
610 return SixteenByteConstantSection;
613 // Otherwise, if it is readonly, but not something we can specially optimize,
614 // just drop it in .const.
615 if (Kind.isReadOnly())
616 return ReadOnlySection;
618 // If this is marked const, put it into a const section. But if the dynamic
619 // linker needs to write to it, put it in the data segment.
620 if (Kind.isReadOnlyWithRel())
621 return ConstDataSection;
623 // Put zero initialized globals with strong external linkage in the
624 // DATA, __common section with the .zerofill directive.
625 if (Kind.isBSSExtern())
626 return DataCommonSection;
628 // Put zero initialized globals with local linkage in __DATA,__bss directive
629 // with the .zerofill directive (aka .lcomm).
630 if (Kind.isBSSLocal())
631 return DataBSSSection;
633 // Otherwise, just drop the variable in the normal data section.
638 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
639 const Constant *C) const {
640 // If this constant requires a relocation, we have to put it in the data
641 // segment, not in the text segment.
642 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
643 return ConstDataSection;
645 if (Kind.isMergeableConst4())
646 return FourByteConstantSection;
647 if (Kind.isMergeableConst8())
648 return EightByteConstantSection;
649 if (Kind.isMergeableConst16())
650 return SixteenByteConstantSection;
651 return ReadOnlySection; // .const
654 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
655 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
656 const TargetMachine &TM, MachineModuleInfo *MMI,
657 MCStreamer &Streamer) const {
658 // The mach-o version of this method defaults to returning a stub reference.
660 if (Encoding & DW_EH_PE_indirect) {
661 MachineModuleInfoMachO &MachOMMI =
662 MMI->getObjFileInfo<MachineModuleInfoMachO>();
665 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
667 // Add information about the stub reference to MachOMMI so that the stub
668 // gets emitted by the asmprinter.
669 MachineModuleInfoImpl::StubValueTy &StubSym =
670 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
671 MachOMMI.getGVStubEntry(SSym);
672 if (!StubSym.getPointer()) {
673 MCSymbol *Sym = TM.getSymbol(GV, Mang);
674 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
677 return TargetLoweringObjectFile::
678 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
679 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
682 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
686 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
687 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
688 MachineModuleInfo *MMI) const {
689 // The mach-o version of this method defaults to returning a stub reference.
690 MachineModuleInfoMachO &MachOMMI =
691 MMI->getObjFileInfo<MachineModuleInfoMachO>();
693 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
695 // Add information about the stub reference to MachOMMI so that the stub
696 // gets emitted by the asmprinter.
697 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
698 if (!StubSym.getPointer()) {
699 MCSymbol *Sym = TM.getSymbol(GV, Mang);
700 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
706 //===----------------------------------------------------------------------===//
708 //===----------------------------------------------------------------------===//
711 getCOFFSectionFlags(SectionKind K) {
716 COFF::IMAGE_SCN_MEM_DISCARDABLE;
719 COFF::IMAGE_SCN_MEM_EXECUTE |
720 COFF::IMAGE_SCN_MEM_READ |
721 COFF::IMAGE_SCN_CNT_CODE;
724 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
725 COFF::IMAGE_SCN_MEM_READ |
726 COFF::IMAGE_SCN_MEM_WRITE;
727 else if (K.isThreadLocal())
729 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
730 COFF::IMAGE_SCN_MEM_READ |
731 COFF::IMAGE_SCN_MEM_WRITE;
732 else if (K.isReadOnly() || K.isReadOnlyWithRel())
734 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
735 COFF::IMAGE_SCN_MEM_READ;
736 else if (K.isWriteable())
738 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
739 COFF::IMAGE_SCN_MEM_READ |
740 COFF::IMAGE_SCN_MEM_WRITE;
745 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
746 const Comdat *C = GV->getComdat();
747 assert(C && "expected GV to have a Comdat!");
749 StringRef ComdatGVName = C->getName();
750 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
752 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
753 "' does not exist.");
755 if (ComdatGV->getComdat() != C)
756 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
757 "' is not a key for its COMDAT.");
762 static int getSelectionForCOFF(const GlobalValue *GV) {
763 if (const Comdat *C = GV->getComdat()) {
764 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
765 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
766 ComdatKey = GA->getBaseObject();
767 if (ComdatKey == GV) {
768 switch (C->getSelectionKind()) {
770 return COFF::IMAGE_COMDAT_SELECT_ANY;
771 case Comdat::ExactMatch:
772 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
773 case Comdat::Largest:
774 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
775 case Comdat::NoDuplicates:
776 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
777 case Comdat::SameSize:
778 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
781 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
783 } else if (GV->isWeakForLinker()) {
784 return COFF::IMAGE_COMDAT_SELECT_ANY;
789 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
790 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
791 const TargetMachine &TM) const {
793 unsigned Characteristics = getCOFFSectionFlags(Kind);
794 StringRef Name = GV->getSection();
795 StringRef COMDATSymName = "";
796 if (GV->hasComdat()) {
797 Selection = getSelectionForCOFF(GV);
798 const GlobalValue *ComdatGV;
799 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
800 ComdatGV = getComdatGVForCOFF(GV);
804 if (!ComdatGV->hasPrivateLinkage()) {
805 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
806 COMDATSymName = Sym->getName();
807 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
812 return getContext().getCOFFSection(Name,
819 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
824 if (Kind.isThreadLocal())
826 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
832 const MCSection *TargetLoweringObjectFileCOFF::
833 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
834 Mangler &Mang, const TargetMachine &TM) const {
835 // If we have -ffunction-sections then we should emit the global value to a
836 // uniqued section specifically for it.
837 bool EmitUniquedSection;
839 EmitUniquedSection = TM.getFunctionSections();
841 EmitUniquedSection = TM.getDataSections();
843 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
844 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
845 unsigned Characteristics = getCOFFSectionFlags(Kind);
847 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
848 int Selection = getSelectionForCOFF(GV);
850 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
851 const GlobalValue *ComdatGV;
853 ComdatGV = getComdatGVForCOFF(GV);
857 if (!ComdatGV->hasPrivateLinkage()) {
858 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
859 StringRef COMDATSymName = Sym->getName();
860 return getContext().getCOFFSection(Name, Characteristics, Kind,
861 COMDATSymName, Selection);
868 if (Kind.isThreadLocal())
869 return TLSDataSection;
871 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
872 return ReadOnlySection;
874 // Note: we claim that common symbols are put in BSSSection, but they are
875 // really emitted with the magic .comm directive, which creates a symbol table
876 // entry but not a section.
877 if (Kind.isBSS() || Kind.isCommon())
883 StringRef TargetLoweringObjectFileCOFF::
884 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
885 const char *LibCmd = "/DEFAULTLIB:";
886 if (LinkerOption.startswith(LibCmd))
887 return LinkerOption.substr(strlen(LibCmd));
891 void TargetLoweringObjectFileCOFF::
892 emitModuleFlags(MCStreamer &Streamer,
893 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
894 Mangler &Mang, const TargetMachine &TM) const {
895 MDNode *LinkerOptions = nullptr;
897 // Look for the "Linker Options" flag, since it's the only one we support.
898 for (ArrayRef<Module::ModuleFlagEntry>::iterator
899 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
900 const Module::ModuleFlagEntry &MFE = *i;
901 StringRef Key = MFE.Key->getString();
902 Metadata *Val = MFE.Val;
903 if (Key == "Linker Options") {
904 LinkerOptions = cast<MDNode>(Val);
911 // Emit the linker options to the linker .drectve section. According to the
912 // spec, this section is a space-separated string containing flags for linker.
913 const MCSection *Sec = getDrectveSection();
914 Streamer.SwitchSection(Sec);
915 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
916 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
917 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
918 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
919 StringRef Op = MDOption->getString();
920 // Lead with a space for consistency with our dllexport implementation.
921 std::string Escaped(" ");
922 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
923 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
924 // how to escape quotes, but it probably uses this algorithm:
925 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
926 // FIXME: Reuse escaping code from Support/Windows/Program.inc
927 Escaped.push_back('\"');
929 Escaped.push_back('\"');
933 Streamer.EmitBytes(Escaped);
938 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
939 unsigned Priority, const MCSymbol *KeySym) const {
940 return getContext().getAssociativeCOFFSection(
941 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
944 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
945 unsigned Priority, const MCSymbol *KeySym) const {
946 return getContext().getAssociativeCOFFSection(
947 cast<MCSectionCOFF>(StaticDtorSection), KeySym);