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