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"
41 using namespace dwarf;
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
48 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
49 MachineModuleInfo *MMI) const {
50 unsigned Encoding = getPersonalityEncoding();
51 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
52 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
53 TM.getSymbol(GV, Mang)->getName());
54 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
55 return TM.getSymbol(GV, Mang);
56 report_fatal_error("We do not support this DWARF encoding yet!");
59 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
60 const TargetMachine &TM,
61 const MCSymbol *Sym) const {
62 SmallString<64> NameData("DW.ref.");
63 NameData += Sym->getName();
64 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
65 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
66 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
67 StringRef Prefix = ".data.";
68 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
69 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
70 const MCSection *Sec = getContext().getELFSection(NameData,
73 SectionKind::getDataRel(),
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) {
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 // K.isMergeableConst() is left out to honour PR4650
185 if (K.isMergeableCString() || K.isMergeableConst4() ||
186 K.isMergeableConst8() || K.isMergeableConst16())
187 Flags |= ELF::SHF_MERGE;
189 if (K.isMergeableCString())
190 Flags |= ELF::SHF_STRINGS;
195 static const Comdat *getELFComdat(const GlobalValue *GV) {
196 const Comdat *C = GV->getComdat();
200 if (C->getSelectionKind() != Comdat::Any)
201 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
202 C->getName() + "' cannot be lowered.");
207 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
208 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
209 const TargetMachine &TM) const {
210 StringRef SectionName = GV->getSection();
212 // Infer section flags from the section name if we can.
213 Kind = getELFKindForNamedSection(SectionName, Kind);
215 StringRef Group = "";
216 unsigned Flags = getELFSectionFlags(Kind);
217 if (const Comdat *C = getELFComdat(GV)) {
218 Group = C->getName();
219 Flags |= ELF::SHF_GROUP;
221 return getContext().getELFSection(SectionName,
222 getELFSectionType(SectionName, Kind), Flags,
223 Kind, /*EntrySize=*/0, Group);
226 /// getSectionPrefixForGlobal - Return the section prefix name used by options
227 /// FunctionsSections and DataSections.
228 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
229 if (Kind.isText()) return ".text.";
230 if (Kind.isReadOnly()) return ".rodata.";
231 if (Kind.isBSS()) return ".bss.";
233 if (Kind.isThreadData()) return ".tdata.";
234 if (Kind.isThreadBSS()) return ".tbss.";
236 if (Kind.isDataNoRel()) return ".data.";
237 if (Kind.isDataRelLocal()) return ".data.rel.local.";
238 if (Kind.isDataRel()) return ".data.rel.";
239 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
241 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
242 return ".data.rel.ro.";
245 const MCSection *TargetLoweringObjectFileELF::
246 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
247 Mangler &Mang, const TargetMachine &TM) const {
248 // If we have -ffunction-section or -fdata-section then we should emit the
249 // global value to a uniqued section specifically for it.
250 bool EmitUniquedSection;
252 EmitUniquedSection = TM.getFunctionSections();
254 EmitUniquedSection = TM.getDataSections();
256 // If this global is linkonce/weak and the target handles this by emitting it
257 // into a 'uniqued' section name, create and return the section now.
258 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
260 StringRef Prefix = getSectionPrefixForGlobal(Kind);
262 SmallString<128> Name(Prefix);
263 TM.getNameWithPrefix(Name, GV, Mang, true);
265 StringRef Group = "";
266 unsigned Flags = getELFSectionFlags(Kind);
267 if (GV->isWeakForLinker() || GV->hasComdat()) {
268 if (const Comdat *C = getELFComdat(GV))
269 Group = C->getName();
271 Group = Name.substr(Prefix.size());
272 Flags |= ELF::SHF_GROUP;
275 return getContext().getELFSection(Name.str(),
276 getELFSectionType(Name.str(), Kind),
277 Flags, Kind, 0, Group);
280 if (Kind.isText()) return TextSection;
282 if (Kind.isMergeable1ByteCString() ||
283 Kind.isMergeable2ByteCString() ||
284 Kind.isMergeable4ByteCString()) {
286 // We also need alignment here.
287 // FIXME: this is getting the alignment of the character, not the
288 // alignment of the global!
290 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
292 const char *SizeSpec = ".rodata.str1.";
293 if (Kind.isMergeable2ByteCString())
294 SizeSpec = ".rodata.str2.";
295 else if (Kind.isMergeable4ByteCString())
296 SizeSpec = ".rodata.str4.";
298 assert(Kind.isMergeable1ByteCString() && "unknown string width");
301 std::string Name = SizeSpec + utostr(Align);
302 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
309 if (Kind.isMergeableConst()) {
310 if (Kind.isMergeableConst4() && MergeableConst4Section)
311 return MergeableConst4Section;
312 if (Kind.isMergeableConst8() && MergeableConst8Section)
313 return MergeableConst8Section;
314 if (Kind.isMergeableConst16() && MergeableConst16Section)
315 return MergeableConst16Section;
316 return ReadOnlySection; // .const
319 if (Kind.isReadOnly()) return ReadOnlySection;
321 if (Kind.isThreadData()) return TLSDataSection;
322 if (Kind.isThreadBSS()) return TLSBSSSection;
324 // Note: we claim that common symbols are put in BSSSection, but they are
325 // really emitted with the magic .comm directive, which creates a symbol table
326 // entry but not a section.
327 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
329 if (Kind.isDataNoRel()) return DataSection;
330 if (Kind.isDataRelLocal()) return DataRelLocalSection;
331 if (Kind.isDataRel()) return DataRelSection;
332 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
334 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
335 return DataRelROSection;
338 /// getSectionForConstant - Given a mergeable constant with the
339 /// specified size and relocation information, return a section that it
340 /// should be placed in.
342 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
343 const Constant *C) const {
344 if (Kind.isMergeableConst4() && MergeableConst4Section)
345 return MergeableConst4Section;
346 if (Kind.isMergeableConst8() && MergeableConst8Section)
347 return MergeableConst8Section;
348 if (Kind.isMergeableConst16() && MergeableConst16Section)
349 return MergeableConst16Section;
350 if (Kind.isReadOnly())
351 return ReadOnlySection;
353 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
354 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
355 return DataRelROSection;
358 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
359 unsigned Priority, const MCSymbol *KeySym) const {
360 // The default scheme is .ctor / .dtor, so we have to invert the priority
362 if (Priority == 65535)
363 return StaticCtorSection;
366 std::string Name = std::string(".init_array.") + utostr(Priority);
367 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
368 ELF::SHF_ALLOC | ELF::SHF_WRITE,
369 SectionKind::getDataRel());
371 std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
372 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
373 ELF::SHF_ALLOC |ELF::SHF_WRITE,
374 SectionKind::getDataRel());
378 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
379 unsigned Priority, const MCSymbol *KeySym) const {
380 // The default scheme is .ctor / .dtor, so we have to invert the priority
382 if (Priority == 65535)
383 return StaticDtorSection;
386 std::string Name = std::string(".fini_array.") + utostr(Priority);
387 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
388 ELF::SHF_ALLOC | ELF::SHF_WRITE,
389 SectionKind::getDataRel());
391 std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
392 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
393 ELF::SHF_ALLOC |ELF::SHF_WRITE,
394 SectionKind::getDataRel());
399 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
400 UseInitArray = UseInitArray_;
405 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
408 SectionKind::getDataRel());
410 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
413 SectionKind::getDataRel());
416 //===----------------------------------------------------------------------===//
418 //===----------------------------------------------------------------------===//
420 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
421 /// option string. Returns StringRef() if the option does not specify a library.
422 StringRef TargetLoweringObjectFileMachO::
423 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
424 const char *LibCmd = "-l";
425 if (LinkerOption.startswith(LibCmd))
426 return LinkerOption.substr(strlen(LibCmd));
430 /// emitModuleFlags - Perform code emission for module flags.
431 void TargetLoweringObjectFileMachO::
432 emitModuleFlags(MCStreamer &Streamer,
433 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
434 Mangler &Mang, const TargetMachine &TM) const {
435 unsigned VersionVal = 0;
436 unsigned ImageInfoFlags = 0;
437 MDNode *LinkerOptions = nullptr;
438 StringRef SectionVal;
440 for (ArrayRef<Module::ModuleFlagEntry>::iterator
441 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
442 const Module::ModuleFlagEntry &MFE = *i;
444 // Ignore flags with 'Require' behavior.
445 if (MFE.Behavior == Module::Require)
448 StringRef Key = MFE.Key->getString();
449 Value *Val = MFE.Val;
451 if (Key == "Objective-C Image Info Version") {
452 VersionVal = cast<ConstantInt>(Val)->getZExtValue();
453 } else if (Key == "Objective-C Garbage Collection" ||
454 Key == "Objective-C GC Only" ||
455 Key == "Objective-C Is Simulated") {
456 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
457 } else if (Key == "Objective-C Image Info Section") {
458 SectionVal = cast<MDString>(Val)->getString();
459 } else if (Key == "Linker Options") {
460 LinkerOptions = cast<MDNode>(Val);
464 // Emit the linker options if present.
466 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
467 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
468 SmallVector<std::string, 4> StrOptions;
470 // Convert to strings.
471 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
472 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
473 StrOptions.push_back(MDOption->getString());
476 Streamer.EmitLinkerOptions(StrOptions);
480 // The section is mandatory. If we don't have it, then we don't have GC info.
481 if (SectionVal.empty()) return;
483 StringRef Segment, Section;
484 unsigned TAA = 0, StubSize = 0;
486 std::string ErrorCode =
487 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
488 TAA, TAAParsed, StubSize);
489 if (!ErrorCode.empty())
490 // If invalid, report the error with report_fatal_error.
491 report_fatal_error("Invalid section specifier '" + Section + "': " +
495 const MCSectionMachO *S =
496 getContext().getMachOSection(Segment, Section, TAA, StubSize,
497 SectionKind::getDataNoRel());
498 Streamer.SwitchSection(S);
499 Streamer.EmitLabel(getContext().
500 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
501 Streamer.EmitIntValue(VersionVal, 4);
502 Streamer.EmitIntValue(ImageInfoFlags, 4);
503 Streamer.AddBlankLine();
506 static void checkMachOComdat(const GlobalValue *GV) {
507 const Comdat *C = GV->getComdat();
511 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
512 "' cannot be lowered.");
515 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
516 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
517 const TargetMachine &TM) const {
518 // Parse the section specifier and create it if valid.
519 StringRef Segment, Section;
520 unsigned TAA = 0, StubSize = 0;
523 checkMachOComdat(GV);
525 std::string ErrorCode =
526 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
527 TAA, TAAParsed, StubSize);
528 if (!ErrorCode.empty()) {
529 // If invalid, report the error with report_fatal_error.
530 report_fatal_error("Global variable '" + GV->getName() +
531 "' has an invalid section specifier '" +
532 GV->getSection() + "': " + ErrorCode + ".");
536 const MCSectionMachO *S =
537 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
539 // If TAA wasn't set by ParseSectionSpecifier() above,
540 // use the value returned by getMachOSection() as a default.
542 TAA = S->getTypeAndAttributes();
544 // Okay, now that we got the section, verify that the TAA & StubSize agree.
545 // If the user declared multiple globals with different section flags, we need
546 // to reject it here.
547 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
548 // If invalid, report the error with report_fatal_error.
549 report_fatal_error("Global variable '" + GV->getName() +
550 "' section type or attributes does not match previous"
551 " section specifier");
557 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
558 const MCSection &Section) const {
559 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
561 // Sections holding 1 byte strings are atomized based on the data
563 // Sections holding 2 byte strings require symbols in order to be
565 // There is no dedicated section for 4 byte strings.
566 if (SMO.getKind().isMergeable1ByteCString())
569 if (SMO.getSegmentName() == "__DATA" &&
570 SMO.getSectionName() == "__cfstring")
573 switch (SMO.getType()) {
577 // These sections are atomized at the element boundaries without using
579 case MachO::S_4BYTE_LITERALS:
580 case MachO::S_8BYTE_LITERALS:
581 case MachO::S_16BYTE_LITERALS:
582 case MachO::S_LITERAL_POINTERS:
583 case MachO::S_NON_LAZY_SYMBOL_POINTERS:
584 case MachO::S_LAZY_SYMBOL_POINTERS:
585 case MachO::S_MOD_INIT_FUNC_POINTERS:
586 case MachO::S_MOD_TERM_FUNC_POINTERS:
587 case MachO::S_INTERPOSING:
592 const MCSection *TargetLoweringObjectFileMachO::
593 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
594 Mangler &Mang, const TargetMachine &TM) const {
595 checkMachOComdat(GV);
597 // Handle thread local data.
598 if (Kind.isThreadBSS()) return TLSBSSSection;
599 if (Kind.isThreadData()) return TLSDataSection;
602 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
604 // If this is weak/linkonce, put this in a coalescable section, either in text
605 // or data depending on if it is writable.
606 if (GV->isWeakForLinker()) {
607 if (Kind.isReadOnly())
608 return ConstTextCoalSection;
609 return DataCoalSection;
612 // FIXME: Alignment check should be handled by section classifier.
613 if (Kind.isMergeable1ByteCString() &&
614 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
615 return CStringSection;
617 // Do not put 16-bit arrays in the UString section if they have an
618 // externally visible label, this runs into issues with certain linker
620 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
621 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
622 return UStringSection;
624 if (Kind.isMergeableConst()) {
625 if (Kind.isMergeableConst4())
626 return FourByteConstantSection;
627 if (Kind.isMergeableConst8())
628 return EightByteConstantSection;
629 if (Kind.isMergeableConst16())
630 return SixteenByteConstantSection;
633 // Otherwise, if it is readonly, but not something we can specially optimize,
634 // just drop it in .const.
635 if (Kind.isReadOnly())
636 return ReadOnlySection;
638 // If this is marked const, put it into a const section. But if the dynamic
639 // linker needs to write to it, put it in the data segment.
640 if (Kind.isReadOnlyWithRel())
641 return ConstDataSection;
643 // Put zero initialized globals with strong external linkage in the
644 // DATA, __common section with the .zerofill directive.
645 if (Kind.isBSSExtern())
646 return DataCommonSection;
648 // Put zero initialized globals with local linkage in __DATA,__bss directive
649 // with the .zerofill directive (aka .lcomm).
650 if (Kind.isBSSLocal())
651 return DataBSSSection;
653 // Otherwise, just drop the variable in the normal data section.
658 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
659 const Constant *C) const {
660 // If this constant requires a relocation, we have to put it in the data
661 // segment, not in the text segment.
662 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
663 return ConstDataSection;
665 if (Kind.isMergeableConst4())
666 return FourByteConstantSection;
667 if (Kind.isMergeableConst8())
668 return EightByteConstantSection;
669 if (Kind.isMergeableConst16())
670 return SixteenByteConstantSection;
671 return ReadOnlySection; // .const
674 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
675 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
676 const TargetMachine &TM, MachineModuleInfo *MMI,
677 MCStreamer &Streamer) const {
678 // The mach-o version of this method defaults to returning a stub reference.
680 if (Encoding & DW_EH_PE_indirect) {
681 MachineModuleInfoMachO &MachOMMI =
682 MMI->getObjFileInfo<MachineModuleInfoMachO>();
685 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
687 // Add information about the stub reference to MachOMMI so that the stub
688 // gets emitted by the asmprinter.
689 MachineModuleInfoImpl::StubValueTy &StubSym =
690 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
691 MachOMMI.getGVStubEntry(SSym);
692 if (!StubSym.getPointer()) {
693 MCSymbol *Sym = TM.getSymbol(GV, Mang);
694 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
697 return TargetLoweringObjectFile::
698 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
699 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
702 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
706 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
707 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
708 MachineModuleInfo *MMI) const {
709 // The mach-o version of this method defaults to returning a stub reference.
710 MachineModuleInfoMachO &MachOMMI =
711 MMI->getObjFileInfo<MachineModuleInfoMachO>();
713 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
715 // Add information about the stub reference to MachOMMI so that the stub
716 // gets emitted by the asmprinter.
717 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
718 if (!StubSym.getPointer()) {
719 MCSymbol *Sym = TM.getSymbol(GV, Mang);
720 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
726 //===----------------------------------------------------------------------===//
728 //===----------------------------------------------------------------------===//
731 getCOFFSectionFlags(SectionKind K) {
736 COFF::IMAGE_SCN_MEM_DISCARDABLE;
739 COFF::IMAGE_SCN_MEM_EXECUTE |
740 COFF::IMAGE_SCN_MEM_READ |
741 COFF::IMAGE_SCN_CNT_CODE;
744 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
745 COFF::IMAGE_SCN_MEM_READ |
746 COFF::IMAGE_SCN_MEM_WRITE;
747 else if (K.isThreadLocal())
749 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
750 COFF::IMAGE_SCN_MEM_READ |
751 COFF::IMAGE_SCN_MEM_WRITE;
752 else if (K.isReadOnly())
754 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
755 COFF::IMAGE_SCN_MEM_READ;
756 else if (K.isWriteable())
758 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
759 COFF::IMAGE_SCN_MEM_READ |
760 COFF::IMAGE_SCN_MEM_WRITE;
765 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
766 const Comdat *C = GV->getComdat();
767 assert(C && "expected GV to have a Comdat!");
769 StringRef ComdatGVName = C->getName();
770 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
772 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
773 "' does not exist.");
775 if (ComdatGV->getComdat() != C)
776 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
777 "' is not a key for it's COMDAT.");
782 static int getSelectionForCOFF(const GlobalValue *GV) {
783 if (const Comdat *C = GV->getComdat()) {
784 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
785 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
786 ComdatKey = GA->getBaseObject();
787 if (ComdatKey == GV) {
788 switch (C->getSelectionKind()) {
790 return COFF::IMAGE_COMDAT_SELECT_ANY;
791 case Comdat::ExactMatch:
792 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
793 case Comdat::Largest:
794 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
795 case Comdat::NoDuplicates:
796 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
797 case Comdat::SameSize:
798 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
801 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
803 } else if (GV->isWeakForLinker()) {
804 return COFF::IMAGE_COMDAT_SELECT_ANY;
809 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
810 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
811 const TargetMachine &TM) const {
813 unsigned Characteristics = getCOFFSectionFlags(Kind);
814 StringRef Name = GV->getSection();
815 StringRef COMDATSymName = "";
816 if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
817 Selection = getSelectionForCOFF(GV);
818 const GlobalValue *ComdatGV;
819 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
820 ComdatGV = getComdatGVForCOFF(GV);
824 if (!ComdatGV->hasPrivateLinkage()) {
825 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
826 COMDATSymName = Sym->getName();
827 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
832 return getContext().getCOFFSection(Name,
839 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
844 if (Kind.isThreadLocal())
846 if (Kind.isWriteable())
852 const MCSection *TargetLoweringObjectFileCOFF::
853 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
854 Mangler &Mang, const TargetMachine &TM) const {
855 // If we have -ffunction-sections then we should emit the global value to a
856 // uniqued section specifically for it.
857 bool EmitUniquedSection;
859 EmitUniquedSection = TM.getFunctionSections();
861 EmitUniquedSection = TM.getDataSections();
863 // If this global is linkonce/weak and the target handles this by emitting it
864 // into a 'uniqued' section name, create and return the section now.
865 // Section names depend on the name of the symbol which is not feasible if the
866 // symbol has private linkage.
867 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
869 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
870 unsigned Characteristics = getCOFFSectionFlags(Kind);
872 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
873 int Selection = getSelectionForCOFF(GV);
875 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
876 const GlobalValue *ComdatGV;
878 ComdatGV = getComdatGVForCOFF(GV);
882 if (!ComdatGV->hasPrivateLinkage()) {
883 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
884 StringRef COMDATSymName = Sym->getName();
885 return getContext().getCOFFSection(Name, Characteristics, Kind,
886 COMDATSymName, Selection);
893 if (Kind.isThreadLocal())
894 return TLSDataSection;
896 if (Kind.isReadOnly())
897 return ReadOnlySection;
899 // Note: we claim that common symbols are put in BSSSection, but they are
900 // really emitted with the magic .comm directive, which creates a symbol table
901 // entry but not a section.
902 if (Kind.isBSS() || Kind.isCommon())
908 StringRef TargetLoweringObjectFileCOFF::
909 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
910 const char *LibCmd = "/DEFAULTLIB:";
911 if (LinkerOption.startswith(LibCmd))
912 return LinkerOption.substr(strlen(LibCmd));
916 void TargetLoweringObjectFileCOFF::
917 emitModuleFlags(MCStreamer &Streamer,
918 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
919 Mangler &Mang, const TargetMachine &TM) const {
920 MDNode *LinkerOptions = nullptr;
922 // Look for the "Linker Options" flag, since it's the only one we support.
923 for (ArrayRef<Module::ModuleFlagEntry>::iterator
924 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
925 const Module::ModuleFlagEntry &MFE = *i;
926 StringRef Key = MFE.Key->getString();
927 Value *Val = MFE.Val;
928 if (Key == "Linker Options") {
929 LinkerOptions = cast<MDNode>(Val);
936 // Emit the linker options to the linker .drectve section. According to the
937 // spec, this section is a space-separated string containing flags for linker.
938 const MCSection *Sec = getDrectveSection();
939 Streamer.SwitchSection(Sec);
940 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
941 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
942 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
943 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
944 StringRef Op = MDOption->getString();
945 // Lead with a space for consistency with our dllexport implementation.
946 std::string Escaped(" ");
947 if (Op.find(" ") != StringRef::npos) {
948 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
949 // how to escape quotes, but it probably uses this algorithm:
950 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
951 // FIXME: Reuse escaping code from Support/Windows/Program.inc
952 Escaped.push_back('\"');
954 Escaped.push_back('\"');
958 Streamer.EmitBytes(Escaped);
963 static const MCSection *getAssociativeCOFFSection(MCContext &Ctx,
964 const MCSection *Sec,
965 const MCSymbol *KeySym) {
966 // Return the normal section if we don't have to be associative.
970 // Make an associative section with the same name and kind as the normal
972 const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec);
973 unsigned Characteristics =
974 SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
975 return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics,
976 SecCOFF->getKind(), KeySym->getName(),
977 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
980 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
981 unsigned Priority, const MCSymbol *KeySym) const {
982 return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym);
985 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
986 unsigned Priority, const MCSymbol *KeySym) const {
987 return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym);