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 const MCSection *TargetLoweringObjectFileELF::
253 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
254 Mangler &Mang, const TargetMachine &TM) const {
255 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
257 // If we have -ffunction-section or -fdata-section then we should emit the
258 // global value to a uniqued section specifically for it.
259 bool EmitUniquedSection = false;
260 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
262 EmitUniquedSection = TM.getFunctionSections();
264 EmitUniquedSection = TM.getDataSections();
267 if (EmitUniquedSection || GV->hasComdat()) {
268 StringRef Prefix = getSectionPrefixForGlobal(Kind);
270 SmallString<128> Name(Prefix);
271 bool UniqueSectionNames = TM.getUniqueSectionNames();
272 if (UniqueSectionNames) {
274 TM.getNameWithPrefix(Name, GV, Mang, true);
276 StringRef Group = "";
277 if (const Comdat *C = getELFComdat(GV)) {
278 Flags |= ELF::SHF_GROUP;
279 Group = C->getName();
282 return getContext().getELFSection(Name, getELFSectionType(Name, Kind),
283 Flags, 0, Group, !UniqueSectionNames);
286 if (Kind.isText()) return TextSection;
288 if (Kind.isMergeableCString()) {
290 // We also need alignment here.
291 // FIXME: this is getting the alignment of the character, not the
292 // alignment of the global!
294 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
296 unsigned EntrySize = 1;
297 if (Kind.isMergeable2ByteCString())
299 else if (Kind.isMergeable4ByteCString())
302 assert(Kind.isMergeable1ByteCString() && "unknown string width");
304 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
305 std::string Name = SizeSpec + utostr(Align);
306 return getContext().getELFSection(
307 Name, ELF::SHT_PROGBITS,
308 ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
311 if (Kind.isMergeableConst()) {
312 if (Kind.isMergeableConst4() && MergeableConst4Section)
313 return MergeableConst4Section;
314 if (Kind.isMergeableConst8() && MergeableConst8Section)
315 return MergeableConst8Section;
316 if (Kind.isMergeableConst16() && MergeableConst16Section)
317 return MergeableConst16Section;
318 return ReadOnlySection; // .const
321 if (Kind.isReadOnly()) return ReadOnlySection;
323 if (Kind.isThreadData()) return TLSDataSection;
324 if (Kind.isThreadBSS()) return TLSBSSSection;
326 // Note: we claim that common symbols are put in BSSSection, but they are
327 // really emitted with the magic .comm directive, which creates a symbol table
328 // entry but not a section.
329 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
331 if (Kind.isDataNoRel()) return DataSection;
332 if (Kind.isDataRelLocal()) return DataRelLocalSection;
333 if (Kind.isDataRel()) return DataRelSection;
334 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
336 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
337 return DataRelROSection;
340 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
341 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
342 // If the function can be removed, produce a unique section so that
343 // the table doesn't prevent the removal.
344 const Comdat *C = F.getComdat();
345 bool EmitUniqueSection = TM.getFunctionSections() || C;
346 if (!EmitUniqueSection)
347 return ReadOnlySection;
349 SmallString<128> Name(".rodata.");
350 TM.getNameWithPrefix(Name, &F, Mang, true);
352 unsigned Flags = ELF::SHF_ALLOC;
353 StringRef Group = "";
355 Flags |= ELF::SHF_GROUP;
356 Group = C->getName();
359 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 0, Group);
362 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
363 bool UsesLabelDifference, const Function &F) const {
364 // We can always create relative relocations, so use another section
365 // that can be marked non-executable.
369 /// getSectionForConstant - Given a mergeable constant with the
370 /// specified size and relocation information, return a section that it
371 /// should be placed in.
373 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
374 const Constant *C) const {
375 if (Kind.isMergeableConst4() && MergeableConst4Section)
376 return MergeableConst4Section;
377 if (Kind.isMergeableConst8() && MergeableConst8Section)
378 return MergeableConst8Section;
379 if (Kind.isMergeableConst16() && MergeableConst16Section)
380 return MergeableConst16Section;
381 if (Kind.isReadOnly())
382 return ReadOnlySection;
384 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
385 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
386 return DataRelROSection;
389 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
393 const MCSymbol *KeySym) {
396 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
397 StringRef COMDAT = KeySym ? KeySym->getName() : "";
400 Flags |= ELF::SHF_GROUP;
404 Type = ELF::SHT_INIT_ARRAY;
405 Name = ".init_array";
407 Type = ELF::SHT_FINI_ARRAY;
408 Name = ".fini_array";
410 if (Priority != 65535) {
412 Name += utostr(Priority);
415 // The default scheme is .ctor / .dtor, so we have to invert the priority
421 if (Priority != 65535) {
423 Name += utostr(65535 - Priority);
425 Type = ELF::SHT_PROGBITS;
428 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
431 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
432 unsigned Priority, const MCSymbol *KeySym) const {
433 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
437 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
438 unsigned Priority, const MCSymbol *KeySym) const {
439 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
444 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
445 UseInitArray = UseInitArray_;
449 StaticCtorSection = getContext().getELFSection(
450 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
451 StaticDtorSection = getContext().getELFSection(
452 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
455 //===----------------------------------------------------------------------===//
457 //===----------------------------------------------------------------------===//
459 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
460 /// option string. Returns StringRef() if the option does not specify a library.
461 StringRef TargetLoweringObjectFileMachO::
462 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
463 const char *LibCmd = "-l";
464 if (LinkerOption.startswith(LibCmd))
465 return LinkerOption.substr(strlen(LibCmd));
469 /// emitModuleFlags - Perform code emission for module flags.
470 void TargetLoweringObjectFileMachO::
471 emitModuleFlags(MCStreamer &Streamer,
472 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
473 Mangler &Mang, const TargetMachine &TM) const {
474 unsigned VersionVal = 0;
475 unsigned ImageInfoFlags = 0;
476 MDNode *LinkerOptions = nullptr;
477 StringRef SectionVal;
479 for (ArrayRef<Module::ModuleFlagEntry>::iterator
480 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
481 const Module::ModuleFlagEntry &MFE = *i;
483 // Ignore flags with 'Require' behavior.
484 if (MFE.Behavior == Module::Require)
487 StringRef Key = MFE.Key->getString();
488 Metadata *Val = MFE.Val;
490 if (Key == "Objective-C Image Info Version") {
491 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
492 } else if (Key == "Objective-C Garbage Collection" ||
493 Key == "Objective-C GC Only" ||
494 Key == "Objective-C Is Simulated" ||
495 Key == "Objective-C Image Swift Version") {
496 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
497 } else if (Key == "Objective-C Image Info Section") {
498 SectionVal = cast<MDString>(Val)->getString();
499 } else if (Key == "Linker Options") {
500 LinkerOptions = cast<MDNode>(Val);
504 // Emit the linker options if present.
506 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
507 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
508 SmallVector<std::string, 4> StrOptions;
510 // Convert to strings.
511 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
512 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
513 StrOptions.push_back(MDOption->getString());
516 Streamer.EmitLinkerOptions(StrOptions);
520 // The section is mandatory. If we don't have it, then we don't have GC info.
521 if (SectionVal.empty()) return;
523 StringRef Segment, Section;
524 unsigned TAA = 0, StubSize = 0;
526 std::string ErrorCode =
527 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
528 TAA, TAAParsed, StubSize);
529 if (!ErrorCode.empty())
530 // If invalid, report the error with report_fatal_error.
531 report_fatal_error("Invalid section specifier '" + Section + "': " +
535 const MCSectionMachO *S =
536 getContext().getMachOSection(Segment, Section, TAA, StubSize,
537 SectionKind::getDataNoRel());
538 Streamer.SwitchSection(S);
539 Streamer.EmitLabel(getContext().
540 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
541 Streamer.EmitIntValue(VersionVal, 4);
542 Streamer.EmitIntValue(ImageInfoFlags, 4);
543 Streamer.AddBlankLine();
546 static void checkMachOComdat(const GlobalValue *GV) {
547 const Comdat *C = GV->getComdat();
551 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
552 "' cannot be lowered.");
555 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
556 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
557 const TargetMachine &TM) const {
558 // Parse the section specifier and create it if valid.
559 StringRef Segment, Section;
560 unsigned TAA = 0, StubSize = 0;
563 checkMachOComdat(GV);
565 std::string ErrorCode =
566 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
567 TAA, TAAParsed, StubSize);
568 if (!ErrorCode.empty()) {
569 // If invalid, report the error with report_fatal_error.
570 report_fatal_error("Global variable '" + GV->getName() +
571 "' has an invalid section specifier '" +
572 GV->getSection() + "': " + ErrorCode + ".");
576 const MCSectionMachO *S =
577 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
579 // If TAA wasn't set by ParseSectionSpecifier() above,
580 // use the value returned by getMachOSection() as a default.
582 TAA = S->getTypeAndAttributes();
584 // Okay, now that we got the section, verify that the TAA & StubSize agree.
585 // If the user declared multiple globals with different section flags, we need
586 // to reject it here.
587 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
588 // If invalid, report the error with report_fatal_error.
589 report_fatal_error("Global variable '" + GV->getName() +
590 "' section type or attributes does not match previous"
591 " section specifier");
597 const MCSection *TargetLoweringObjectFileMachO::
598 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
599 Mangler &Mang, const TargetMachine &TM) const {
600 checkMachOComdat(GV);
602 // Handle thread local data.
603 if (Kind.isThreadBSS()) return TLSBSSSection;
604 if (Kind.isThreadData()) return TLSDataSection;
607 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
609 // If this is weak/linkonce, put this in a coalescable section, either in text
610 // or data depending on if it is writable.
611 if (GV->isWeakForLinker()) {
612 if (Kind.isReadOnly())
613 return ConstTextCoalSection;
614 return DataCoalSection;
617 // FIXME: Alignment check should be handled by section classifier.
618 if (Kind.isMergeable1ByteCString() &&
619 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
620 return CStringSection;
622 // Do not put 16-bit arrays in the UString section if they have an
623 // externally visible label, this runs into issues with certain linker
625 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
626 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
627 return UStringSection;
629 // With MachO only variables whose corresponding symbol starts with 'l' or
630 // 'L' can be merged, so we only try merging GVs with private linkage.
631 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
632 if (Kind.isMergeableConst4())
633 return FourByteConstantSection;
634 if (Kind.isMergeableConst8())
635 return EightByteConstantSection;
636 if (Kind.isMergeableConst16())
637 return SixteenByteConstantSection;
640 // Otherwise, if it is readonly, but not something we can specially optimize,
641 // just drop it in .const.
642 if (Kind.isReadOnly())
643 return ReadOnlySection;
645 // If this is marked const, put it into a const section. But if the dynamic
646 // linker needs to write to it, put it in the data segment.
647 if (Kind.isReadOnlyWithRel())
648 return ConstDataSection;
650 // Put zero initialized globals with strong external linkage in the
651 // DATA, __common section with the .zerofill directive.
652 if (Kind.isBSSExtern())
653 return DataCommonSection;
655 // Put zero initialized globals with local linkage in __DATA,__bss directive
656 // with the .zerofill directive (aka .lcomm).
657 if (Kind.isBSSLocal())
658 return DataBSSSection;
660 // Otherwise, just drop the variable in the normal data section.
665 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
666 const Constant *C) const {
667 // If this constant requires a relocation, we have to put it in the data
668 // segment, not in the text segment.
669 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
670 return ConstDataSection;
672 if (Kind.isMergeableConst4())
673 return FourByteConstantSection;
674 if (Kind.isMergeableConst8())
675 return EightByteConstantSection;
676 if (Kind.isMergeableConst16())
677 return SixteenByteConstantSection;
678 return ReadOnlySection; // .const
681 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
682 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
683 const TargetMachine &TM, MachineModuleInfo *MMI,
684 MCStreamer &Streamer) const {
685 // The mach-o version of this method defaults to returning a stub reference.
687 if (Encoding & DW_EH_PE_indirect) {
688 MachineModuleInfoMachO &MachOMMI =
689 MMI->getObjFileInfo<MachineModuleInfoMachO>();
692 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
694 // Add information about the stub reference to MachOMMI so that the stub
695 // gets emitted by the asmprinter.
696 MachineModuleInfoImpl::StubValueTy &StubSym =
697 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
698 MachOMMI.getGVStubEntry(SSym);
699 if (!StubSym.getPointer()) {
700 MCSymbol *Sym = TM.getSymbol(GV, Mang);
701 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
704 return TargetLoweringObjectFile::
705 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
706 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
709 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
713 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
714 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
715 MachineModuleInfo *MMI) const {
716 // The mach-o version of this method defaults to returning a stub reference.
717 MachineModuleInfoMachO &MachOMMI =
718 MMI->getObjFileInfo<MachineModuleInfoMachO>();
720 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
722 // Add information about the stub reference to MachOMMI so that the stub
723 // gets emitted by the asmprinter.
724 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
725 if (!StubSym.getPointer()) {
726 MCSymbol *Sym = TM.getSymbol(GV, Mang);
727 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
733 //===----------------------------------------------------------------------===//
735 //===----------------------------------------------------------------------===//
738 getCOFFSectionFlags(SectionKind K) {
743 COFF::IMAGE_SCN_MEM_DISCARDABLE;
746 COFF::IMAGE_SCN_MEM_EXECUTE |
747 COFF::IMAGE_SCN_MEM_READ |
748 COFF::IMAGE_SCN_CNT_CODE;
751 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
752 COFF::IMAGE_SCN_MEM_READ |
753 COFF::IMAGE_SCN_MEM_WRITE;
754 else if (K.isThreadLocal())
756 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
757 COFF::IMAGE_SCN_MEM_READ |
758 COFF::IMAGE_SCN_MEM_WRITE;
759 else if (K.isReadOnly() || K.isReadOnlyWithRel())
761 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
762 COFF::IMAGE_SCN_MEM_READ;
763 else if (K.isWriteable())
765 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
766 COFF::IMAGE_SCN_MEM_READ |
767 COFF::IMAGE_SCN_MEM_WRITE;
772 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
773 const Comdat *C = GV->getComdat();
774 assert(C && "expected GV to have a Comdat!");
776 StringRef ComdatGVName = C->getName();
777 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
779 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
780 "' does not exist.");
782 if (ComdatGV->getComdat() != C)
783 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
784 "' is not a key for its COMDAT.");
789 static int getSelectionForCOFF(const GlobalValue *GV) {
790 if (const Comdat *C = GV->getComdat()) {
791 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
792 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
793 ComdatKey = GA->getBaseObject();
794 if (ComdatKey == GV) {
795 switch (C->getSelectionKind()) {
797 return COFF::IMAGE_COMDAT_SELECT_ANY;
798 case Comdat::ExactMatch:
799 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
800 case Comdat::Largest:
801 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
802 case Comdat::NoDuplicates:
803 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
804 case Comdat::SameSize:
805 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
808 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
810 } else if (GV->isWeakForLinker()) {
811 return COFF::IMAGE_COMDAT_SELECT_ANY;
816 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
817 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
818 const TargetMachine &TM) const {
820 unsigned Characteristics = getCOFFSectionFlags(Kind);
821 StringRef Name = GV->getSection();
822 StringRef COMDATSymName = "";
823 if (GV->hasComdat()) {
824 Selection = getSelectionForCOFF(GV);
825 const GlobalValue *ComdatGV;
826 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
827 ComdatGV = getComdatGVForCOFF(GV);
831 if (!ComdatGV->hasPrivateLinkage()) {
832 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
833 COMDATSymName = Sym->getName();
834 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
839 return getContext().getCOFFSection(Name,
846 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
851 if (Kind.isThreadLocal())
853 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
859 const MCSection *TargetLoweringObjectFileCOFF::
860 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
861 Mangler &Mang, const TargetMachine &TM) const {
862 // If we have -ffunction-sections then we should emit the global value to a
863 // uniqued section specifically for it.
864 bool EmitUniquedSection;
866 EmitUniquedSection = TM.getFunctionSections();
868 EmitUniquedSection = TM.getDataSections();
870 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
871 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
872 unsigned Characteristics = getCOFFSectionFlags(Kind);
874 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
875 int Selection = getSelectionForCOFF(GV);
877 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
878 const GlobalValue *ComdatGV;
880 ComdatGV = getComdatGVForCOFF(GV);
884 if (!ComdatGV->hasPrivateLinkage()) {
885 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
886 StringRef COMDATSymName = Sym->getName();
887 return getContext().getCOFFSection(Name, Characteristics, Kind,
888 COMDATSymName, Selection);
895 if (Kind.isThreadLocal())
896 return TLSDataSection;
898 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
899 return ReadOnlySection;
901 // Note: we claim that common symbols are put in BSSSection, but they are
902 // really emitted with the magic .comm directive, which creates a symbol table
903 // entry but not a section.
904 if (Kind.isBSS() || Kind.isCommon())
910 StringRef TargetLoweringObjectFileCOFF::
911 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
912 const char *LibCmd = "/DEFAULTLIB:";
913 if (LinkerOption.startswith(LibCmd))
914 return LinkerOption.substr(strlen(LibCmd));
918 void TargetLoweringObjectFileCOFF::
919 emitModuleFlags(MCStreamer &Streamer,
920 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
921 Mangler &Mang, const TargetMachine &TM) const {
922 MDNode *LinkerOptions = nullptr;
924 // Look for the "Linker Options" flag, since it's the only one we support.
925 for (ArrayRef<Module::ModuleFlagEntry>::iterator
926 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
927 const Module::ModuleFlagEntry &MFE = *i;
928 StringRef Key = MFE.Key->getString();
929 Metadata *Val = MFE.Val;
930 if (Key == "Linker Options") {
931 LinkerOptions = cast<MDNode>(Val);
938 // Emit the linker options to the linker .drectve section. According to the
939 // spec, this section is a space-separated string containing flags for linker.
940 const MCSection *Sec = getDrectveSection();
941 Streamer.SwitchSection(Sec);
942 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
943 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
944 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
945 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
946 StringRef Op = MDOption->getString();
947 // Lead with a space for consistency with our dllexport implementation.
948 std::string Escaped(" ");
949 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
950 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
951 // how to escape quotes, but it probably uses this algorithm:
952 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
953 // FIXME: Reuse escaping code from Support/Windows/Program.inc
954 Escaped.push_back('\"');
956 Escaped.push_back('\"');
960 Streamer.EmitBytes(Escaped);
965 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
966 unsigned Priority, const MCSymbol *KeySym) const {
967 return getContext().getAssociativeCOFFSection(
968 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
971 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
972 unsigned Priority, const MCSymbol *KeySym) const {
973 return getContext().getAssociativeCOFFSection(
974 cast<MCSectionCOFF>(StaticDtorSection), KeySym);