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 static const MCSectionELF *selectELFSectionForGlobal(
248 MCContext &Ctx, const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
249 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags) {
250 unsigned EntrySize = 0;
251 if (Kind.isMergeableCString()) {
252 if (Kind.isMergeable2ByteCString()) {
254 } else if (Kind.isMergeable4ByteCString()) {
258 assert(Kind.isMergeable1ByteCString() && "unknown string width");
260 } else if (Kind.isMergeableConst()) {
261 if (Kind.isMergeableConst4()) {
263 } else if (Kind.isMergeableConst8()) {
266 assert(Kind.isMergeableConst16() && "unknown data width");
271 StringRef Group = "";
272 if (const Comdat *C = getELFComdat(GV)) {
273 Flags |= ELF::SHF_GROUP;
274 Group = C->getName();
277 bool UniqueSectionNames = TM.getUniqueSectionNames();
278 SmallString<128> Name;
279 if (Kind.isMergeableCString()) {
280 // We also need alignment here.
281 // FIXME: this is getting the alignment of the character, not the
282 // alignment of the global!
284 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
286 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
287 Name = SizeSpec + utostr(Align);
288 } else if (Kind.isMergeableConst()) {
289 Name = ".rodata.cst";
290 Name += utostr(EntrySize);
292 Name = getSectionPrefixForGlobal(Kind);
295 if (EmitUniqueSection && UniqueSectionNames) {
297 TM.getNameWithPrefix(Name, GV, Mang, true);
299 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
301 EmitUniqueSection && !UniqueSectionNames);
304 const MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
305 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
306 const TargetMachine &TM) const {
307 unsigned Flags = getELFSectionFlags(Kind);
309 // If we have -ffunction-section or -fdata-section then we should emit the
310 // global value to a uniqued section specifically for it.
311 bool EmitUniqueSection = false;
312 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
314 EmitUniqueSection = TM.getFunctionSections();
316 EmitUniqueSection = TM.getDataSections();
318 EmitUniqueSection |= GV->hasComdat();
320 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
321 EmitUniqueSection, Flags);
324 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
325 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
326 // If the function can be removed, produce a unique section so that
327 // the table doesn't prevent the removal.
328 const Comdat *C = F.getComdat();
329 bool EmitUniqueSection = TM.getFunctionSections() || C;
330 if (!EmitUniqueSection)
331 return ReadOnlySection;
333 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
334 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC);
337 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
338 bool UsesLabelDifference, const Function &F) const {
339 // We can always create relative relocations, so use another section
340 // that can be marked non-executable.
344 /// getSectionForConstant - Given a mergeable constant with the
345 /// specified size and relocation information, return a section that it
346 /// should be placed in.
348 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
349 const Constant *C) const {
350 if (Kind.isMergeableConst4() && MergeableConst4Section)
351 return MergeableConst4Section;
352 if (Kind.isMergeableConst8() && MergeableConst8Section)
353 return MergeableConst8Section;
354 if (Kind.isMergeableConst16() && MergeableConst16Section)
355 return MergeableConst16Section;
356 if (Kind.isReadOnly())
357 return ReadOnlySection;
359 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
360 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
361 return DataRelROSection;
364 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
368 const MCSymbol *KeySym) {
371 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
372 StringRef COMDAT = KeySym ? KeySym->getName() : "";
375 Flags |= ELF::SHF_GROUP;
379 Type = ELF::SHT_INIT_ARRAY;
380 Name = ".init_array";
382 Type = ELF::SHT_FINI_ARRAY;
383 Name = ".fini_array";
385 if (Priority != 65535) {
387 Name += utostr(Priority);
390 // The default scheme is .ctor / .dtor, so we have to invert the priority
396 if (Priority != 65535) {
398 Name += utostr(65535 - Priority);
400 Type = ELF::SHT_PROGBITS;
403 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
406 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
407 unsigned Priority, const MCSymbol *KeySym) const {
408 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
412 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
413 unsigned Priority, const MCSymbol *KeySym) const {
414 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
419 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
420 UseInitArray = UseInitArray_;
424 StaticCtorSection = getContext().getELFSection(
425 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
426 StaticDtorSection = getContext().getELFSection(
427 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
430 //===----------------------------------------------------------------------===//
432 //===----------------------------------------------------------------------===//
434 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
435 /// option string. Returns StringRef() if the option does not specify a library.
436 StringRef TargetLoweringObjectFileMachO::
437 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
438 const char *LibCmd = "-l";
439 if (LinkerOption.startswith(LibCmd))
440 return LinkerOption.substr(strlen(LibCmd));
444 /// emitModuleFlags - Perform code emission for module flags.
445 void TargetLoweringObjectFileMachO::
446 emitModuleFlags(MCStreamer &Streamer,
447 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
448 Mangler &Mang, const TargetMachine &TM) const {
449 unsigned VersionVal = 0;
450 unsigned ImageInfoFlags = 0;
451 MDNode *LinkerOptions = nullptr;
452 StringRef SectionVal;
454 for (ArrayRef<Module::ModuleFlagEntry>::iterator
455 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
456 const Module::ModuleFlagEntry &MFE = *i;
458 // Ignore flags with 'Require' behavior.
459 if (MFE.Behavior == Module::Require)
462 StringRef Key = MFE.Key->getString();
463 Metadata *Val = MFE.Val;
465 if (Key == "Objective-C Image Info Version") {
466 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
467 } else if (Key == "Objective-C Garbage Collection" ||
468 Key == "Objective-C GC Only" ||
469 Key == "Objective-C Is Simulated" ||
470 Key == "Objective-C Image Swift Version") {
471 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
472 } else if (Key == "Objective-C Image Info Section") {
473 SectionVal = cast<MDString>(Val)->getString();
474 } else if (Key == "Linker Options") {
475 LinkerOptions = cast<MDNode>(Val);
479 // Emit the linker options if present.
481 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
482 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
483 SmallVector<std::string, 4> StrOptions;
485 // Convert to strings.
486 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
487 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
488 StrOptions.push_back(MDOption->getString());
491 Streamer.EmitLinkerOptions(StrOptions);
495 // The section is mandatory. If we don't have it, then we don't have GC info.
496 if (SectionVal.empty()) return;
498 StringRef Segment, Section;
499 unsigned TAA = 0, StubSize = 0;
501 std::string ErrorCode =
502 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
503 TAA, TAAParsed, StubSize);
504 if (!ErrorCode.empty())
505 // If invalid, report the error with report_fatal_error.
506 report_fatal_error("Invalid section specifier '" + Section + "': " +
510 const MCSectionMachO *S =
511 getContext().getMachOSection(Segment, Section, TAA, StubSize,
512 SectionKind::getDataNoRel());
513 Streamer.SwitchSection(S);
514 Streamer.EmitLabel(getContext().
515 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
516 Streamer.EmitIntValue(VersionVal, 4);
517 Streamer.EmitIntValue(ImageInfoFlags, 4);
518 Streamer.AddBlankLine();
521 static void checkMachOComdat(const GlobalValue *GV) {
522 const Comdat *C = GV->getComdat();
526 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
527 "' cannot be lowered.");
530 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
531 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
532 const TargetMachine &TM) const {
533 // Parse the section specifier and create it if valid.
534 StringRef Segment, Section;
535 unsigned TAA = 0, StubSize = 0;
538 checkMachOComdat(GV);
540 std::string ErrorCode =
541 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
542 TAA, TAAParsed, StubSize);
543 if (!ErrorCode.empty()) {
544 // If invalid, report the error with report_fatal_error.
545 report_fatal_error("Global variable '" + GV->getName() +
546 "' has an invalid section specifier '" +
547 GV->getSection() + "': " + ErrorCode + ".");
551 const MCSectionMachO *S =
552 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
554 // If TAA wasn't set by ParseSectionSpecifier() above,
555 // use the value returned by getMachOSection() as a default.
557 TAA = S->getTypeAndAttributes();
559 // Okay, now that we got the section, verify that the TAA & StubSize agree.
560 // If the user declared multiple globals with different section flags, we need
561 // to reject it here.
562 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
563 // If invalid, report the error with report_fatal_error.
564 report_fatal_error("Global variable '" + GV->getName() +
565 "' section type or attributes does not match previous"
566 " section specifier");
572 const MCSection *TargetLoweringObjectFileMachO::
573 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
574 Mangler &Mang, const TargetMachine &TM) const {
575 checkMachOComdat(GV);
577 // Handle thread local data.
578 if (Kind.isThreadBSS()) return TLSBSSSection;
579 if (Kind.isThreadData()) return TLSDataSection;
582 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
584 // If this is weak/linkonce, put this in a coalescable section, either in text
585 // or data depending on if it is writable.
586 if (GV->isWeakForLinker()) {
587 if (Kind.isReadOnly())
588 return ConstTextCoalSection;
589 return DataCoalSection;
592 // FIXME: Alignment check should be handled by section classifier.
593 if (Kind.isMergeable1ByteCString() &&
594 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
595 return CStringSection;
597 // Do not put 16-bit arrays in the UString section if they have an
598 // externally visible label, this runs into issues with certain linker
600 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
601 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
602 return UStringSection;
604 // With MachO only variables whose corresponding symbol starts with 'l' or
605 // 'L' can be merged, so we only try merging GVs with private linkage.
606 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
607 if (Kind.isMergeableConst4())
608 return FourByteConstantSection;
609 if (Kind.isMergeableConst8())
610 return EightByteConstantSection;
611 if (Kind.isMergeableConst16())
612 return SixteenByteConstantSection;
615 // Otherwise, if it is readonly, but not something we can specially optimize,
616 // just drop it in .const.
617 if (Kind.isReadOnly())
618 return ReadOnlySection;
620 // If this is marked const, put it into a const section. But if the dynamic
621 // linker needs to write to it, put it in the data segment.
622 if (Kind.isReadOnlyWithRel())
623 return ConstDataSection;
625 // Put zero initialized globals with strong external linkage in the
626 // DATA, __common section with the .zerofill directive.
627 if (Kind.isBSSExtern())
628 return DataCommonSection;
630 // Put zero initialized globals with local linkage in __DATA,__bss directive
631 // with the .zerofill directive (aka .lcomm).
632 if (Kind.isBSSLocal())
633 return DataBSSSection;
635 // Otherwise, just drop the variable in the normal data section.
640 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
641 const Constant *C) const {
642 // If this constant requires a relocation, we have to put it in the data
643 // segment, not in the text segment.
644 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
645 return ConstDataSection;
647 if (Kind.isMergeableConst4())
648 return FourByteConstantSection;
649 if (Kind.isMergeableConst8())
650 return EightByteConstantSection;
651 if (Kind.isMergeableConst16())
652 return SixteenByteConstantSection;
653 return ReadOnlySection; // .const
656 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
657 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
658 const TargetMachine &TM, MachineModuleInfo *MMI,
659 MCStreamer &Streamer) const {
660 // The mach-o version of this method defaults to returning a stub reference.
662 if (Encoding & DW_EH_PE_indirect) {
663 MachineModuleInfoMachO &MachOMMI =
664 MMI->getObjFileInfo<MachineModuleInfoMachO>();
667 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
669 // Add information about the stub reference to MachOMMI so that the stub
670 // gets emitted by the asmprinter.
671 MachineModuleInfoImpl::StubValueTy &StubSym =
672 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
673 MachOMMI.getGVStubEntry(SSym);
674 if (!StubSym.getPointer()) {
675 MCSymbol *Sym = TM.getSymbol(GV, Mang);
676 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
679 return TargetLoweringObjectFile::
680 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
681 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
684 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
688 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
689 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
690 MachineModuleInfo *MMI) const {
691 // The mach-o version of this method defaults to returning a stub reference.
692 MachineModuleInfoMachO &MachOMMI =
693 MMI->getObjFileInfo<MachineModuleInfoMachO>();
695 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
697 // Add information about the stub reference to MachOMMI so that the stub
698 // gets emitted by the asmprinter.
699 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
700 if (!StubSym.getPointer()) {
701 MCSymbol *Sym = TM.getSymbol(GV, Mang);
702 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
708 //===----------------------------------------------------------------------===//
710 //===----------------------------------------------------------------------===//
713 getCOFFSectionFlags(SectionKind K) {
718 COFF::IMAGE_SCN_MEM_DISCARDABLE;
721 COFF::IMAGE_SCN_MEM_EXECUTE |
722 COFF::IMAGE_SCN_MEM_READ |
723 COFF::IMAGE_SCN_CNT_CODE;
726 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
727 COFF::IMAGE_SCN_MEM_READ |
728 COFF::IMAGE_SCN_MEM_WRITE;
729 else if (K.isThreadLocal())
731 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
732 COFF::IMAGE_SCN_MEM_READ |
733 COFF::IMAGE_SCN_MEM_WRITE;
734 else if (K.isReadOnly() || K.isReadOnlyWithRel())
736 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
737 COFF::IMAGE_SCN_MEM_READ;
738 else if (K.isWriteable())
740 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
741 COFF::IMAGE_SCN_MEM_READ |
742 COFF::IMAGE_SCN_MEM_WRITE;
747 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
748 const Comdat *C = GV->getComdat();
749 assert(C && "expected GV to have a Comdat!");
751 StringRef ComdatGVName = C->getName();
752 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
754 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
755 "' does not exist.");
757 if (ComdatGV->getComdat() != C)
758 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
759 "' is not a key for its COMDAT.");
764 static int getSelectionForCOFF(const GlobalValue *GV) {
765 if (const Comdat *C = GV->getComdat()) {
766 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
767 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
768 ComdatKey = GA->getBaseObject();
769 if (ComdatKey == GV) {
770 switch (C->getSelectionKind()) {
772 return COFF::IMAGE_COMDAT_SELECT_ANY;
773 case Comdat::ExactMatch:
774 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
775 case Comdat::Largest:
776 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
777 case Comdat::NoDuplicates:
778 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
779 case Comdat::SameSize:
780 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
783 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
785 } else if (GV->isWeakForLinker()) {
786 return COFF::IMAGE_COMDAT_SELECT_ANY;
791 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
792 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
793 const TargetMachine &TM) const {
795 unsigned Characteristics = getCOFFSectionFlags(Kind);
796 StringRef Name = GV->getSection();
797 StringRef COMDATSymName = "";
798 if (GV->hasComdat()) {
799 Selection = getSelectionForCOFF(GV);
800 const GlobalValue *ComdatGV;
801 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
802 ComdatGV = getComdatGVForCOFF(GV);
806 if (!ComdatGV->hasPrivateLinkage()) {
807 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
808 COMDATSymName = Sym->getName();
809 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
814 return getContext().getCOFFSection(Name,
821 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
826 if (Kind.isThreadLocal())
828 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
834 const MCSection *TargetLoweringObjectFileCOFF::
835 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
836 Mangler &Mang, const TargetMachine &TM) const {
837 // If we have -ffunction-sections then we should emit the global value to a
838 // uniqued section specifically for it.
839 bool EmitUniquedSection;
841 EmitUniquedSection = TM.getFunctionSections();
843 EmitUniquedSection = TM.getDataSections();
845 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
846 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
847 unsigned Characteristics = getCOFFSectionFlags(Kind);
849 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
850 int Selection = getSelectionForCOFF(GV);
852 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
853 const GlobalValue *ComdatGV;
855 ComdatGV = getComdatGVForCOFF(GV);
859 if (!ComdatGV->hasPrivateLinkage()) {
860 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
861 StringRef COMDATSymName = Sym->getName();
862 return getContext().getCOFFSection(Name, Characteristics, Kind,
863 COMDATSymName, Selection);
870 if (Kind.isThreadLocal())
871 return TLSDataSection;
873 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
874 return ReadOnlySection;
876 // Note: we claim that common symbols are put in BSSSection, but they are
877 // really emitted with the magic .comm directive, which creates a symbol table
878 // entry but not a section.
879 if (Kind.isBSS() || Kind.isCommon())
885 StringRef TargetLoweringObjectFileCOFF::
886 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
887 const char *LibCmd = "/DEFAULTLIB:";
888 if (LinkerOption.startswith(LibCmd))
889 return LinkerOption.substr(strlen(LibCmd));
893 void TargetLoweringObjectFileCOFF::
894 emitModuleFlags(MCStreamer &Streamer,
895 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
896 Mangler &Mang, const TargetMachine &TM) const {
897 MDNode *LinkerOptions = nullptr;
899 // Look for the "Linker Options" flag, since it's the only one we support.
900 for (ArrayRef<Module::ModuleFlagEntry>::iterator
901 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
902 const Module::ModuleFlagEntry &MFE = *i;
903 StringRef Key = MFE.Key->getString();
904 Metadata *Val = MFE.Val;
905 if (Key == "Linker Options") {
906 LinkerOptions = cast<MDNode>(Val);
913 // Emit the linker options to the linker .drectve section. According to the
914 // spec, this section is a space-separated string containing flags for linker.
915 const MCSection *Sec = getDrectveSection();
916 Streamer.SwitchSection(Sec);
917 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
918 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
919 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
920 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
921 // Lead with a space for consistency with our dllexport implementation.
922 std::string Directive(" ");
923 Directive.append(MDOption->getString());
924 Streamer.EmitBytes(Directive);
929 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
930 unsigned Priority, const MCSymbol *KeySym) const {
931 return getContext().getAssociativeCOFFSection(
932 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
935 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
936 unsigned Priority, const MCSymbol *KeySym) const {
937 return getContext().getAssociativeCOFFSection(
938 cast<MCSectionCOFF>(StaticDtorSection), KeySym);