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