xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision c77e0ff7854f27e5ec81ce2efa98f84dda2bb363)
1 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
45 using namespace llvm;
46 using namespace dwarf;
47 
48 //===----------------------------------------------------------------------===//
49 //                                  ELF
50 //===----------------------------------------------------------------------===//
51 
52 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
53     const GlobalValue *GV, Mangler &Mang, 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, Mang)->getName());
59   if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
60     return TM.getSymbol(GV, Mang);
61   report_fatal_error("We do not support this DWARF encoding yet!");
62 }
63 
64 void TargetLoweringObjectFileELF::emitPersonalityValue(
65     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
66   SmallString<64> NameData("DW.ref.");
67   NameData += Sym->getName();
68   MCSymbolELF *Label =
69       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
70   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
71   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
72   StringRef Prefix = ".data.";
73   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
74   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
75   MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
76                                               Flags, 0, Label->getName());
77   unsigned Size = DL.getPointerSize();
78   Streamer.SwitchSection(Sec);
79   Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
80   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
81   const MCExpr *E = MCConstantExpr::create(Size, getContext());
82   Streamer.emitELFSize(Label, E);
83   Streamer.EmitLabel(Label);
84 
85   Streamer.EmitSymbolValue(Sym, Size);
86 }
87 
88 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
89     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
90     const TargetMachine &TM, MachineModuleInfo *MMI,
91     MCStreamer &Streamer) const {
92 
93   if (Encoding & dwarf::DW_EH_PE_indirect) {
94     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
95 
96     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
97 
98     // Add information about the stub reference to ELFMMI so that the stub
99     // gets emitted by the asmprinter.
100     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
101     if (!StubSym.getPointer()) {
102       MCSymbol *Sym = TM.getSymbol(GV, Mang);
103       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
104     }
105 
106     return TargetLoweringObjectFile::
107       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
108                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
109   }
110 
111   return TargetLoweringObjectFile::
112     getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
113 }
114 
115 static SectionKind
116 getELFKindForNamedSection(StringRef Name, SectionKind K) {
117   // N.B.: The defaults used in here are no the same ones used in MC.
118   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
119   // both gas and MC will produce a section with no flags. Given
120   // section(".eh_frame") gcc will produce:
121   //
122   //   .section   .eh_frame,"a",@progbits
123 
124   if (Name == getInstrProfCoverageSectionName(false))
125     return SectionKind::getMetadata();
126 
127   if (Name.empty() || Name[0] != '.') return K;
128 
129   // Some lame default implementation based on some magic section names.
130   if (Name == ".bss" ||
131       Name.startswith(".bss.") ||
132       Name.startswith(".gnu.linkonce.b.") ||
133       Name.startswith(".llvm.linkonce.b.") ||
134       Name == ".sbss" ||
135       Name.startswith(".sbss.") ||
136       Name.startswith(".gnu.linkonce.sb.") ||
137       Name.startswith(".llvm.linkonce.sb."))
138     return SectionKind::getBSS();
139 
140   if (Name == ".tdata" ||
141       Name.startswith(".tdata.") ||
142       Name.startswith(".gnu.linkonce.td.") ||
143       Name.startswith(".llvm.linkonce.td."))
144     return SectionKind::getThreadData();
145 
146   if (Name == ".tbss" ||
147       Name.startswith(".tbss.") ||
148       Name.startswith(".gnu.linkonce.tb.") ||
149       Name.startswith(".llvm.linkonce.tb."))
150     return SectionKind::getThreadBSS();
151 
152   return K;
153 }
154 
155 
156 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
157 
158   if (Name == getInstrProfCoverageSectionName(false))
159     return ELF::SHT_NOTE;
160 
161   if (Name == ".init_array")
162     return ELF::SHT_INIT_ARRAY;
163 
164   if (Name == ".fini_array")
165     return ELF::SHT_FINI_ARRAY;
166 
167   if (Name == ".preinit_array")
168     return ELF::SHT_PREINIT_ARRAY;
169 
170   if (K.isBSS() || K.isThreadBSS())
171     return ELF::SHT_NOBITS;
172 
173   return ELF::SHT_PROGBITS;
174 }
175 
176 static unsigned getELFSectionFlags(SectionKind K) {
177   unsigned Flags = 0;
178 
179   if (!K.isMetadata())
180     Flags |= ELF::SHF_ALLOC;
181 
182   if (K.isText())
183     Flags |= ELF::SHF_EXECINSTR;
184 
185   if (K.isWriteable())
186     Flags |= ELF::SHF_WRITE;
187 
188   if (K.isThreadLocal())
189     Flags |= ELF::SHF_TLS;
190 
191   if (K.isMergeableCString() || K.isMergeableConst())
192     Flags |= ELF::SHF_MERGE;
193 
194   if (K.isMergeableCString())
195     Flags |= ELF::SHF_STRINGS;
196 
197   return Flags;
198 }
199 
200 static const Comdat *getELFComdat(const GlobalValue *GV) {
201   const Comdat *C = GV->getComdat();
202   if (!C)
203     return nullptr;
204 
205   if (C->getSelectionKind() != Comdat::Any)
206     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
207                        C->getName() + "' cannot be lowered.");
208 
209   return C;
210 }
211 
212 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
213     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
214     const TargetMachine &TM) const {
215   StringRef SectionName = GV->getSection();
216 
217   // Infer section flags from the section name if we can.
218   Kind = getELFKindForNamedSection(SectionName, Kind);
219 
220   StringRef Group = "";
221   unsigned Flags = getELFSectionFlags(Kind);
222   if (const Comdat *C = getELFComdat(GV)) {
223     Group = C->getName();
224     Flags |= ELF::SHF_GROUP;
225   }
226   return getContext().getELFSection(SectionName,
227                                     getELFSectionType(SectionName, Kind), Flags,
228                                     /*EntrySize=*/0, Group);
229 }
230 
231 /// Return the section prefix name used by options FunctionsSections and
232 /// DataSections.
233 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
234   if (Kind.isText())
235     return ".text";
236   if (Kind.isReadOnly())
237     return ".rodata";
238   if (Kind.isBSS())
239     return ".bss";
240   if (Kind.isThreadData())
241     return ".tdata";
242   if (Kind.isThreadBSS())
243     return ".tbss";
244   if (Kind.isData())
245     return ".data";
246   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
247   return ".data.rel.ro";
248 }
249 
250 static MCSectionELF *
251 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
252                           SectionKind Kind, Mangler &Mang,
253                           const TargetMachine &TM, bool EmitUniqueSection,
254                           unsigned Flags, unsigned *NextUniqueID) {
255   unsigned EntrySize = 0;
256   if (Kind.isMergeableCString()) {
257     if (Kind.isMergeable2ByteCString()) {
258       EntrySize = 2;
259     } else if (Kind.isMergeable4ByteCString()) {
260       EntrySize = 4;
261     } else {
262       EntrySize = 1;
263       assert(Kind.isMergeable1ByteCString() && "unknown string width");
264     }
265   } else if (Kind.isMergeableConst()) {
266     if (Kind.isMergeableConst4()) {
267       EntrySize = 4;
268     } else if (Kind.isMergeableConst8()) {
269       EntrySize = 8;
270     } else {
271       assert(Kind.isMergeableConst16() && "unknown data width");
272       EntrySize = 16;
273     }
274   }
275 
276   StringRef Group = "";
277   if (const Comdat *C = getELFComdat(GV)) {
278     Flags |= ELF::SHF_GROUP;
279     Group = C->getName();
280   }
281 
282   bool UniqueSectionNames = TM.getUniqueSectionNames();
283   SmallString<128> Name;
284   if (Kind.isMergeableCString()) {
285     // We also need alignment here.
286     // FIXME: this is getting the alignment of the character, not the
287     // alignment of the global!
288     unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
289         cast<GlobalVariable>(GV));
290 
291     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
292     Name = SizeSpec + utostr(Align);
293   } else if (Kind.isMergeableConst()) {
294     Name = ".rodata.cst";
295     Name += utostr(EntrySize);
296   } else {
297     Name = getSectionPrefixForGlobal(Kind);
298   }
299 
300   if (EmitUniqueSection && UniqueSectionNames) {
301     Name.push_back('.');
302     TM.getNameWithPrefix(Name, GV, Mang, true);
303   }
304   unsigned UniqueID = ~0;
305   if (EmitUniqueSection && !UniqueSectionNames) {
306     UniqueID = *NextUniqueID;
307     (*NextUniqueID)++;
308   }
309   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
310                            EntrySize, Group, UniqueID);
311 }
312 
313 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
314     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
315     const TargetMachine &TM) const {
316   unsigned Flags = getELFSectionFlags(Kind);
317 
318   // If we have -ffunction-section or -fdata-section then we should emit the
319   // global value to a uniqued section specifically for it.
320   bool EmitUniqueSection = false;
321   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
322     if (Kind.isText())
323       EmitUniqueSection = TM.getFunctionSections();
324     else
325       EmitUniqueSection = TM.getDataSections();
326   }
327   EmitUniqueSection |= GV->hasComdat();
328 
329   return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
330                                    EmitUniqueSection, Flags, &NextUniqueID);
331 }
332 
333 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
334     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
335   // If the function can be removed, produce a unique section so that
336   // the table doesn't prevent the removal.
337   const Comdat *C = F.getComdat();
338   bool EmitUniqueSection = TM.getFunctionSections() || C;
339   if (!EmitUniqueSection)
340     return ReadOnlySection;
341 
342   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
343                                    Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
344                                    &NextUniqueID);
345 }
346 
347 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
348     bool UsesLabelDifference, const Function &F) const {
349   // We can always create relative relocations, so use another section
350   // that can be marked non-executable.
351   return false;
352 }
353 
354 /// Given a mergeable constant with the specified size and relocation
355 /// information, return a section that it should be placed in.
356 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
357     const DataLayout &DL, SectionKind Kind, const Constant *C) const {
358   if (Kind.isMergeableConst4() && MergeableConst4Section)
359     return MergeableConst4Section;
360   if (Kind.isMergeableConst8() && MergeableConst8Section)
361     return MergeableConst8Section;
362   if (Kind.isMergeableConst16() && MergeableConst16Section)
363     return MergeableConst16Section;
364   if (Kind.isReadOnly())
365     return ReadOnlySection;
366 
367   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
368   return DataRelROSection;
369 }
370 
371 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
372                                               bool IsCtor, unsigned Priority,
373                                               const MCSymbol *KeySym) {
374   std::string Name;
375   unsigned Type;
376   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
377   StringRef COMDAT = KeySym ? KeySym->getName() : "";
378 
379   if (KeySym)
380     Flags |= ELF::SHF_GROUP;
381 
382   if (UseInitArray) {
383     if (IsCtor) {
384       Type = ELF::SHT_INIT_ARRAY;
385       Name = ".init_array";
386     } else {
387       Type = ELF::SHT_FINI_ARRAY;
388       Name = ".fini_array";
389     }
390     if (Priority != 65535) {
391       Name += '.';
392       Name += utostr(Priority);
393     }
394   } else {
395     // The default scheme is .ctor / .dtor, so we have to invert the priority
396     // numbering.
397     if (IsCtor)
398       Name = ".ctors";
399     else
400       Name = ".dtors";
401     if (Priority != 65535) {
402       Name += '.';
403       Name += utostr(65535 - Priority);
404     }
405     Type = ELF::SHT_PROGBITS;
406   }
407 
408   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
409 }
410 
411 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
412     unsigned Priority, const MCSymbol *KeySym) const {
413   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
414                                   KeySym);
415 }
416 
417 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
418     unsigned Priority, const MCSymbol *KeySym) const {
419   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
420                                   KeySym);
421 }
422 
423 void
424 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
425   UseInitArray = UseInitArray_;
426   if (!UseInitArray)
427     return;
428 
429   StaticCtorSection = getContext().getELFSection(
430       ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
431   StaticDtorSection = getContext().getELFSection(
432       ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
433 }
434 
435 //===----------------------------------------------------------------------===//
436 //                                 MachO
437 //===----------------------------------------------------------------------===//
438 
439 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
440   : TargetLoweringObjectFile() {
441   SupportIndirectSymViaGOTPCRel = true;
442 }
443 
444 /// emitModuleFlags - Perform code emission for module flags.
445 void TargetLoweringObjectFileMachO::
446 emitModuleFlags(MCStreamer &Streamer,
447                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
448                 Mangler &Mang, const TargetMachine &TM) const {
449   unsigned VersionVal = 0;
450   unsigned ImageInfoFlags = 0;
451   MDNode *LinkerOptions = nullptr;
452   StringRef SectionVal;
453 
454   for (ArrayRef<Module::ModuleFlagEntry>::iterator
455          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
456     const Module::ModuleFlagEntry &MFE = *i;
457 
458     // Ignore flags with 'Require' behavior.
459     if (MFE.Behavior == Module::Require)
460       continue;
461 
462     StringRef Key = MFE.Key->getString();
463     Metadata *Val = MFE.Val;
464 
465     if (Key == "Objective-C Image Info Version") {
466       VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
467     } else if (Key == "Objective-C Garbage Collection" ||
468                Key == "Objective-C GC Only" ||
469                Key == "Objective-C Is Simulated" ||
470                Key == "Objective-C Class Properties" ||
471                Key == "Objective-C Image Swift Version") {
472       ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
473     } else if (Key == "Objective-C Image Info Section") {
474       SectionVal = cast<MDString>(Val)->getString();
475     } else if (Key == "Linker Options") {
476       LinkerOptions = cast<MDNode>(Val);
477     }
478   }
479 
480   // Emit the linker options if present.
481   if (LinkerOptions) {
482     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
483       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
484       SmallVector<std::string, 4> StrOptions;
485 
486       // Convert to strings.
487       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
488         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
489         StrOptions.push_back(MDOption->getString());
490       }
491 
492       Streamer.EmitLinkerOptions(StrOptions);
493     }
494   }
495 
496   // The section is mandatory. If we don't have it, then we don't have GC info.
497   if (SectionVal.empty()) return;
498 
499   StringRef Segment, Section;
500   unsigned TAA = 0, StubSize = 0;
501   bool TAAParsed;
502   std::string ErrorCode =
503     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
504                                           TAA, TAAParsed, StubSize);
505   if (!ErrorCode.empty())
506     // If invalid, report the error with report_fatal_error.
507     report_fatal_error("Invalid section specifier '" + Section + "': " +
508                        ErrorCode + ".");
509 
510   // Get the section.
511   MCSectionMachO *S = getContext().getMachOSection(
512       Segment, Section, TAA, StubSize, SectionKind::getData());
513   Streamer.SwitchSection(S);
514   Streamer.EmitLabel(getContext().
515                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
516   Streamer.EmitIntValue(VersionVal, 4);
517   Streamer.EmitIntValue(ImageInfoFlags, 4);
518   Streamer.AddBlankLine();
519 }
520 
521 static void checkMachOComdat(const GlobalValue *GV) {
522   const Comdat *C = GV->getComdat();
523   if (!C)
524     return;
525 
526   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
527                      "' cannot be lowered.");
528 }
529 
530 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
531     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
532     const TargetMachine &TM) const {
533   // Parse the section specifier and create it if valid.
534   StringRef Segment, Section;
535   unsigned TAA = 0, StubSize = 0;
536   bool TAAParsed;
537 
538   checkMachOComdat(GV);
539 
540   std::string ErrorCode =
541     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
542                                           TAA, TAAParsed, StubSize);
543   if (!ErrorCode.empty()) {
544     // If invalid, report the error with report_fatal_error.
545     report_fatal_error("Global variable '" + GV->getName() +
546                        "' has an invalid section specifier '" +
547                        GV->getSection() + "': " + ErrorCode + ".");
548   }
549 
550   // Get the section.
551   MCSectionMachO *S =
552       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
553 
554   // If TAA wasn't set by ParseSectionSpecifier() above,
555   // use the value returned by getMachOSection() as a default.
556   if (!TAAParsed)
557     TAA = S->getTypeAndAttributes();
558 
559   // Okay, now that we got the section, verify that the TAA & StubSize agree.
560   // If the user declared multiple globals with different section flags, we need
561   // to reject it here.
562   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
563     // If invalid, report the error with report_fatal_error.
564     report_fatal_error("Global variable '" + GV->getName() +
565                        "' section type or attributes does not match previous"
566                        " section specifier");
567   }
568 
569   return S;
570 }
571 
572 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
573     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
574     const TargetMachine &TM) const {
575   checkMachOComdat(GV);
576 
577   // Handle thread local data.
578   if (Kind.isThreadBSS()) return TLSBSSSection;
579   if (Kind.isThreadData()) return TLSDataSection;
580 
581   if (Kind.isText())
582     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
583 
584   // If this is weak/linkonce, put this in a coalescable section, either in text
585   // or data depending on if it is writable.
586   if (GV->isWeakForLinker()) {
587     if (Kind.isReadOnly())
588       return ConstTextCoalSection;
589     return DataCoalSection;
590   }
591 
592   // FIXME: Alignment check should be handled by section classifier.
593   if (Kind.isMergeable1ByteCString() &&
594       GV->getParent()->getDataLayout().getPreferredAlignment(
595           cast<GlobalVariable>(GV)) < 32)
596     return CStringSection;
597 
598   // Do not put 16-bit arrays in the UString section if they have an
599   // externally visible label, this runs into issues with certain linker
600   // versions.
601   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
602       GV->getParent()->getDataLayout().getPreferredAlignment(
603           cast<GlobalVariable>(GV)) < 32)
604     return UStringSection;
605 
606   // With MachO only variables whose corresponding symbol starts with 'l' or
607   // 'L' can be merged, so we only try merging GVs with private linkage.
608   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
609     if (Kind.isMergeableConst4())
610       return FourByteConstantSection;
611     if (Kind.isMergeableConst8())
612       return EightByteConstantSection;
613     if (Kind.isMergeableConst16())
614       return SixteenByteConstantSection;
615   }
616 
617   // Otherwise, if it is readonly, but not something we can specially optimize,
618   // just drop it in .const.
619   if (Kind.isReadOnly())
620     return ReadOnlySection;
621 
622   // If this is marked const, put it into a const section.  But if the dynamic
623   // linker needs to write to it, put it in the data segment.
624   if (Kind.isReadOnlyWithRel())
625     return ConstDataSection;
626 
627   // Put zero initialized globals with strong external linkage in the
628   // DATA, __common section with the .zerofill directive.
629   if (Kind.isBSSExtern())
630     return DataCommonSection;
631 
632   // Put zero initialized globals with local linkage in __DATA,__bss directive
633   // with the .zerofill directive (aka .lcomm).
634   if (Kind.isBSSLocal())
635     return DataBSSSection;
636 
637   // Otherwise, just drop the variable in the normal data section.
638   return DataSection;
639 }
640 
641 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
642     const DataLayout &DL, SectionKind Kind, const Constant *C) const {
643   // If this constant requires a relocation, we have to put it in the data
644   // segment, not in the text segment.
645   if (Kind.isData() || Kind.isReadOnlyWithRel())
646     return ConstDataSection;
647 
648   if (Kind.isMergeableConst4())
649     return FourByteConstantSection;
650   if (Kind.isMergeableConst8())
651     return EightByteConstantSection;
652   if (Kind.isMergeableConst16())
653     return SixteenByteConstantSection;
654   return ReadOnlySection;  // .const
655 }
656 
657 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
658     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
659     const TargetMachine &TM, MachineModuleInfo *MMI,
660     MCStreamer &Streamer) const {
661   // The mach-o version of this method defaults to returning a stub reference.
662 
663   if (Encoding & DW_EH_PE_indirect) {
664     MachineModuleInfoMachO &MachOMMI =
665       MMI->getObjFileInfo<MachineModuleInfoMachO>();
666 
667     MCSymbol *SSym =
668         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
669 
670     // Add information about the stub reference to MachOMMI so that the stub
671     // gets emitted by the asmprinter.
672     MachineModuleInfoImpl::StubValueTy &StubSym =
673       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
674                                   MachOMMI.getGVStubEntry(SSym);
675     if (!StubSym.getPointer()) {
676       MCSymbol *Sym = TM.getSymbol(GV, Mang);
677       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
678     }
679 
680     return TargetLoweringObjectFile::
681       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
682                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
683   }
684 
685   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
686                                                            TM, MMI, Streamer);
687 }
688 
689 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
690     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
691     MachineModuleInfo *MMI) const {
692   // The mach-o version of this method defaults to returning a stub reference.
693   MachineModuleInfoMachO &MachOMMI =
694     MMI->getObjFileInfo<MachineModuleInfoMachO>();
695 
696   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
697 
698   // Add information about the stub reference to MachOMMI so that the stub
699   // gets emitted by the asmprinter.
700   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
701   if (!StubSym.getPointer()) {
702     MCSymbol *Sym = TM.getSymbol(GV, Mang);
703     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
704   }
705 
706   return SSym;
707 }
708 
709 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
710     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
711     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
712   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
713   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
714   // through a non_lazy_ptr stub instead. One advantage is that it allows the
715   // computation of deltas to final external symbols. Example:
716   //
717   //    _extgotequiv:
718   //       .long   _extfoo
719   //
720   //    _delta:
721   //       .long   _extgotequiv-_delta
722   //
723   // is transformed to:
724   //
725   //    _delta:
726   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
727   //
728   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
729   //    L_extfoo$non_lazy_ptr:
730   //       .indirect_symbol        _extfoo
731   //       .long   0
732   //
733   MachineModuleInfoMachO &MachOMMI =
734     MMI->getObjFileInfo<MachineModuleInfoMachO>();
735   MCContext &Ctx = getContext();
736 
737   // The offset must consider the original displacement from the base symbol
738   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
739   Offset = -MV.getConstant();
740   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
741 
742   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
743   // non_lazy_ptr stubs.
744   SmallString<128> Name;
745   StringRef Suffix = "$non_lazy_ptr";
746   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
747   Name += Sym->getName();
748   Name += Suffix;
749   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
750 
751   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
752   if (!StubSym.getPointer())
753     StubSym = MachineModuleInfoImpl::
754       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
755 
756   const MCExpr *BSymExpr =
757     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
758   const MCExpr *LHS =
759     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
760 
761   if (!Offset)
762     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
763 
764   const MCExpr *RHS =
765     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
766   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
767 }
768 
769 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
770                                const MCSection &Section) {
771   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
772     return true;
773 
774   // If it is not dead stripped, it is safe to use private labels.
775   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
776   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
777     return true;
778 
779   return false;
780 }
781 
782 void TargetLoweringObjectFileMachO::getNameWithPrefix(
783     SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
784     const TargetMachine &TM) const {
785   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
786   const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
787   bool CannotUsePrivateLabel =
788       !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
789   Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
790 }
791 
792 //===----------------------------------------------------------------------===//
793 //                                  COFF
794 //===----------------------------------------------------------------------===//
795 
796 static unsigned
797 getCOFFSectionFlags(SectionKind K) {
798   unsigned Flags = 0;
799 
800   if (K.isMetadata())
801     Flags |=
802       COFF::IMAGE_SCN_MEM_DISCARDABLE;
803   else if (K.isText())
804     Flags |=
805       COFF::IMAGE_SCN_MEM_EXECUTE |
806       COFF::IMAGE_SCN_MEM_READ |
807       COFF::IMAGE_SCN_CNT_CODE;
808   else if (K.isBSS())
809     Flags |=
810       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
811       COFF::IMAGE_SCN_MEM_READ |
812       COFF::IMAGE_SCN_MEM_WRITE;
813   else if (K.isThreadLocal())
814     Flags |=
815       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
816       COFF::IMAGE_SCN_MEM_READ |
817       COFF::IMAGE_SCN_MEM_WRITE;
818   else if (K.isReadOnly() || K.isReadOnlyWithRel())
819     Flags |=
820       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
821       COFF::IMAGE_SCN_MEM_READ;
822   else if (K.isWriteable())
823     Flags |=
824       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
825       COFF::IMAGE_SCN_MEM_READ |
826       COFF::IMAGE_SCN_MEM_WRITE;
827 
828   return Flags;
829 }
830 
831 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
832   const Comdat *C = GV->getComdat();
833   assert(C && "expected GV to have a Comdat!");
834 
835   StringRef ComdatGVName = C->getName();
836   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
837   if (!ComdatGV)
838     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
839                        "' does not exist.");
840 
841   if (ComdatGV->getComdat() != C)
842     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
843                        "' is not a key for its COMDAT.");
844 
845   return ComdatGV;
846 }
847 
848 static int getSelectionForCOFF(const GlobalValue *GV) {
849   if (const Comdat *C = GV->getComdat()) {
850     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
851     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
852       ComdatKey = GA->getBaseObject();
853     if (ComdatKey == GV) {
854       switch (C->getSelectionKind()) {
855       case Comdat::Any:
856         return COFF::IMAGE_COMDAT_SELECT_ANY;
857       case Comdat::ExactMatch:
858         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
859       case Comdat::Largest:
860         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
861       case Comdat::NoDuplicates:
862         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
863       case Comdat::SameSize:
864         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
865       }
866     } else {
867       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
868     }
869   }
870   return 0;
871 }
872 
873 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
874     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
875     const TargetMachine &TM) const {
876   int Selection = 0;
877   unsigned Characteristics = getCOFFSectionFlags(Kind);
878   StringRef Name = GV->getSection();
879   StringRef COMDATSymName = "";
880   if (GV->hasComdat()) {
881     Selection = getSelectionForCOFF(GV);
882     const GlobalValue *ComdatGV;
883     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
884       ComdatGV = getComdatGVForCOFF(GV);
885     else
886       ComdatGV = GV;
887 
888     if (!ComdatGV->hasPrivateLinkage()) {
889       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
890       COMDATSymName = Sym->getName();
891       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
892     } else {
893       Selection = 0;
894     }
895   }
896   return getContext().getCOFFSection(Name,
897                                      Characteristics,
898                                      Kind,
899                                      COMDATSymName,
900                                      Selection);
901 }
902 
903 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
904   if (Kind.isText())
905     return ".text";
906   if (Kind.isBSS())
907     return ".bss";
908   if (Kind.isThreadLocal())
909     return ".tls$";
910   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
911     return ".rdata";
912   return ".data";
913 }
914 
915 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
916     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
917     const TargetMachine &TM) const {
918   // If we have -ffunction-sections then we should emit the global value to a
919   // uniqued section specifically for it.
920   bool EmitUniquedSection;
921   if (Kind.isText())
922     EmitUniquedSection = TM.getFunctionSections();
923   else
924     EmitUniquedSection = TM.getDataSections();
925 
926   if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
927     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
928     unsigned Characteristics = getCOFFSectionFlags(Kind);
929 
930     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
931     int Selection = getSelectionForCOFF(GV);
932     if (!Selection)
933       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
934     const GlobalValue *ComdatGV;
935     if (GV->hasComdat())
936       ComdatGV = getComdatGVForCOFF(GV);
937     else
938       ComdatGV = GV;
939 
940     if (!ComdatGV->hasPrivateLinkage()) {
941       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
942       StringRef COMDATSymName = Sym->getName();
943       return getContext().getCOFFSection(Name, Characteristics, Kind,
944                                          COMDATSymName, Selection);
945     } else {
946       SmallString<256> TmpData;
947       Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
948       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
949                                          Selection);
950     }
951   }
952 
953   if (Kind.isText())
954     return TextSection;
955 
956   if (Kind.isThreadLocal())
957     return TLSDataSection;
958 
959   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
960     return ReadOnlySection;
961 
962   // Note: we claim that common symbols are put in BSSSection, but they are
963   // really emitted with the magic .comm directive, which creates a symbol table
964   // entry but not a section.
965   if (Kind.isBSS() || Kind.isCommon())
966     return BSSSection;
967 
968   return DataSection;
969 }
970 
971 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
972     SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
973     const TargetMachine &TM) const {
974   bool CannotUsePrivateLabel = false;
975   if (GV->hasPrivateLinkage() &&
976       ((isa<Function>(GV) && TM.getFunctionSections()) ||
977        (isa<GlobalVariable>(GV) && TM.getDataSections())))
978     CannotUsePrivateLabel = true;
979 
980   Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
981 }
982 
983 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
984     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
985   // If the function can be removed, produce a unique section so that
986   // the table doesn't prevent the removal.
987   const Comdat *C = F.getComdat();
988   bool EmitUniqueSection = TM.getFunctionSections() || C;
989   if (!EmitUniqueSection)
990     return ReadOnlySection;
991 
992   // FIXME: we should produce a symbol for F instead.
993   if (F.hasPrivateLinkage())
994     return ReadOnlySection;
995 
996   MCSymbol *Sym = TM.getSymbol(&F, Mang);
997   StringRef COMDATSymName = Sym->getName();
998 
999   SectionKind Kind = SectionKind::getReadOnly();
1000   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1001   unsigned Characteristics = getCOFFSectionFlags(Kind);
1002   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1003 
1004   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1005                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
1006 }
1007 
1008 void TargetLoweringObjectFileCOFF::
1009 emitModuleFlags(MCStreamer &Streamer,
1010                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1011                 Mangler &Mang, const TargetMachine &TM) const {
1012   MDNode *LinkerOptions = nullptr;
1013 
1014   // Look for the "Linker Options" flag, since it's the only one we support.
1015   for (ArrayRef<Module::ModuleFlagEntry>::iterator
1016        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1017     const Module::ModuleFlagEntry &MFE = *i;
1018     StringRef Key = MFE.Key->getString();
1019     Metadata *Val = MFE.Val;
1020     if (Key == "Linker Options") {
1021       LinkerOptions = cast<MDNode>(Val);
1022       break;
1023     }
1024   }
1025   if (!LinkerOptions)
1026     return;
1027 
1028   // Emit the linker options to the linker .drectve section.  According to the
1029   // spec, this section is a space-separated string containing flags for linker.
1030   MCSection *Sec = getDrectveSection();
1031   Streamer.SwitchSection(Sec);
1032   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1033     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1034     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1035       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1036       // Lead with a space for consistency with our dllexport implementation.
1037       std::string Directive(" ");
1038       Directive.append(MDOption->getString());
1039       Streamer.EmitBytes(Directive);
1040     }
1041   }
1042 }
1043 
1044 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1045     unsigned Priority, const MCSymbol *KeySym) const {
1046   return getContext().getAssociativeCOFFSection(
1047       cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1048 }
1049 
1050 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1051     unsigned Priority, const MCSymbol *KeySym) const {
1052   return getContext().getAssociativeCOFFSection(
1053       cast<MCSectionCOFF>(StaticDtorSection), KeySym);
1054 }
1055 
1056 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1057     raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1058   if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1059     return;
1060 
1061   const Triple &TT = getTargetTriple();
1062 
1063   if (TT.isKnownWindowsMSVCEnvironment())
1064     OS << " /EXPORT:";
1065   else
1066     OS << " -export:";
1067 
1068   if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1069     std::string Flag;
1070     raw_string_ostream FlagOS(Flag);
1071     Mang.getNameWithPrefix(FlagOS, GV, false);
1072     FlagOS.flush();
1073     if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1074       OS << Flag.substr(1);
1075     else
1076       OS << Flag;
1077   } else {
1078     Mang.getNameWithPrefix(OS, GV, false);
1079   }
1080 
1081   if (!GV->getValueType()->isFunctionTy()) {
1082     if (TT.isKnownWindowsMSVCEnvironment())
1083       OS << ",DATA";
1084     else
1085       OS << ",data";
1086   }
1087 }
1088