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/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSectionELF.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbolELF.h"
35 #include "llvm/MC/MCValue.h"
36 #include "llvm/ProfileData/InstrProf.h"
37 #include "llvm/Support/COFF.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ELF.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
46 using namespace dwarf;
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
53 const GlobalValue *GV, const TargetMachine &TM,
54 MachineModuleInfo *MMI) const {
55 unsigned Encoding = getPersonalityEncoding();
56 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
57 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
58 TM.getSymbol(GV)->getName());
59 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
60 return TM.getSymbol(GV);
61 report_fatal_error("We do not support this DWARF encoding yet!");
64 void TargetLoweringObjectFileELF::emitPersonalityValue(
65 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
66 SmallString<64> NameData("DW.ref.");
67 NameData += Sym->getName();
69 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
70 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
71 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
72 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
73 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
74 ELF::SHT_PROGBITS, Flags, 0);
75 unsigned Size = DL.getPointerSize();
76 Streamer.SwitchSection(Sec);
77 Streamer.EmitValueToAlignment(DL.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, const TargetMachine &TM,
88 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
90 if (Encoding & dwarf::DW_EH_PE_indirect) {
91 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
93 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
95 // Add information about the stub reference to ELFMMI so that the stub
96 // gets emitted by the asmprinter.
97 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
98 if (!StubSym.getPointer()) {
99 MCSymbol *Sym = TM.getSymbol(GV);
100 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
103 return TargetLoweringObjectFile::
104 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
105 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
108 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
113 getELFKindForNamedSection(StringRef Name, SectionKind K) {
114 // N.B.: The defaults used in here are no the same ones used in MC.
115 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
116 // both gas and MC will produce a section with no flags. Given
117 // section(".eh_frame") gcc will produce:
119 // .section .eh_frame,"a",@progbits
121 if (Name == getInstrProfCoverageSectionName(false))
122 return SectionKind::getMetadata();
124 if (Name.empty() || Name[0] != '.') return K;
126 // Some lame default implementation based on some magic section names.
127 if (Name == ".bss" ||
128 Name.startswith(".bss.") ||
129 Name.startswith(".gnu.linkonce.b.") ||
130 Name.startswith(".llvm.linkonce.b.") ||
132 Name.startswith(".sbss.") ||
133 Name.startswith(".gnu.linkonce.sb.") ||
134 Name.startswith(".llvm.linkonce.sb."))
135 return SectionKind::getBSS();
137 if (Name == ".tdata" ||
138 Name.startswith(".tdata.") ||
139 Name.startswith(".gnu.linkonce.td.") ||
140 Name.startswith(".llvm.linkonce.td."))
141 return SectionKind::getThreadData();
143 if (Name == ".tbss" ||
144 Name.startswith(".tbss.") ||
145 Name.startswith(".gnu.linkonce.tb.") ||
146 Name.startswith(".llvm.linkonce.tb."))
147 return SectionKind::getThreadBSS();
153 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
154 // Use SHT_NOTE for section whose name starts with ".note" to allow
155 // emitting ELF notes from C variable declaration.
156 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
157 if (Name.startswith(".note"))
158 return ELF::SHT_NOTE;
160 if (Name == ".init_array")
161 return ELF::SHT_INIT_ARRAY;
163 if (Name == ".fini_array")
164 return ELF::SHT_FINI_ARRAY;
166 if (Name == ".preinit_array")
167 return ELF::SHT_PREINIT_ARRAY;
169 if (K.isBSS() || K.isThreadBSS())
170 return ELF::SHT_NOBITS;
172 return ELF::SHT_PROGBITS;
175 static unsigned getELFSectionFlags(SectionKind K) {
179 Flags |= ELF::SHF_ALLOC;
182 Flags |= ELF::SHF_EXECINSTR;
184 if (K.isExecuteOnly())
185 Flags |= ELF::SHF_ARM_PURECODE;
188 Flags |= ELF::SHF_WRITE;
190 if (K.isThreadLocal())
191 Flags |= ELF::SHF_TLS;
193 if (K.isMergeableCString() || K.isMergeableConst())
194 Flags |= ELF::SHF_MERGE;
196 if (K.isMergeableCString())
197 Flags |= ELF::SHF_STRINGS;
202 static const Comdat *getELFComdat(const GlobalValue *GV) {
203 const Comdat *C = GV->getComdat();
207 if (C->getSelectionKind() != Comdat::Any)
208 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
209 C->getName() + "' cannot be lowered.");
214 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
215 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
216 StringRef SectionName = GO->getSection();
218 // Infer section flags from the section name if we can.
219 Kind = getELFKindForNamedSection(SectionName, Kind);
221 StringRef Group = "";
222 unsigned Flags = getELFSectionFlags(Kind);
223 if (const Comdat *C = getELFComdat(GO)) {
224 Group = C->getName();
225 Flags |= ELF::SHF_GROUP;
227 return getContext().getELFSection(SectionName,
228 getELFSectionType(SectionName, Kind), Flags,
229 /*EntrySize=*/0, Group);
232 /// Return the section prefix name used by options FunctionsSections and
234 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
237 if (Kind.isReadOnly())
241 if (Kind.isThreadData())
243 if (Kind.isThreadBSS())
247 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
248 return ".data.rel.ro";
251 static MCSectionELF *
252 selectELFSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
253 SectionKind Kind, Mangler &Mang,
254 const TargetMachine &TM, bool EmitUniqueSection,
255 unsigned Flags, unsigned *NextUniqueID) {
256 unsigned EntrySize = 0;
257 if (Kind.isMergeableCString()) {
258 if (Kind.isMergeable2ByteCString()) {
260 } else if (Kind.isMergeable4ByteCString()) {
264 assert(Kind.isMergeable1ByteCString() && "unknown string width");
266 } else if (Kind.isMergeableConst()) {
267 if (Kind.isMergeableConst4()) {
269 } else if (Kind.isMergeableConst8()) {
271 } else if (Kind.isMergeableConst16()) {
274 assert(Kind.isMergeableConst32() && "unknown data width");
279 StringRef Group = "";
280 if (const Comdat *C = getELFComdat(GO)) {
281 Flags |= ELF::SHF_GROUP;
282 Group = C->getName();
285 bool UniqueSectionNames = TM.getUniqueSectionNames();
286 SmallString<128> Name;
287 if (Kind.isMergeableCString()) {
288 // We also need alignment here.
289 // FIXME: this is getting the alignment of the character, not the
290 // alignment of the global!
291 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
292 cast<GlobalVariable>(GO));
294 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
295 Name = SizeSpec + utostr(Align);
296 } else if (Kind.isMergeableConst()) {
297 Name = ".rodata.cst";
298 Name += utostr(EntrySize);
300 Name = getSectionPrefixForGlobal(Kind);
303 if (const auto *F = dyn_cast<Function>(GO)) {
304 const auto &OptionalPrefix = F->getSectionPrefix();
306 Name += *OptionalPrefix;
309 if (EmitUniqueSection && UniqueSectionNames) {
311 TM.getNameWithPrefix(Name, GO, Mang, true);
313 unsigned UniqueID = MCContext::GenericSectionID;
314 if (EmitUniqueSection && !UniqueSectionNames) {
315 UniqueID = *NextUniqueID;
318 // Use 0 as the unique ID for execute-only text
319 if (Kind.isExecuteOnly())
321 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
322 EntrySize, Group, UniqueID);
325 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
326 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
327 unsigned Flags = getELFSectionFlags(Kind);
329 // If we have -ffunction-section or -fdata-section then we should emit the
330 // global value to a uniqued section specifically for it.
331 bool EmitUniqueSection = false;
332 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
334 EmitUniqueSection = TM.getFunctionSections();
336 EmitUniqueSection = TM.getDataSections();
338 EmitUniqueSection |= GO->hasComdat();
340 return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
341 EmitUniqueSection, Flags, &NextUniqueID);
344 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
345 const Function &F, const TargetMachine &TM) const {
346 // If the function can be removed, produce a unique section so that
347 // the table doesn't prevent the removal.
348 const Comdat *C = F.getComdat();
349 bool EmitUniqueSection = TM.getFunctionSections() || C;
350 if (!EmitUniqueSection)
351 return ReadOnlySection;
353 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
354 getMangler(), TM, EmitUniqueSection, ELF::SHF_ALLOC,
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 /// Given a mergeable constant with the specified size and relocation
366 /// information, return a section that it should be placed in.
367 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
368 const DataLayout &DL, SectionKind Kind, const Constant *C,
369 unsigned &Align) const {
370 if (Kind.isMergeableConst4() && MergeableConst4Section)
371 return MergeableConst4Section;
372 if (Kind.isMergeableConst8() && MergeableConst8Section)
373 return MergeableConst8Section;
374 if (Kind.isMergeableConst16() && MergeableConst16Section)
375 return MergeableConst16Section;
376 if (Kind.isMergeableConst32() && MergeableConst32Section)
377 return MergeableConst32Section;
378 if (Kind.isReadOnly())
379 return ReadOnlySection;
381 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
382 return DataRelROSection;
385 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
386 bool IsCtor, unsigned Priority,
387 const MCSymbol *KeySym) {
390 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
391 StringRef COMDAT = KeySym ? KeySym->getName() : "";
394 Flags |= ELF::SHF_GROUP;
398 Type = ELF::SHT_INIT_ARRAY;
399 Name = ".init_array";
401 Type = ELF::SHT_FINI_ARRAY;
402 Name = ".fini_array";
404 if (Priority != 65535) {
406 Name += utostr(Priority);
409 // The default scheme is .ctor / .dtor, so we have to invert the priority
415 if (Priority != 65535) {
417 Name += utostr(65535 - Priority);
419 Type = ELF::SHT_PROGBITS;
422 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
425 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
426 unsigned Priority, const MCSymbol *KeySym) const {
427 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
431 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
432 unsigned Priority, const MCSymbol *KeySym) const {
433 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
437 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
438 const GlobalValue *LHS, const GlobalValue *RHS,
439 const TargetMachine &TM) const {
440 // We may only use a PLT-relative relocation to refer to unnamed_addr
442 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
445 // Basic sanity checks.
446 if (LHS->getType()->getPointerAddressSpace() != 0 ||
447 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
448 RHS->isThreadLocal())
451 return MCBinaryExpr::createSub(
452 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
454 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
458 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
459 UseInitArray = UseInitArray_;
460 MCContext &Ctx = getContext();
462 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
463 ELF::SHF_ALLOC | ELF::SHF_WRITE);
465 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
466 ELF::SHF_ALLOC | ELF::SHF_WRITE);
470 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
471 ELF::SHF_WRITE | ELF::SHF_ALLOC);
472 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
473 ELF::SHF_WRITE | ELF::SHF_ALLOC);
476 //===----------------------------------------------------------------------===//
478 //===----------------------------------------------------------------------===//
480 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
481 : TargetLoweringObjectFile() {
482 SupportIndirectSymViaGOTPCRel = true;
485 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
486 const TargetMachine &TM) {
487 TargetLoweringObjectFile::Initialize(Ctx, TM);
488 if (TM.getRelocationModel() == Reloc::Static) {
489 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
490 SectionKind::getData());
491 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
492 SectionKind::getData());
494 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
495 MachO::S_MOD_INIT_FUNC_POINTERS,
496 SectionKind::getData());
497 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
498 MachO::S_MOD_TERM_FUNC_POINTERS,
499 SectionKind::getData());
503 /// emitModuleFlags - Perform code emission for module flags.
504 void TargetLoweringObjectFileMachO::emitModuleFlags(
505 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
506 const TargetMachine &TM) const {
507 unsigned VersionVal = 0;
508 unsigned ImageInfoFlags = 0;
509 MDNode *LinkerOptions = nullptr;
510 StringRef SectionVal;
512 for (const auto &MFE : ModuleFlags) {
513 // Ignore flags with 'Require' behavior.
514 if (MFE.Behavior == Module::Require)
517 StringRef Key = MFE.Key->getString();
518 Metadata *Val = MFE.Val;
520 if (Key == "Objective-C Image Info Version") {
521 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
522 } else if (Key == "Objective-C Garbage Collection" ||
523 Key == "Objective-C GC Only" ||
524 Key == "Objective-C Is Simulated" ||
525 Key == "Objective-C Class Properties" ||
526 Key == "Objective-C Image Swift Version") {
527 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
528 } else if (Key == "Objective-C Image Info Section") {
529 SectionVal = cast<MDString>(Val)->getString();
530 } else if (Key == "Linker Options") {
531 LinkerOptions = cast<MDNode>(Val);
535 // Emit the linker options if present.
537 for (const auto &Option : LinkerOptions->operands()) {
538 SmallVector<std::string, 4> StrOptions;
539 for (const auto &Piece : cast<MDNode>(Option)->operands())
540 StrOptions.push_back(cast<MDString>(Piece)->getString());
541 Streamer.EmitLinkerOptions(StrOptions);
545 // The section is mandatory. If we don't have it, then we don't have GC info.
546 if (SectionVal.empty()) return;
548 StringRef Segment, Section;
549 unsigned TAA = 0, StubSize = 0;
551 std::string ErrorCode =
552 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
553 TAA, TAAParsed, StubSize);
554 if (!ErrorCode.empty())
555 // If invalid, report the error with report_fatal_error.
556 report_fatal_error("Invalid section specifier '" + Section + "': " +
560 MCSectionMachO *S = getContext().getMachOSection(
561 Segment, Section, TAA, StubSize, SectionKind::getData());
562 Streamer.SwitchSection(S);
563 Streamer.EmitLabel(getContext().
564 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
565 Streamer.EmitIntValue(VersionVal, 4);
566 Streamer.EmitIntValue(ImageInfoFlags, 4);
567 Streamer.AddBlankLine();
570 static void checkMachOComdat(const GlobalValue *GV) {
571 const Comdat *C = GV->getComdat();
575 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
576 "' cannot be lowered.");
579 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
580 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
581 // Parse the section specifier and create it if valid.
582 StringRef Segment, Section;
583 unsigned TAA = 0, StubSize = 0;
586 checkMachOComdat(GO);
588 std::string ErrorCode =
589 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
590 TAA, TAAParsed, StubSize);
591 if (!ErrorCode.empty()) {
592 // If invalid, report the error with report_fatal_error.
593 report_fatal_error("Global variable '" + GO->getName() +
594 "' has an invalid section specifier '" +
595 GO->getSection() + "': " + ErrorCode + ".");
600 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
602 // If TAA wasn't set by ParseSectionSpecifier() above,
603 // use the value returned by getMachOSection() as a default.
605 TAA = S->getTypeAndAttributes();
607 // Okay, now that we got the section, verify that the TAA & StubSize agree.
608 // If the user declared multiple globals with different section flags, we need
609 // to reject it here.
610 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
611 // If invalid, report the error with report_fatal_error.
612 report_fatal_error("Global variable '" + GO->getName() +
613 "' section type or attributes does not match previous"
614 " section specifier");
620 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
621 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
622 checkMachOComdat(GO);
624 // Handle thread local data.
625 if (Kind.isThreadBSS()) return TLSBSSSection;
626 if (Kind.isThreadData()) return TLSDataSection;
629 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
631 // If this is weak/linkonce, put this in a coalescable section, either in text
632 // or data depending on if it is writable.
633 if (GO->isWeakForLinker()) {
634 if (Kind.isReadOnly())
635 return ConstTextCoalSection;
636 return DataCoalSection;
639 // FIXME: Alignment check should be handled by section classifier.
640 if (Kind.isMergeable1ByteCString() &&
641 GO->getParent()->getDataLayout().getPreferredAlignment(
642 cast<GlobalVariable>(GO)) < 32)
643 return CStringSection;
645 // Do not put 16-bit arrays in the UString section if they have an
646 // externally visible label, this runs into issues with certain linker
648 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
649 GO->getParent()->getDataLayout().getPreferredAlignment(
650 cast<GlobalVariable>(GO)) < 32)
651 return UStringSection;
653 // With MachO only variables whose corresponding symbol starts with 'l' or
654 // 'L' can be merged, so we only try merging GVs with private linkage.
655 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
656 if (Kind.isMergeableConst4())
657 return FourByteConstantSection;
658 if (Kind.isMergeableConst8())
659 return EightByteConstantSection;
660 if (Kind.isMergeableConst16())
661 return SixteenByteConstantSection;
664 // Otherwise, if it is readonly, but not something we can specially optimize,
665 // just drop it in .const.
666 if (Kind.isReadOnly())
667 return ReadOnlySection;
669 // If this is marked const, put it into a const section. But if the dynamic
670 // linker needs to write to it, put it in the data segment.
671 if (Kind.isReadOnlyWithRel())
672 return ConstDataSection;
674 // Put zero initialized globals with strong external linkage in the
675 // DATA, __common section with the .zerofill directive.
676 if (Kind.isBSSExtern())
677 return DataCommonSection;
679 // Put zero initialized globals with local linkage in __DATA,__bss directive
680 // with the .zerofill directive (aka .lcomm).
681 if (Kind.isBSSLocal())
682 return DataBSSSection;
684 // Otherwise, just drop the variable in the normal data section.
688 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
689 const DataLayout &DL, SectionKind Kind, const Constant *C,
690 unsigned &Align) const {
691 // If this constant requires a relocation, we have to put it in the data
692 // segment, not in the text segment.
693 if (Kind.isData() || Kind.isReadOnlyWithRel())
694 return ConstDataSection;
696 if (Kind.isMergeableConst4())
697 return FourByteConstantSection;
698 if (Kind.isMergeableConst8())
699 return EightByteConstantSection;
700 if (Kind.isMergeableConst16())
701 return SixteenByteConstantSection;
702 return ReadOnlySection; // .const
705 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
706 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
707 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
708 // The mach-o version of this method defaults to returning a stub reference.
710 if (Encoding & DW_EH_PE_indirect) {
711 MachineModuleInfoMachO &MachOMMI =
712 MMI->getObjFileInfo<MachineModuleInfoMachO>();
714 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
716 // Add information about the stub reference to MachOMMI so that the stub
717 // gets emitted by the asmprinter.
718 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
719 if (!StubSym.getPointer()) {
720 MCSymbol *Sym = TM.getSymbol(GV);
721 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
724 return TargetLoweringObjectFile::
725 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
726 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
729 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
733 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
734 const GlobalValue *GV, const TargetMachine &TM,
735 MachineModuleInfo *MMI) const {
736 // The mach-o version of this method defaults to returning a stub reference.
737 MachineModuleInfoMachO &MachOMMI =
738 MMI->getObjFileInfo<MachineModuleInfoMachO>();
740 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
742 // Add information about the stub reference to MachOMMI so that the stub
743 // gets emitted by the asmprinter.
744 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
745 if (!StubSym.getPointer()) {
746 MCSymbol *Sym = TM.getSymbol(GV);
747 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
753 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
754 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
755 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
756 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
757 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
758 // through a non_lazy_ptr stub instead. One advantage is that it allows the
759 // computation of deltas to final external symbols. Example:
765 // .long _extgotequiv-_delta
767 // is transformed to:
770 // .long L_extfoo$non_lazy_ptr-(_delta+0)
772 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
773 // L_extfoo$non_lazy_ptr:
774 // .indirect_symbol _extfoo
777 MachineModuleInfoMachO &MachOMMI =
778 MMI->getObjFileInfo<MachineModuleInfoMachO>();
779 MCContext &Ctx = getContext();
781 // The offset must consider the original displacement from the base symbol
782 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
783 Offset = -MV.getConstant();
784 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
786 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
787 // non_lazy_ptr stubs.
788 SmallString<128> Name;
789 StringRef Suffix = "$non_lazy_ptr";
790 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
791 Name += Sym->getName();
793 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
795 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
796 if (!StubSym.getPointer())
797 StubSym = MachineModuleInfoImpl::
798 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
800 const MCExpr *BSymExpr =
801 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
803 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
806 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
809 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
810 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
813 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
814 const MCSection &Section) {
815 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
818 // If it is not dead stripped, it is safe to use private labels.
819 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
820 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
826 void TargetLoweringObjectFileMachO::getNameWithPrefix(
827 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
828 const TargetMachine &TM) const {
829 bool CannotUsePrivateLabel = true;
830 if (auto *GO = GV->getBaseObject()) {
831 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
832 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
833 CannotUsePrivateLabel =
834 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
836 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
839 //===----------------------------------------------------------------------===//
841 //===----------------------------------------------------------------------===//
844 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
846 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
850 COFF::IMAGE_SCN_MEM_DISCARDABLE;
853 COFF::IMAGE_SCN_MEM_EXECUTE |
854 COFF::IMAGE_SCN_MEM_READ |
855 COFF::IMAGE_SCN_CNT_CODE |
856 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
859 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
860 COFF::IMAGE_SCN_MEM_READ |
861 COFF::IMAGE_SCN_MEM_WRITE;
862 else if (K.isThreadLocal())
864 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
865 COFF::IMAGE_SCN_MEM_READ |
866 COFF::IMAGE_SCN_MEM_WRITE;
867 else if (K.isReadOnly() || K.isReadOnlyWithRel())
869 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
870 COFF::IMAGE_SCN_MEM_READ;
871 else if (K.isWriteable())
873 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
874 COFF::IMAGE_SCN_MEM_READ |
875 COFF::IMAGE_SCN_MEM_WRITE;
880 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
881 const Comdat *C = GV->getComdat();
882 assert(C && "expected GV to have a Comdat!");
884 StringRef ComdatGVName = C->getName();
885 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
887 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
888 "' does not exist.");
890 if (ComdatGV->getComdat() != C)
891 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
892 "' is not a key for its COMDAT.");
897 static int getSelectionForCOFF(const GlobalValue *GV) {
898 if (const Comdat *C = GV->getComdat()) {
899 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
900 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
901 ComdatKey = GA->getBaseObject();
902 if (ComdatKey == GV) {
903 switch (C->getSelectionKind()) {
905 return COFF::IMAGE_COMDAT_SELECT_ANY;
906 case Comdat::ExactMatch:
907 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
908 case Comdat::Largest:
909 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
910 case Comdat::NoDuplicates:
911 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
912 case Comdat::SameSize:
913 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
916 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
922 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
923 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
925 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
926 StringRef Name = GO->getSection();
927 StringRef COMDATSymName = "";
928 if (GO->hasComdat()) {
929 Selection = getSelectionForCOFF(GO);
930 const GlobalValue *ComdatGV;
931 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
932 ComdatGV = getComdatGVForCOFF(GO);
936 if (!ComdatGV->hasPrivateLinkage()) {
937 MCSymbol *Sym = TM.getSymbol(ComdatGV);
938 COMDATSymName = Sym->getName();
939 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
945 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
949 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
954 if (Kind.isThreadLocal())
956 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
961 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
962 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
963 // If we have -ffunction-sections then we should emit the global value to a
964 // uniqued section specifically for it.
965 bool EmitUniquedSection;
967 EmitUniquedSection = TM.getFunctionSections();
969 EmitUniquedSection = TM.getDataSections();
971 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
972 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
973 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
975 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
976 int Selection = getSelectionForCOFF(GO);
978 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
979 const GlobalValue *ComdatGV;
981 ComdatGV = getComdatGVForCOFF(GO);
985 unsigned UniqueID = MCContext::GenericSectionID;
986 if (EmitUniquedSection)
987 UniqueID = NextUniqueID++;
989 if (!ComdatGV->hasPrivateLinkage()) {
990 MCSymbol *Sym = TM.getSymbol(ComdatGV);
991 StringRef COMDATSymName = Sym->getName();
992 return getContext().getCOFFSection(Name, Characteristics, Kind,
993 COMDATSymName, Selection, UniqueID);
995 SmallString<256> TmpData;
996 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
997 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
998 Selection, UniqueID);
1005 if (Kind.isThreadLocal())
1006 return TLSDataSection;
1008 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1009 return ReadOnlySection;
1011 // Note: we claim that common symbols are put in BSSSection, but they are
1012 // really emitted with the magic .comm directive, which creates a symbol table
1013 // entry but not a section.
1014 if (Kind.isBSS() || Kind.isCommon())
1020 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1021 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1022 const TargetMachine &TM) const {
1023 bool CannotUsePrivateLabel = false;
1024 if (GV->hasPrivateLinkage() &&
1025 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1026 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1027 CannotUsePrivateLabel = true;
1029 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1032 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1033 const Function &F, const TargetMachine &TM) const {
1034 // If the function can be removed, produce a unique section so that
1035 // the table doesn't prevent the removal.
1036 const Comdat *C = F.getComdat();
1037 bool EmitUniqueSection = TM.getFunctionSections() || C;
1038 if (!EmitUniqueSection)
1039 return ReadOnlySection;
1041 // FIXME: we should produce a symbol for F instead.
1042 if (F.hasPrivateLinkage())
1043 return ReadOnlySection;
1045 MCSymbol *Sym = TM.getSymbol(&F);
1046 StringRef COMDATSymName = Sym->getName();
1048 SectionKind Kind = SectionKind::getReadOnly();
1049 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1050 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1051 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1052 unsigned UniqueID = NextUniqueID++;
1054 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1055 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1058 void TargetLoweringObjectFileCOFF::emitModuleFlags(
1059 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1060 const TargetMachine &TM) const {
1061 MDNode *LinkerOptions = nullptr;
1063 for (const auto &MFE : ModuleFlags) {
1064 StringRef Key = MFE.Key->getString();
1065 if (Key == "Linker Options")
1066 LinkerOptions = cast<MDNode>(MFE.Val);
1069 if (LinkerOptions) {
1070 // Emit the linker options to the linker .drectve section. According to the
1071 // spec, this section is a space-separated string containing flags for
1073 MCSection *Sec = getDrectveSection();
1074 Streamer.SwitchSection(Sec);
1075 for (const auto &Option : LinkerOptions->operands()) {
1076 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1077 // Lead with a space for consistency with our dllexport implementation.
1078 std::string Directive(" ");
1079 Directive.append(cast<MDString>(Piece)->getString());
1080 Streamer.EmitBytes(Directive);
1086 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1087 const TargetMachine &TM) {
1088 TargetLoweringObjectFile::Initialize(Ctx, TM);
1089 const Triple &T = TM.getTargetTriple();
1090 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1092 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1093 COFF::IMAGE_SCN_MEM_READ,
1094 SectionKind::getReadOnly());
1096 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1097 COFF::IMAGE_SCN_MEM_READ,
1098 SectionKind::getReadOnly());
1100 StaticCtorSection = Ctx.getCOFFSection(
1101 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1102 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1103 SectionKind::getData());
1104 StaticDtorSection = Ctx.getCOFFSection(
1105 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1106 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1107 SectionKind::getData());
1111 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1112 unsigned Priority, const MCSymbol *KeySym) const {
1113 return getContext().getAssociativeCOFFSection(
1114 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
1117 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1118 unsigned Priority, const MCSymbol *KeySym) const {
1119 return getContext().getAssociativeCOFFSection(
1120 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
1123 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1124 raw_ostream &OS, const GlobalValue *GV) const {
1125 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1128 const Triple &TT = getTargetTriple();
1130 if (TT.isKnownWindowsMSVCEnvironment())
1135 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1137 raw_string_ostream FlagOS(Flag);
1138 getMangler().getNameWithPrefix(FlagOS, GV, false);
1140 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1141 OS << Flag.substr(1);
1145 getMangler().getNameWithPrefix(OS, GV, false);
1148 if (!GV->getValueType()->isFunctionTy()) {
1149 if (TT.isKnownWindowsMSVCEnvironment())