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;
169 getELFSectionFlags(SectionKind K, bool InCOMDAT) {
173 Flags |= ELF::SHF_ALLOC;
176 Flags |= ELF::SHF_EXECINSTR;
179 Flags |= ELF::SHF_WRITE;
181 if (K.isThreadLocal())
182 Flags |= ELF::SHF_TLS;
184 // FIXME: There is nothing in ELF preventing an SHF_MERGE from being
185 // in a comdat. We just avoid it for now because we don't print
186 // those .sections correctly.
187 if (!InCOMDAT && (K.isMergeableCString() || K.isMergeableConst()))
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, GV->hasComdat());
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 /*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 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
251 // If we have -ffunction-section or -fdata-section then we should emit the
252 // global value to a uniqued section specifically for it.
253 bool EmitUniquedSection = false;
254 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
256 EmitUniquedSection = TM.getFunctionSections();
258 EmitUniquedSection = TM.getDataSections();
261 if (EmitUniquedSection || GV->hasComdat()) {
262 StringRef Prefix = getSectionPrefixForGlobal(Kind);
264 SmallString<128> Name(Prefix);
265 TM.getNameWithPrefix(Name, GV, Mang, true);
267 StringRef Group = "";
268 if (const Comdat *C = getELFComdat(GV)) {
269 Flags |= ELF::SHF_GROUP;
270 Group = C->getName();
273 return getContext().getELFSection(
274 Name.str(), getELFSectionType(Name.str(), Kind), Flags, 0, Group);
277 if (Kind.isText()) return TextSection;
279 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 unsigned EntrySize = 1;
288 if (Kind.isMergeable2ByteCString())
290 else if (Kind.isMergeable4ByteCString())
293 assert(Kind.isMergeable1ByteCString() && "unknown string width");
295 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
296 std::string Name = SizeSpec + utostr(Align);
297 return getContext().getELFSection(
298 Name, ELF::SHT_PROGBITS,
299 ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
302 if (Kind.isMergeableConst()) {
303 if (Kind.isMergeableConst4() && MergeableConst4Section)
304 return MergeableConst4Section;
305 if (Kind.isMergeableConst8() && MergeableConst8Section)
306 return MergeableConst8Section;
307 if (Kind.isMergeableConst16() && MergeableConst16Section)
308 return MergeableConst16Section;
309 return ReadOnlySection; // .const
312 if (Kind.isReadOnly()) return ReadOnlySection;
314 if (Kind.isThreadData()) return TLSDataSection;
315 if (Kind.isThreadBSS()) return TLSBSSSection;
317 // Note: we claim that common symbols are put in BSSSection, but they are
318 // really emitted with the magic .comm directive, which creates a symbol table
319 // entry but not a section.
320 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
322 if (Kind.isDataNoRel()) return DataSection;
323 if (Kind.isDataRelLocal()) return DataRelLocalSection;
324 if (Kind.isDataRel()) return DataRelSection;
325 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
327 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
328 return DataRelROSection;
331 /// getSectionForConstant - Given a mergeable constant with the
332 /// specified size and relocation information, return a section that it
333 /// should be placed in.
335 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
336 const Constant *C) const {
337 if (Kind.isMergeableConst4() && MergeableConst4Section)
338 return MergeableConst4Section;
339 if (Kind.isMergeableConst8() && MergeableConst8Section)
340 return MergeableConst8Section;
341 if (Kind.isMergeableConst16() && MergeableConst16Section)
342 return MergeableConst16Section;
343 if (Kind.isReadOnly())
344 return ReadOnlySection;
346 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
347 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
348 return DataRelROSection;
351 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
355 const MCSymbol *KeySym) {
358 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
359 StringRef COMDAT = KeySym ? KeySym->getName() : "";
362 Flags |= ELF::SHF_GROUP;
366 Type = ELF::SHT_INIT_ARRAY;
367 Name = ".init_array";
369 Type = ELF::SHT_FINI_ARRAY;
370 Name = ".fini_array";
372 if (Priority != 65535) {
374 Name += utostr(Priority);
377 // The default scheme is .ctor / .dtor, so we have to invert the priority
383 if (Priority != 65535) {
385 Name += utostr(65535 - Priority);
387 Type = ELF::SHT_PROGBITS;
390 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
393 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
394 unsigned Priority, const MCSymbol *KeySym) const {
395 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
399 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
400 unsigned Priority, const MCSymbol *KeySym) const {
401 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
406 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
407 UseInitArray = UseInitArray_;
411 StaticCtorSection = getContext().getELFSection(
412 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
413 StaticDtorSection = getContext().getELFSection(
414 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
417 //===----------------------------------------------------------------------===//
419 //===----------------------------------------------------------------------===//
421 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
422 /// option string. Returns StringRef() if the option does not specify a library.
423 StringRef TargetLoweringObjectFileMachO::
424 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
425 const char *LibCmd = "-l";
426 if (LinkerOption.startswith(LibCmd))
427 return LinkerOption.substr(strlen(LibCmd));
431 /// emitModuleFlags - Perform code emission for module flags.
432 void TargetLoweringObjectFileMachO::
433 emitModuleFlags(MCStreamer &Streamer,
434 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
435 Mangler &Mang, const TargetMachine &TM) const {
436 unsigned VersionVal = 0;
437 unsigned ImageInfoFlags = 0;
438 MDNode *LinkerOptions = nullptr;
439 StringRef SectionVal;
441 for (ArrayRef<Module::ModuleFlagEntry>::iterator
442 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
443 const Module::ModuleFlagEntry &MFE = *i;
445 // Ignore flags with 'Require' behavior.
446 if (MFE.Behavior == Module::Require)
449 StringRef Key = MFE.Key->getString();
450 Metadata *Val = MFE.Val;
452 if (Key == "Objective-C Image Info Version") {
453 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
454 } else if (Key == "Objective-C Garbage Collection" ||
455 Key == "Objective-C GC Only" ||
456 Key == "Objective-C Is Simulated" ||
457 Key == "Objective-C Image Swift Version") {
458 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
459 } else if (Key == "Objective-C Image Info Section") {
460 SectionVal = cast<MDString>(Val)->getString();
461 } else if (Key == "Linker Options") {
462 LinkerOptions = cast<MDNode>(Val);
466 // Emit the linker options if present.
468 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
469 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
470 SmallVector<std::string, 4> StrOptions;
472 // Convert to strings.
473 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
474 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
475 StrOptions.push_back(MDOption->getString());
478 Streamer.EmitLinkerOptions(StrOptions);
482 // The section is mandatory. If we don't have it, then we don't have GC info.
483 if (SectionVal.empty()) return;
485 StringRef Segment, Section;
486 unsigned TAA = 0, StubSize = 0;
488 std::string ErrorCode =
489 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
490 TAA, TAAParsed, StubSize);
491 if (!ErrorCode.empty())
492 // If invalid, report the error with report_fatal_error.
493 report_fatal_error("Invalid section specifier '" + Section + "': " +
497 const MCSectionMachO *S =
498 getContext().getMachOSection(Segment, Section, TAA, StubSize,
499 SectionKind::getDataNoRel());
500 Streamer.SwitchSection(S);
501 Streamer.EmitLabel(getContext().
502 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
503 Streamer.EmitIntValue(VersionVal, 4);
504 Streamer.EmitIntValue(ImageInfoFlags, 4);
505 Streamer.AddBlankLine();
508 static void checkMachOComdat(const GlobalValue *GV) {
509 const Comdat *C = GV->getComdat();
513 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
514 "' cannot be lowered.");
517 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
518 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
519 const TargetMachine &TM) const {
520 // Parse the section specifier and create it if valid.
521 StringRef Segment, Section;
522 unsigned TAA = 0, StubSize = 0;
525 checkMachOComdat(GV);
527 std::string ErrorCode =
528 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
529 TAA, TAAParsed, StubSize);
530 if (!ErrorCode.empty()) {
531 // If invalid, report the error with report_fatal_error.
532 report_fatal_error("Global variable '" + GV->getName() +
533 "' has an invalid section specifier '" +
534 GV->getSection() + "': " + ErrorCode + ".");
538 const MCSectionMachO *S =
539 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
541 // If TAA wasn't set by ParseSectionSpecifier() above,
542 // use the value returned by getMachOSection() as a default.
544 TAA = S->getTypeAndAttributes();
546 // Okay, now that we got the section, verify that the TAA & StubSize agree.
547 // If the user declared multiple globals with different section flags, we need
548 // to reject it here.
549 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
550 // If invalid, report the error with report_fatal_error.
551 report_fatal_error("Global variable '" + GV->getName() +
552 "' section type or attributes does not match previous"
553 " section specifier");
559 const MCSection *TargetLoweringObjectFileMachO::
560 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
561 Mangler &Mang, const TargetMachine &TM) const {
562 checkMachOComdat(GV);
564 // Handle thread local data.
565 if (Kind.isThreadBSS()) return TLSBSSSection;
566 if (Kind.isThreadData()) return TLSDataSection;
569 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
571 // If this is weak/linkonce, put this in a coalescable section, either in text
572 // or data depending on if it is writable.
573 if (GV->isWeakForLinker()) {
574 if (Kind.isReadOnly())
575 return ConstTextCoalSection;
576 return DataCoalSection;
579 // FIXME: Alignment check should be handled by section classifier.
580 if (Kind.isMergeable1ByteCString() &&
581 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
582 return CStringSection;
584 // Do not put 16-bit arrays in the UString section if they have an
585 // externally visible label, this runs into issues with certain linker
587 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
588 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
589 return UStringSection;
591 // With MachO only variables whose corresponding symbol starts with 'l' or
592 // 'L' can be merged, so we only try merging GVs with private linkage.
593 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
594 if (Kind.isMergeableConst4())
595 return FourByteConstantSection;
596 if (Kind.isMergeableConst8())
597 return EightByteConstantSection;
598 if (Kind.isMergeableConst16())
599 return SixteenByteConstantSection;
602 // Otherwise, if it is readonly, but not something we can specially optimize,
603 // just drop it in .const.
604 if (Kind.isReadOnly())
605 return ReadOnlySection;
607 // If this is marked const, put it into a const section. But if the dynamic
608 // linker needs to write to it, put it in the data segment.
609 if (Kind.isReadOnlyWithRel())
610 return ConstDataSection;
612 // Put zero initialized globals with strong external linkage in the
613 // DATA, __common section with the .zerofill directive.
614 if (Kind.isBSSExtern())
615 return DataCommonSection;
617 // Put zero initialized globals with local linkage in __DATA,__bss directive
618 // with the .zerofill directive (aka .lcomm).
619 if (Kind.isBSSLocal())
620 return DataBSSSection;
622 // Otherwise, just drop the variable in the normal data section.
627 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
628 const Constant *C) const {
629 // If this constant requires a relocation, we have to put it in the data
630 // segment, not in the text segment.
631 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
632 return ConstDataSection;
634 if (Kind.isMergeableConst4())
635 return FourByteConstantSection;
636 if (Kind.isMergeableConst8())
637 return EightByteConstantSection;
638 if (Kind.isMergeableConst16())
639 return SixteenByteConstantSection;
640 return ReadOnlySection; // .const
643 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
644 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
645 const TargetMachine &TM, MachineModuleInfo *MMI,
646 MCStreamer &Streamer) const {
647 // The mach-o version of this method defaults to returning a stub reference.
649 if (Encoding & DW_EH_PE_indirect) {
650 MachineModuleInfoMachO &MachOMMI =
651 MMI->getObjFileInfo<MachineModuleInfoMachO>();
654 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
656 // Add information about the stub reference to MachOMMI so that the stub
657 // gets emitted by the asmprinter.
658 MachineModuleInfoImpl::StubValueTy &StubSym =
659 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
660 MachOMMI.getGVStubEntry(SSym);
661 if (!StubSym.getPointer()) {
662 MCSymbol *Sym = TM.getSymbol(GV, Mang);
663 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
666 return TargetLoweringObjectFile::
667 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
668 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
671 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
675 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
676 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
677 MachineModuleInfo *MMI) const {
678 // The mach-o version of this method defaults to returning a stub reference.
679 MachineModuleInfoMachO &MachOMMI =
680 MMI->getObjFileInfo<MachineModuleInfoMachO>();
682 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
684 // Add information about the stub reference to MachOMMI so that the stub
685 // gets emitted by the asmprinter.
686 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
687 if (!StubSym.getPointer()) {
688 MCSymbol *Sym = TM.getSymbol(GV, Mang);
689 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
695 //===----------------------------------------------------------------------===//
697 //===----------------------------------------------------------------------===//
700 getCOFFSectionFlags(SectionKind K) {
705 COFF::IMAGE_SCN_MEM_DISCARDABLE;
708 COFF::IMAGE_SCN_MEM_EXECUTE |
709 COFF::IMAGE_SCN_MEM_READ |
710 COFF::IMAGE_SCN_CNT_CODE;
713 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
714 COFF::IMAGE_SCN_MEM_READ |
715 COFF::IMAGE_SCN_MEM_WRITE;
716 else if (K.isThreadLocal())
718 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
719 COFF::IMAGE_SCN_MEM_READ |
720 COFF::IMAGE_SCN_MEM_WRITE;
721 else if (K.isReadOnly() || K.isReadOnlyWithRel())
723 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
724 COFF::IMAGE_SCN_MEM_READ;
725 else if (K.isWriteable())
727 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
728 COFF::IMAGE_SCN_MEM_READ |
729 COFF::IMAGE_SCN_MEM_WRITE;
734 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
735 const Comdat *C = GV->getComdat();
736 assert(C && "expected GV to have a Comdat!");
738 StringRef ComdatGVName = C->getName();
739 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
741 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
742 "' does not exist.");
744 if (ComdatGV->getComdat() != C)
745 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
746 "' is not a key for its COMDAT.");
751 static int getSelectionForCOFF(const GlobalValue *GV) {
752 if (const Comdat *C = GV->getComdat()) {
753 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
754 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
755 ComdatKey = GA->getBaseObject();
756 if (ComdatKey == GV) {
757 switch (C->getSelectionKind()) {
759 return COFF::IMAGE_COMDAT_SELECT_ANY;
760 case Comdat::ExactMatch:
761 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
762 case Comdat::Largest:
763 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
764 case Comdat::NoDuplicates:
765 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
766 case Comdat::SameSize:
767 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
770 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
772 } else if (GV->isWeakForLinker()) {
773 return COFF::IMAGE_COMDAT_SELECT_ANY;
778 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
779 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
780 const TargetMachine &TM) const {
782 unsigned Characteristics = getCOFFSectionFlags(Kind);
783 StringRef Name = GV->getSection();
784 StringRef COMDATSymName = "";
785 if (GV->hasComdat()) {
786 Selection = getSelectionForCOFF(GV);
787 const GlobalValue *ComdatGV;
788 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
789 ComdatGV = getComdatGVForCOFF(GV);
793 if (!ComdatGV->hasPrivateLinkage()) {
794 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
795 COMDATSymName = Sym->getName();
796 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
801 return getContext().getCOFFSection(Name,
808 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
813 if (Kind.isThreadLocal())
815 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
821 const MCSection *TargetLoweringObjectFileCOFF::
822 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
823 Mangler &Mang, const TargetMachine &TM) const {
824 // If we have -ffunction-sections then we should emit the global value to a
825 // uniqued section specifically for it.
826 bool EmitUniquedSection;
828 EmitUniquedSection = TM.getFunctionSections();
830 EmitUniquedSection = TM.getDataSections();
832 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
833 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
834 unsigned Characteristics = getCOFFSectionFlags(Kind);
836 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
837 int Selection = getSelectionForCOFF(GV);
839 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
840 const GlobalValue *ComdatGV;
842 ComdatGV = getComdatGVForCOFF(GV);
846 if (!ComdatGV->hasPrivateLinkage()) {
847 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
848 StringRef COMDATSymName = Sym->getName();
849 return getContext().getCOFFSection(Name, Characteristics, Kind,
850 COMDATSymName, Selection);
857 if (Kind.isThreadLocal())
858 return TLSDataSection;
860 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
861 return ReadOnlySection;
863 // Note: we claim that common symbols are put in BSSSection, but they are
864 // really emitted with the magic .comm directive, which creates a symbol table
865 // entry but not a section.
866 if (Kind.isBSS() || Kind.isCommon())
872 StringRef TargetLoweringObjectFileCOFF::
873 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
874 const char *LibCmd = "/DEFAULTLIB:";
875 if (LinkerOption.startswith(LibCmd))
876 return LinkerOption.substr(strlen(LibCmd));
880 void TargetLoweringObjectFileCOFF::
881 emitModuleFlags(MCStreamer &Streamer,
882 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
883 Mangler &Mang, const TargetMachine &TM) const {
884 MDNode *LinkerOptions = nullptr;
886 // Look for the "Linker Options" flag, since it's the only one we support.
887 for (ArrayRef<Module::ModuleFlagEntry>::iterator
888 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
889 const Module::ModuleFlagEntry &MFE = *i;
890 StringRef Key = MFE.Key->getString();
891 Metadata *Val = MFE.Val;
892 if (Key == "Linker Options") {
893 LinkerOptions = cast<MDNode>(Val);
900 // Emit the linker options to the linker .drectve section. According to the
901 // spec, this section is a space-separated string containing flags for linker.
902 const MCSection *Sec = getDrectveSection();
903 Streamer.SwitchSection(Sec);
904 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
905 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
906 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
907 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
908 StringRef Op = MDOption->getString();
909 // Lead with a space for consistency with our dllexport implementation.
910 std::string Escaped(" ");
911 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
912 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
913 // how to escape quotes, but it probably uses this algorithm:
914 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
915 // FIXME: Reuse escaping code from Support/Windows/Program.inc
916 Escaped.push_back('\"');
918 Escaped.push_back('\"');
922 Streamer.EmitBytes(Escaped);
927 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
928 unsigned Priority, const MCSymbol *KeySym) const {
929 return getContext().getAssociativeCOFFSection(
930 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
933 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
934 unsigned Priority, const MCSymbol *KeySym) const {
935 return getContext().getAssociativeCOFFSection(
936 cast<MCSectionCOFF>(StaticDtorSection), KeySym);