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 /// Return the section prefix name used by options FunctionsSections and
229 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
232 if (Kind.isReadOnly())
236 if (Kind.isThreadData())
238 if (Kind.isThreadBSS())
240 if (Kind.isDataNoRel())
242 if (Kind.isDataRelLocal())
243 return ".data.rel.local";
244 if (Kind.isDataRel())
246 if (Kind.isReadOnlyWithRelLocal())
247 return ".data.rel.ro.local";
248 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
249 return ".data.rel.ro";
252 static const MCSection *
253 getUniqueELFSection(MCContext &Ctx, const GlobalValue &GV, SectionKind Kind,
254 Mangler &Mang, const TargetMachine &TM, unsigned Flags) {
255 StringRef Prefix = getSectionPrefixForGlobal(Kind);
257 SmallString<128> Name(Prefix);
258 bool UniqueSectionNames = TM.getUniqueSectionNames();
259 if (UniqueSectionNames) {
261 TM.getNameWithPrefix(Name, &GV, Mang, true);
263 StringRef Group = "";
264 if (const Comdat *C = getELFComdat(&GV)) {
265 Flags |= ELF::SHF_GROUP;
266 Group = C->getName();
269 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 0, Group,
270 !UniqueSectionNames);
273 const MCSection *TargetLoweringObjectFileELF::
274 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
275 Mangler &Mang, const TargetMachine &TM) const {
276 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
278 // If we have -ffunction-section or -fdata-section then we should emit the
279 // global value to a uniqued section specifically for it.
280 bool EmitUniquedSection = false;
281 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
283 EmitUniquedSection = TM.getFunctionSections();
285 EmitUniquedSection = TM.getDataSections();
288 if (EmitUniquedSection || GV->hasComdat())
289 return getUniqueELFSection(getContext(), *GV, Kind, Mang, TM, Flags);
291 if (Kind.isText()) return TextSection;
293 if (Kind.isMergeableCString()) {
295 // We also need alignment here.
296 // FIXME: this is getting the alignment of the character, not the
297 // alignment of the global!
299 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
301 unsigned EntrySize = 1;
302 if (Kind.isMergeable2ByteCString())
304 else if (Kind.isMergeable4ByteCString())
307 assert(Kind.isMergeable1ByteCString() && "unknown string width");
309 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
310 std::string Name = SizeSpec + utostr(Align);
311 return getContext().getELFSection(
312 Name, ELF::SHT_PROGBITS,
313 ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
316 if (Kind.isMergeableConst()) {
317 if (Kind.isMergeableConst4() && MergeableConst4Section)
318 return MergeableConst4Section;
319 if (Kind.isMergeableConst8() && MergeableConst8Section)
320 return MergeableConst8Section;
321 if (Kind.isMergeableConst16() && MergeableConst16Section)
322 return MergeableConst16Section;
323 return ReadOnlySection; // .const
326 if (Kind.isReadOnly()) return ReadOnlySection;
328 if (Kind.isThreadData()) return TLSDataSection;
329 if (Kind.isThreadBSS()) return TLSBSSSection;
331 // Note: we claim that common symbols are put in BSSSection, but they are
332 // really emitted with the magic .comm directive, which creates a symbol table
333 // entry but not a section.
334 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
336 if (Kind.isDataNoRel()) return DataSection;
337 if (Kind.isDataRelLocal()) return DataRelLocalSection;
338 if (Kind.isDataRel()) return DataRelSection;
339 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
341 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
342 return DataRelROSection;
345 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
346 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
347 // If the function can be removed, produce a unique section so that
348 // the table doesn't prevent the removal.
349 const Comdat *C = F.getComdat();
350 bool EmitUniqueSection = TM.getFunctionSections() || C;
351 if (!EmitUniqueSection)
352 return ReadOnlySection;
354 return getUniqueELFSection(getContext(), F, SectionKind::getReadOnly(), Mang,
358 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
359 bool UsesLabelDifference, const Function &F) const {
360 // We can always create relative relocations, so use another section
361 // that can be marked non-executable.
365 /// getSectionForConstant - Given a mergeable constant with the
366 /// specified size and relocation information, return a section that it
367 /// should be placed in.
369 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
370 const Constant *C) const {
371 if (Kind.isMergeableConst4() && MergeableConst4Section)
372 return MergeableConst4Section;
373 if (Kind.isMergeableConst8() && MergeableConst8Section)
374 return MergeableConst8Section;
375 if (Kind.isMergeableConst16() && MergeableConst16Section)
376 return MergeableConst16Section;
377 if (Kind.isReadOnly())
378 return ReadOnlySection;
380 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
381 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
382 return DataRelROSection;
385 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
389 const MCSymbol *KeySym) {
392 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
393 StringRef COMDAT = KeySym ? KeySym->getName() : "";
396 Flags |= ELF::SHF_GROUP;
400 Type = ELF::SHT_INIT_ARRAY;
401 Name = ".init_array";
403 Type = ELF::SHT_FINI_ARRAY;
404 Name = ".fini_array";
406 if (Priority != 65535) {
408 Name += utostr(Priority);
411 // The default scheme is .ctor / .dtor, so we have to invert the priority
417 if (Priority != 65535) {
419 Name += utostr(65535 - Priority);
421 Type = ELF::SHT_PROGBITS;
424 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
427 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
428 unsigned Priority, const MCSymbol *KeySym) const {
429 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
433 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
434 unsigned Priority, const MCSymbol *KeySym) const {
435 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
440 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
441 UseInitArray = UseInitArray_;
445 StaticCtorSection = getContext().getELFSection(
446 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
447 StaticDtorSection = getContext().getELFSection(
448 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
451 //===----------------------------------------------------------------------===//
453 //===----------------------------------------------------------------------===//
455 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
456 /// option string. Returns StringRef() if the option does not specify a library.
457 StringRef TargetLoweringObjectFileMachO::
458 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
459 const char *LibCmd = "-l";
460 if (LinkerOption.startswith(LibCmd))
461 return LinkerOption.substr(strlen(LibCmd));
465 /// emitModuleFlags - Perform code emission for module flags.
466 void TargetLoweringObjectFileMachO::
467 emitModuleFlags(MCStreamer &Streamer,
468 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
469 Mangler &Mang, const TargetMachine &TM) const {
470 unsigned VersionVal = 0;
471 unsigned ImageInfoFlags = 0;
472 MDNode *LinkerOptions = nullptr;
473 StringRef SectionVal;
475 for (ArrayRef<Module::ModuleFlagEntry>::iterator
476 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
477 const Module::ModuleFlagEntry &MFE = *i;
479 // Ignore flags with 'Require' behavior.
480 if (MFE.Behavior == Module::Require)
483 StringRef Key = MFE.Key->getString();
484 Metadata *Val = MFE.Val;
486 if (Key == "Objective-C Image Info Version") {
487 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
488 } else if (Key == "Objective-C Garbage Collection" ||
489 Key == "Objective-C GC Only" ||
490 Key == "Objective-C Is Simulated" ||
491 Key == "Objective-C Image Swift Version") {
492 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
493 } else if (Key == "Objective-C Image Info Section") {
494 SectionVal = cast<MDString>(Val)->getString();
495 } else if (Key == "Linker Options") {
496 LinkerOptions = cast<MDNode>(Val);
500 // Emit the linker options if present.
502 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
503 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
504 SmallVector<std::string, 4> StrOptions;
506 // Convert to strings.
507 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
508 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
509 StrOptions.push_back(MDOption->getString());
512 Streamer.EmitLinkerOptions(StrOptions);
516 // The section is mandatory. If we don't have it, then we don't have GC info.
517 if (SectionVal.empty()) return;
519 StringRef Segment, Section;
520 unsigned TAA = 0, StubSize = 0;
522 std::string ErrorCode =
523 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
524 TAA, TAAParsed, StubSize);
525 if (!ErrorCode.empty())
526 // If invalid, report the error with report_fatal_error.
527 report_fatal_error("Invalid section specifier '" + Section + "': " +
531 const MCSectionMachO *S =
532 getContext().getMachOSection(Segment, Section, TAA, StubSize,
533 SectionKind::getDataNoRel());
534 Streamer.SwitchSection(S);
535 Streamer.EmitLabel(getContext().
536 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
537 Streamer.EmitIntValue(VersionVal, 4);
538 Streamer.EmitIntValue(ImageInfoFlags, 4);
539 Streamer.AddBlankLine();
542 static void checkMachOComdat(const GlobalValue *GV) {
543 const Comdat *C = GV->getComdat();
547 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
548 "' cannot be lowered.");
551 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
552 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
553 const TargetMachine &TM) const {
554 // Parse the section specifier and create it if valid.
555 StringRef Segment, Section;
556 unsigned TAA = 0, StubSize = 0;
559 checkMachOComdat(GV);
561 std::string ErrorCode =
562 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
563 TAA, TAAParsed, StubSize);
564 if (!ErrorCode.empty()) {
565 // If invalid, report the error with report_fatal_error.
566 report_fatal_error("Global variable '" + GV->getName() +
567 "' has an invalid section specifier '" +
568 GV->getSection() + "': " + ErrorCode + ".");
572 const MCSectionMachO *S =
573 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
575 // If TAA wasn't set by ParseSectionSpecifier() above,
576 // use the value returned by getMachOSection() as a default.
578 TAA = S->getTypeAndAttributes();
580 // Okay, now that we got the section, verify that the TAA & StubSize agree.
581 // If the user declared multiple globals with different section flags, we need
582 // to reject it here.
583 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
584 // If invalid, report the error with report_fatal_error.
585 report_fatal_error("Global variable '" + GV->getName() +
586 "' section type or attributes does not match previous"
587 " section specifier");
593 const MCSection *TargetLoweringObjectFileMachO::
594 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
595 Mangler &Mang, const TargetMachine &TM) const {
596 checkMachOComdat(GV);
598 // Handle thread local data.
599 if (Kind.isThreadBSS()) return TLSBSSSection;
600 if (Kind.isThreadData()) return TLSDataSection;
603 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
605 // If this is weak/linkonce, put this in a coalescable section, either in text
606 // or data depending on if it is writable.
607 if (GV->isWeakForLinker()) {
608 if (Kind.isReadOnly())
609 return ConstTextCoalSection;
610 return DataCoalSection;
613 // FIXME: Alignment check should be handled by section classifier.
614 if (Kind.isMergeable1ByteCString() &&
615 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
616 return CStringSection;
618 // Do not put 16-bit arrays in the UString section if they have an
619 // externally visible label, this runs into issues with certain linker
621 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
622 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
623 return UStringSection;
625 // With MachO only variables whose corresponding symbol starts with 'l' or
626 // 'L' can be merged, so we only try merging GVs with private linkage.
627 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
628 if (Kind.isMergeableConst4())
629 return FourByteConstantSection;
630 if (Kind.isMergeableConst8())
631 return EightByteConstantSection;
632 if (Kind.isMergeableConst16())
633 return SixteenByteConstantSection;
636 // Otherwise, if it is readonly, but not something we can specially optimize,
637 // just drop it in .const.
638 if (Kind.isReadOnly())
639 return ReadOnlySection;
641 // If this is marked const, put it into a const section. But if the dynamic
642 // linker needs to write to it, put it in the data segment.
643 if (Kind.isReadOnlyWithRel())
644 return ConstDataSection;
646 // Put zero initialized globals with strong external linkage in the
647 // DATA, __common section with the .zerofill directive.
648 if (Kind.isBSSExtern())
649 return DataCommonSection;
651 // Put zero initialized globals with local linkage in __DATA,__bss directive
652 // with the .zerofill directive (aka .lcomm).
653 if (Kind.isBSSLocal())
654 return DataBSSSection;
656 // Otherwise, just drop the variable in the normal data section.
661 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
662 const Constant *C) const {
663 // If this constant requires a relocation, we have to put it in the data
664 // segment, not in the text segment.
665 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
666 return ConstDataSection;
668 if (Kind.isMergeableConst4())
669 return FourByteConstantSection;
670 if (Kind.isMergeableConst8())
671 return EightByteConstantSection;
672 if (Kind.isMergeableConst16())
673 return SixteenByteConstantSection;
674 return ReadOnlySection; // .const
677 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
678 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
679 const TargetMachine &TM, MachineModuleInfo *MMI,
680 MCStreamer &Streamer) const {
681 // The mach-o version of this method defaults to returning a stub reference.
683 if (Encoding & DW_EH_PE_indirect) {
684 MachineModuleInfoMachO &MachOMMI =
685 MMI->getObjFileInfo<MachineModuleInfoMachO>();
688 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
690 // Add information about the stub reference to MachOMMI so that the stub
691 // gets emitted by the asmprinter.
692 MachineModuleInfoImpl::StubValueTy &StubSym =
693 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
694 MachOMMI.getGVStubEntry(SSym);
695 if (!StubSym.getPointer()) {
696 MCSymbol *Sym = TM.getSymbol(GV, Mang);
697 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
700 return TargetLoweringObjectFile::
701 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
702 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
705 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
709 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
710 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
711 MachineModuleInfo *MMI) const {
712 // The mach-o version of this method defaults to returning a stub reference.
713 MachineModuleInfoMachO &MachOMMI =
714 MMI->getObjFileInfo<MachineModuleInfoMachO>();
716 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
718 // Add information about the stub reference to MachOMMI so that the stub
719 // gets emitted by the asmprinter.
720 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
721 if (!StubSym.getPointer()) {
722 MCSymbol *Sym = TM.getSymbol(GV, Mang);
723 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
729 //===----------------------------------------------------------------------===//
731 //===----------------------------------------------------------------------===//
734 getCOFFSectionFlags(SectionKind K) {
739 COFF::IMAGE_SCN_MEM_DISCARDABLE;
742 COFF::IMAGE_SCN_MEM_EXECUTE |
743 COFF::IMAGE_SCN_MEM_READ |
744 COFF::IMAGE_SCN_CNT_CODE;
747 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
748 COFF::IMAGE_SCN_MEM_READ |
749 COFF::IMAGE_SCN_MEM_WRITE;
750 else if (K.isThreadLocal())
752 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
753 COFF::IMAGE_SCN_MEM_READ |
754 COFF::IMAGE_SCN_MEM_WRITE;
755 else if (K.isReadOnly() || K.isReadOnlyWithRel())
757 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
758 COFF::IMAGE_SCN_MEM_READ;
759 else if (K.isWriteable())
761 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
762 COFF::IMAGE_SCN_MEM_READ |
763 COFF::IMAGE_SCN_MEM_WRITE;
768 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
769 const Comdat *C = GV->getComdat();
770 assert(C && "expected GV to have a Comdat!");
772 StringRef ComdatGVName = C->getName();
773 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
775 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
776 "' does not exist.");
778 if (ComdatGV->getComdat() != C)
779 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
780 "' is not a key for its COMDAT.");
785 static int getSelectionForCOFF(const GlobalValue *GV) {
786 if (const Comdat *C = GV->getComdat()) {
787 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
788 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
789 ComdatKey = GA->getBaseObject();
790 if (ComdatKey == GV) {
791 switch (C->getSelectionKind()) {
793 return COFF::IMAGE_COMDAT_SELECT_ANY;
794 case Comdat::ExactMatch:
795 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
796 case Comdat::Largest:
797 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
798 case Comdat::NoDuplicates:
799 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
800 case Comdat::SameSize:
801 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
804 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
806 } else if (GV->isWeakForLinker()) {
807 return COFF::IMAGE_COMDAT_SELECT_ANY;
812 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
813 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
814 const TargetMachine &TM) const {
816 unsigned Characteristics = getCOFFSectionFlags(Kind);
817 StringRef Name = GV->getSection();
818 StringRef COMDATSymName = "";
819 if (GV->hasComdat()) {
820 Selection = getSelectionForCOFF(GV);
821 const GlobalValue *ComdatGV;
822 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
823 ComdatGV = getComdatGVForCOFF(GV);
827 if (!ComdatGV->hasPrivateLinkage()) {
828 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
829 COMDATSymName = Sym->getName();
830 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
835 return getContext().getCOFFSection(Name,
842 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
847 if (Kind.isThreadLocal())
849 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
855 const MCSection *TargetLoweringObjectFileCOFF::
856 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
857 Mangler &Mang, const TargetMachine &TM) const {
858 // If we have -ffunction-sections then we should emit the global value to a
859 // uniqued section specifically for it.
860 bool EmitUniquedSection;
862 EmitUniquedSection = TM.getFunctionSections();
864 EmitUniquedSection = TM.getDataSections();
866 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
867 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
868 unsigned Characteristics = getCOFFSectionFlags(Kind);
870 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
871 int Selection = getSelectionForCOFF(GV);
873 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
874 const GlobalValue *ComdatGV;
876 ComdatGV = getComdatGVForCOFF(GV);
880 if (!ComdatGV->hasPrivateLinkage()) {
881 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
882 StringRef COMDATSymName = Sym->getName();
883 return getContext().getCOFFSection(Name, Characteristics, Kind,
884 COMDATSymName, Selection);
891 if (Kind.isThreadLocal())
892 return TLSDataSection;
894 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
895 return ReadOnlySection;
897 // Note: we claim that common symbols are put in BSSSection, but they are
898 // really emitted with the magic .comm directive, which creates a symbol table
899 // entry but not a section.
900 if (Kind.isBSS() || Kind.isCommon())
906 StringRef TargetLoweringObjectFileCOFF::
907 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
908 const char *LibCmd = "/DEFAULTLIB:";
909 if (LinkerOption.startswith(LibCmd))
910 return LinkerOption.substr(strlen(LibCmd));
914 void TargetLoweringObjectFileCOFF::
915 emitModuleFlags(MCStreamer &Streamer,
916 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
917 Mangler &Mang, const TargetMachine &TM) const {
918 MDNode *LinkerOptions = nullptr;
920 // Look for the "Linker Options" flag, since it's the only one we support.
921 for (ArrayRef<Module::ModuleFlagEntry>::iterator
922 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
923 const Module::ModuleFlagEntry &MFE = *i;
924 StringRef Key = MFE.Key->getString();
925 Metadata *Val = MFE.Val;
926 if (Key == "Linker Options") {
927 LinkerOptions = cast<MDNode>(Val);
934 // Emit the linker options to the linker .drectve section. According to the
935 // spec, this section is a space-separated string containing flags for linker.
936 const MCSection *Sec = getDrectveSection();
937 Streamer.SwitchSection(Sec);
938 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
939 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
940 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
941 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
942 // Lead with a space for consistency with our dllexport implementation.
943 std::string Directive(" ");
944 Directive.append(MDOption->getString());
945 Streamer.EmitBytes(Directive);
950 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
951 unsigned Priority, const MCSymbol *KeySym) const {
952 return getContext().getAssociativeCOFFSection(
953 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
956 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
957 unsigned Priority, const MCSymbol *KeySym) const {
958 return getContext().getAssociativeCOFFSection(
959 cast<MCSectionCOFF>(StaticDtorSection), KeySym);