xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision fce7f73bec461211ff5187f34d5f76facd22f753)
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/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/BinaryFormat/Dwarf.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/BinaryFormat/MachO.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
27 #include "llvm/IR/Comdat.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCContext.h"
42 #include "llvm/MC/MCExpr.h"
43 #include "llvm/MC/MCSectionCOFF.h"
44 #include "llvm/MC/MCSectionELF.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/MC/MCSectionWasm.h"
47 #include "llvm/MC/MCStreamer.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/MC/MCSymbolELF.h"
50 #include "llvm/MC/MCValue.h"
51 #include "llvm/MC/SectionKind.h"
52 #include "llvm/ProfileData/InstrProf.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetMachine.h"
59 #include <cassert>
60 #include <string>
61 
62 using namespace llvm;
63 using namespace dwarf;
64 
65 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
66                              StringRef &Section) {
67   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
68   M.getModuleFlagsMetadata(ModuleFlags);
69 
70   for (const auto &MFE: ModuleFlags) {
71     // Ignore flags with 'Require' behaviour.
72     if (MFE.Behavior == Module::Require)
73       continue;
74 
75     StringRef Key = MFE.Key->getString();
76     if (Key == "Objective-C Image Info Version") {
77       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
78     } else if (Key == "Objective-C Garbage Collection" ||
79                Key == "Objective-C GC Only" ||
80                Key == "Objective-C Is Simulated" ||
81                Key == "Objective-C Class Properties" ||
82                Key == "Objective-C Image Swift Version") {
83       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84     } else if (Key == "Objective-C Image Info Section") {
85       Section = cast<MDString>(MFE.Val)->getString();
86     }
87   }
88 }
89 
90 //===----------------------------------------------------------------------===//
91 //                                  ELF
92 //===----------------------------------------------------------------------===//
93 
94 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
95                                              const TargetMachine &TgtM) {
96   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
97   TM = &TgtM;
98 
99   bool Large = TgtM.getCodeModel() == CodeModel::Large;
100 
101   switch (TgtM.getTargetTriple().getArch()) {
102   case Triple::arm:
103   case Triple::armeb:
104   case Triple::thumb:
105   case Triple::thumbeb:
106     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
107       break;
108     // Fallthrough if not using EHABI
109     LLVM_FALLTHROUGH;
110   case Triple::ppc:
111   case Triple::x86:
112     PersonalityEncoding = isPositionIndependent()
113                               ? dwarf::DW_EH_PE_indirect |
114                                     dwarf::DW_EH_PE_pcrel |
115                                     dwarf::DW_EH_PE_sdata4
116                               : dwarf::DW_EH_PE_absptr;
117     LSDAEncoding = isPositionIndependent()
118                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
119                        : dwarf::DW_EH_PE_absptr;
120     TTypeEncoding = isPositionIndependent()
121                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
122                               dwarf::DW_EH_PE_sdata4
123                         : dwarf::DW_EH_PE_absptr;
124     break;
125   case Triple::x86_64:
126     if (isPositionIndependent()) {
127       PersonalityEncoding =
128           dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
129           (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
130       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
131                      (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
132       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
133                       (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
134     } else {
135       PersonalityEncoding =
136           Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
137       LSDAEncoding = Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
138       TTypeEncoding = Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
139     }
140     break;
141   case Triple::hexagon:
142     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
143     LSDAEncoding = dwarf::DW_EH_PE_absptr;
144     TTypeEncoding = dwarf::DW_EH_PE_absptr;
145     if (isPositionIndependent()) {
146       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
147       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
148       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
149     }
150     break;
151   case Triple::aarch64:
152   case Triple::aarch64_be:
153     // The small model guarantees static code/data size < 4GB, but not where it
154     // will be in memory. Most of these could end up >2GB away so even a signed
155     // pc-relative 32-bit address is insufficient, theoretically.
156     if (isPositionIndependent()) {
157       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
158         dwarf::DW_EH_PE_sdata8;
159       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
160       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
161         dwarf::DW_EH_PE_sdata8;
162     } else {
163       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
164       LSDAEncoding = dwarf::DW_EH_PE_absptr;
165       TTypeEncoding = dwarf::DW_EH_PE_absptr;
166     }
167     break;
168   case Triple::lanai:
169     LSDAEncoding = dwarf::DW_EH_PE_absptr;
170     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
171     TTypeEncoding = dwarf::DW_EH_PE_absptr;
172     break;
173   case Triple::mips:
174   case Triple::mipsel:
175   case Triple::mips64:
176   case Triple::mips64el:
177     // MIPS uses indirect pointer to refer personality functions and types, so
178     // that the eh_frame section can be read-only. DW.ref.personality will be
179     // generated for relocation.
180     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
181     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
182     //        identify N64 from just a triple.
183     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
184                     dwarf::DW_EH_PE_sdata4;
185     // We don't support PC-relative LSDA references in GAS so we use the default
186     // DW_EH_PE_absptr for those.
187 
188     // FreeBSD must be explicit about the data size and using pcrel since it's
189     // assembler/linker won't do the automatic conversion that the Linux tools
190     // do.
191     if (TgtM.getTargetTriple().isOSFreeBSD()) {
192       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
193       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
194     }
195     break;
196   case Triple::ppc64:
197   case Triple::ppc64le:
198     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
199       dwarf::DW_EH_PE_udata8;
200     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
201     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
202       dwarf::DW_EH_PE_udata8;
203     break;
204   case Triple::sparcel:
205   case Triple::sparc:
206     if (isPositionIndependent()) {
207       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
208       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
209         dwarf::DW_EH_PE_sdata4;
210       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
211         dwarf::DW_EH_PE_sdata4;
212     } else {
213       LSDAEncoding = dwarf::DW_EH_PE_absptr;
214       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
215       TTypeEncoding = dwarf::DW_EH_PE_absptr;
216     }
217     break;
218   case Triple::sparcv9:
219     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
220     if (isPositionIndependent()) {
221       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
222         dwarf::DW_EH_PE_sdata4;
223       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
224         dwarf::DW_EH_PE_sdata4;
225     } else {
226       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
227       TTypeEncoding = dwarf::DW_EH_PE_absptr;
228     }
229     break;
230   case Triple::systemz:
231     // All currently-defined code models guarantee that 4-byte PC-relative
232     // values will be in range.
233     if (isPositionIndependent()) {
234       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
235         dwarf::DW_EH_PE_sdata4;
236       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
237       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
238         dwarf::DW_EH_PE_sdata4;
239     } else {
240       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
241       LSDAEncoding = dwarf::DW_EH_PE_absptr;
242       TTypeEncoding = dwarf::DW_EH_PE_absptr;
243     }
244     break;
245   default:
246     break;
247   }
248 }
249 
250 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
251                                                      Module &M) const {
252   auto &C = getContext();
253 
254   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
255     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
256                               ELF::SHF_EXCLUDE);
257 
258     Streamer.SwitchSection(S);
259 
260     for (const auto &Operand : LinkerOptions->operands()) {
261       if (cast<MDNode>(Operand)->getNumOperands() != 2)
262         report_fatal_error("invalid llvm.linker.options");
263       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
264         Streamer.EmitBytes(cast<MDString>(Option)->getString());
265         Streamer.EmitIntValue(0, 1);
266       }
267     }
268   }
269 
270   unsigned Version = 0;
271   unsigned Flags = 0;
272   StringRef Section;
273 
274   GetObjCImageInfo(M, Version, Flags, Section);
275   if (!Section.empty()) {
276     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
277     Streamer.SwitchSection(S);
278     Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
279     Streamer.EmitIntValue(Version, 4);
280     Streamer.EmitIntValue(Flags, 4);
281     Streamer.AddBlankLine();
282   }
283 
284   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
285   M.getModuleFlagsMetadata(ModuleFlags);
286 
287   MDNode *CFGProfile = nullptr;
288 
289   for (const auto &MFE : ModuleFlags) {
290     StringRef Key = MFE.Key->getString();
291     if (Key == "CG Profile") {
292       CFGProfile = cast<MDNode>(MFE.Val);
293       break;
294     }
295   }
296 
297   if (!CFGProfile)
298     return;
299 
300   auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
301     if (!MDO)
302       return nullptr;
303     auto V = cast<ValueAsMetadata>(MDO);
304     const Function *F = cast<Function>(V->getValue());
305     return TM->getSymbol(F);
306   };
307 
308   for (const auto &Edge : CFGProfile->operands()) {
309     MDNode *E = cast<MDNode>(Edge);
310     const MCSymbol *From = GetSym(E->getOperand(0));
311     const MCSymbol *To = GetSym(E->getOperand(1));
312     // Skip null functions. This can happen if functions are dead stripped after
313     // the CGProfile pass has been run.
314     if (!From || !To)
315       continue;
316     uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
317                          ->getValue()
318                          ->getUniqueInteger()
319                          .getZExtValue();
320     Streamer.emitCGProfileEntry(
321         MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
322         MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
323   }
324 }
325 
326 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
327     const GlobalValue *GV, const TargetMachine &TM,
328     MachineModuleInfo *MMI) const {
329   unsigned Encoding = getPersonalityEncoding();
330   if ((Encoding & 0x80) == DW_EH_PE_indirect)
331     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
332                                           TM.getSymbol(GV)->getName());
333   if ((Encoding & 0x70) == DW_EH_PE_absptr)
334     return TM.getSymbol(GV);
335   report_fatal_error("We do not support this DWARF encoding yet!");
336 }
337 
338 void TargetLoweringObjectFileELF::emitPersonalityValue(
339     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
340   SmallString<64> NameData("DW.ref.");
341   NameData += Sym->getName();
342   MCSymbolELF *Label =
343       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
344   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
345   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
346   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
347   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
348                                                    ELF::SHT_PROGBITS, Flags, 0);
349   unsigned Size = DL.getPointerSize();
350   Streamer.SwitchSection(Sec);
351   Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
352   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
353   const MCExpr *E = MCConstantExpr::create(Size, getContext());
354   Streamer.emitELFSize(Label, E);
355   Streamer.EmitLabel(Label);
356 
357   Streamer.EmitSymbolValue(Sym, Size);
358 }
359 
360 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
361     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
362     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
363   if (Encoding & DW_EH_PE_indirect) {
364     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
365 
366     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
367 
368     // Add information about the stub reference to ELFMMI so that the stub
369     // gets emitted by the asmprinter.
370     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
371     if (!StubSym.getPointer()) {
372       MCSymbol *Sym = TM.getSymbol(GV);
373       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
374     }
375 
376     return TargetLoweringObjectFile::
377       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
378                         Encoding & ~DW_EH_PE_indirect, Streamer);
379   }
380 
381   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
382                                                            MMI, Streamer);
383 }
384 
385 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
386   // N.B.: The defaults used in here are not the same ones used in MC.
387   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
388   // both gas and MC will produce a section with no flags. Given
389   // section(".eh_frame") gcc will produce:
390   //
391   //   .section   .eh_frame,"a",@progbits
392 
393   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
394                                       /*AddSegmentInfo=*/false))
395     return SectionKind::getMetadata();
396 
397   if (Name.empty() || Name[0] != '.') return K;
398 
399   // Default implementation based on some magic section names.
400   if (Name == ".bss" ||
401       Name.startswith(".bss.") ||
402       Name.startswith(".gnu.linkonce.b.") ||
403       Name.startswith(".llvm.linkonce.b.") ||
404       Name == ".sbss" ||
405       Name.startswith(".sbss.") ||
406       Name.startswith(".gnu.linkonce.sb.") ||
407       Name.startswith(".llvm.linkonce.sb."))
408     return SectionKind::getBSS();
409 
410   if (Name == ".tdata" ||
411       Name.startswith(".tdata.") ||
412       Name.startswith(".gnu.linkonce.td.") ||
413       Name.startswith(".llvm.linkonce.td."))
414     return SectionKind::getThreadData();
415 
416   if (Name == ".tbss" ||
417       Name.startswith(".tbss.") ||
418       Name.startswith(".gnu.linkonce.tb.") ||
419       Name.startswith(".llvm.linkonce.tb."))
420     return SectionKind::getThreadBSS();
421 
422   return K;
423 }
424 
425 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
426   // Use SHT_NOTE for section whose name starts with ".note" to allow
427   // emitting ELF notes from C variable declaration.
428   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
429   if (Name.startswith(".note"))
430     return ELF::SHT_NOTE;
431 
432   if (Name == ".init_array")
433     return ELF::SHT_INIT_ARRAY;
434 
435   if (Name == ".fini_array")
436     return ELF::SHT_FINI_ARRAY;
437 
438   if (Name == ".preinit_array")
439     return ELF::SHT_PREINIT_ARRAY;
440 
441   if (K.isBSS() || K.isThreadBSS())
442     return ELF::SHT_NOBITS;
443 
444   return ELF::SHT_PROGBITS;
445 }
446 
447 static unsigned getELFSectionFlags(SectionKind K) {
448   unsigned Flags = 0;
449 
450   if (!K.isMetadata())
451     Flags |= ELF::SHF_ALLOC;
452 
453   if (K.isText())
454     Flags |= ELF::SHF_EXECINSTR;
455 
456   if (K.isExecuteOnly())
457     Flags |= ELF::SHF_ARM_PURECODE;
458 
459   if (K.isWriteable())
460     Flags |= ELF::SHF_WRITE;
461 
462   if (K.isThreadLocal())
463     Flags |= ELF::SHF_TLS;
464 
465   if (K.isMergeableCString() || K.isMergeableConst())
466     Flags |= ELF::SHF_MERGE;
467 
468   if (K.isMergeableCString())
469     Flags |= ELF::SHF_STRINGS;
470 
471   return Flags;
472 }
473 
474 static const Comdat *getELFComdat(const GlobalValue *GV) {
475   const Comdat *C = GV->getComdat();
476   if (!C)
477     return nullptr;
478 
479   if (C->getSelectionKind() != Comdat::Any)
480     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
481                        C->getName() + "' cannot be lowered.");
482 
483   return C;
484 }
485 
486 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
487                                               const TargetMachine &TM) {
488   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
489   if (!MD)
490     return nullptr;
491 
492   const MDOperand &Op = MD->getOperand(0);
493   if (!Op.get())
494     return nullptr;
495 
496   auto *VM = dyn_cast<ValueAsMetadata>(Op);
497   if (!VM)
498     report_fatal_error("MD_associated operand is not ValueAsMetadata");
499 
500   GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
501   return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
502 }
503 
504 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
505     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
506   StringRef SectionName = GO->getSection();
507 
508   // Check if '#pragma clang section' name is applicable.
509   // Note that pragma directive overrides -ffunction-section, -fdata-section
510   // and so section name is exactly as user specified and not uniqued.
511   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
512   if (GV && GV->hasImplicitSection()) {
513     auto Attrs = GV->getAttributes();
514     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
515       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
516     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
517       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
518     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
519       SectionName = Attrs.getAttribute("data-section").getValueAsString();
520     }
521   }
522   const Function *F = dyn_cast<Function>(GO);
523   if (F && F->hasFnAttribute("implicit-section-name")) {
524     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
525   }
526 
527   // Infer section flags from the section name if we can.
528   Kind = getELFKindForNamedSection(SectionName, Kind);
529 
530   StringRef Group = "";
531   unsigned Flags = getELFSectionFlags(Kind);
532   if (const Comdat *C = getELFComdat(GO)) {
533     Group = C->getName();
534     Flags |= ELF::SHF_GROUP;
535   }
536 
537   // A section can have at most one associated section. Put each global with
538   // MD_associated in a unique section.
539   unsigned UniqueID = MCContext::GenericSectionID;
540   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
541   if (AssociatedSymbol) {
542     UniqueID = NextUniqueID++;
543     Flags |= ELF::SHF_LINK_ORDER;
544   }
545 
546   MCSectionELF *Section = getContext().getELFSection(
547       SectionName, getELFSectionType(SectionName, Kind), Flags,
548       /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
549   // Make sure that we did not get some other section with incompatible sh_link.
550   // This should not be possible due to UniqueID code above.
551   assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
552          "Associated symbol mismatch between sections");
553   return Section;
554 }
555 
556 /// Return the section prefix name used by options FunctionsSections and
557 /// DataSections.
558 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
559   if (Kind.isText())
560     return ".text";
561   if (Kind.isReadOnly())
562     return ".rodata";
563   if (Kind.isBSS())
564     return ".bss";
565   if (Kind.isThreadData())
566     return ".tdata";
567   if (Kind.isThreadBSS())
568     return ".tbss";
569   if (Kind.isData())
570     return ".data";
571   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
572   return ".data.rel.ro";
573 }
574 
575 static unsigned getEntrySizeForKind(SectionKind Kind) {
576   if (Kind.isMergeable1ByteCString())
577     return 1;
578   else if (Kind.isMergeable2ByteCString())
579     return 2;
580   else if (Kind.isMergeable4ByteCString())
581     return 4;
582   else if (Kind.isMergeableConst4())
583     return 4;
584   else if (Kind.isMergeableConst8())
585     return 8;
586   else if (Kind.isMergeableConst16())
587     return 16;
588   else if (Kind.isMergeableConst32())
589     return 32;
590   else {
591     // We shouldn't have mergeable C strings or mergeable constants that we
592     // didn't handle above.
593     assert(!Kind.isMergeableCString() && "unknown string width");
594     assert(!Kind.isMergeableConst() && "unknown data width");
595     return 0;
596   }
597 }
598 
599 static MCSectionELF *selectELFSectionForGlobal(
600     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
601     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
602     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
603 
604   StringRef Group = "";
605   if (const Comdat *C = getELFComdat(GO)) {
606     Flags |= ELF::SHF_GROUP;
607     Group = C->getName();
608   }
609 
610   // Get the section entry size based on the kind.
611   unsigned EntrySize = getEntrySizeForKind(Kind);
612 
613   SmallString<128> Name;
614   if (Kind.isMergeableCString()) {
615     // We also need alignment here.
616     // FIXME: this is getting the alignment of the character, not the
617     // alignment of the global!
618     unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
619         cast<GlobalVariable>(GO));
620 
621     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
622     Name = SizeSpec + utostr(Align);
623   } else if (Kind.isMergeableConst()) {
624     Name = ".rodata.cst";
625     Name += utostr(EntrySize);
626   } else {
627     Name = getSectionPrefixForGlobal(Kind);
628   }
629 
630   if (const auto *F = dyn_cast<Function>(GO)) {
631     const auto &OptionalPrefix = F->getSectionPrefix();
632     if (OptionalPrefix)
633       Name += *OptionalPrefix;
634   }
635 
636   unsigned UniqueID = MCContext::GenericSectionID;
637   if (EmitUniqueSection) {
638     if (TM.getUniqueSectionNames()) {
639       Name.push_back('.');
640       TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
641     } else {
642       UniqueID = *NextUniqueID;
643       (*NextUniqueID)++;
644     }
645   }
646   // Use 0 as the unique ID for execute-only text.
647   if (Kind.isExecuteOnly())
648     UniqueID = 0;
649   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
650                            EntrySize, Group, UniqueID, AssociatedSymbol);
651 }
652 
653 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
654     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
655   unsigned Flags = getELFSectionFlags(Kind);
656 
657   // If we have -ffunction-section or -fdata-section then we should emit the
658   // global value to a uniqued section specifically for it.
659   bool EmitUniqueSection = false;
660   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
661     if (Kind.isText())
662       EmitUniqueSection = TM.getFunctionSections();
663     else
664       EmitUniqueSection = TM.getDataSections();
665   }
666   EmitUniqueSection |= GO->hasComdat();
667 
668   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
669   if (AssociatedSymbol) {
670     EmitUniqueSection = true;
671     Flags |= ELF::SHF_LINK_ORDER;
672   }
673 
674   MCSectionELF *Section = selectELFSectionForGlobal(
675       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
676       &NextUniqueID, AssociatedSymbol);
677   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
678   return Section;
679 }
680 
681 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
682     const Function &F, const TargetMachine &TM) const {
683   // If the function can be removed, produce a unique section so that
684   // the table doesn't prevent the removal.
685   const Comdat *C = F.getComdat();
686   bool EmitUniqueSection = TM.getFunctionSections() || C;
687   if (!EmitUniqueSection)
688     return ReadOnlySection;
689 
690   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
691                                    getMangler(), TM, EmitUniqueSection,
692                                    ELF::SHF_ALLOC, &NextUniqueID,
693                                    /* AssociatedSymbol */ nullptr);
694 }
695 
696 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
697     bool UsesLabelDifference, const Function &F) const {
698   // We can always create relative relocations, so use another section
699   // that can be marked non-executable.
700   return false;
701 }
702 
703 /// Given a mergeable constant with the specified size and relocation
704 /// information, return a section that it should be placed in.
705 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
706     const DataLayout &DL, SectionKind Kind, const Constant *C,
707     unsigned &Align) const {
708   if (Kind.isMergeableConst4() && MergeableConst4Section)
709     return MergeableConst4Section;
710   if (Kind.isMergeableConst8() && MergeableConst8Section)
711     return MergeableConst8Section;
712   if (Kind.isMergeableConst16() && MergeableConst16Section)
713     return MergeableConst16Section;
714   if (Kind.isMergeableConst32() && MergeableConst32Section)
715     return MergeableConst32Section;
716   if (Kind.isReadOnly())
717     return ReadOnlySection;
718 
719   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
720   return DataRelROSection;
721 }
722 
723 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
724                                               bool IsCtor, unsigned Priority,
725                                               const MCSymbol *KeySym) {
726   std::string Name;
727   unsigned Type;
728   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
729   StringRef COMDAT = KeySym ? KeySym->getName() : "";
730 
731   if (KeySym)
732     Flags |= ELF::SHF_GROUP;
733 
734   if (UseInitArray) {
735     if (IsCtor) {
736       Type = ELF::SHT_INIT_ARRAY;
737       Name = ".init_array";
738     } else {
739       Type = ELF::SHT_FINI_ARRAY;
740       Name = ".fini_array";
741     }
742     if (Priority != 65535) {
743       Name += '.';
744       Name += utostr(Priority);
745     }
746   } else {
747     // The default scheme is .ctor / .dtor, so we have to invert the priority
748     // numbering.
749     if (IsCtor)
750       Name = ".ctors";
751     else
752       Name = ".dtors";
753     if (Priority != 65535)
754       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
755     Type = ELF::SHT_PROGBITS;
756   }
757 
758   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
759 }
760 
761 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
762     unsigned Priority, const MCSymbol *KeySym) const {
763   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
764                                   KeySym);
765 }
766 
767 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
768     unsigned Priority, const MCSymbol *KeySym) const {
769   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
770                                   KeySym);
771 }
772 
773 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
774     const GlobalValue *LHS, const GlobalValue *RHS,
775     const TargetMachine &TM) const {
776   // We may only use a PLT-relative relocation to refer to unnamed_addr
777   // functions.
778   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
779     return nullptr;
780 
781   // Basic sanity checks.
782   if (LHS->getType()->getPointerAddressSpace() != 0 ||
783       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
784       RHS->isThreadLocal())
785     return nullptr;
786 
787   return MCBinaryExpr::createSub(
788       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
789                               getContext()),
790       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
791 }
792 
793 void
794 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
795   UseInitArray = UseInitArray_;
796   MCContext &Ctx = getContext();
797   if (!UseInitArray) {
798     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
799                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
800 
801     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
802                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
803     return;
804   }
805 
806   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
807                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
808   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
809                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
810 }
811 
812 //===----------------------------------------------------------------------===//
813 //                                 MachO
814 //===----------------------------------------------------------------------===//
815 
816 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
817   : TargetLoweringObjectFile() {
818   SupportIndirectSymViaGOTPCRel = true;
819 }
820 
821 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
822                                                const TargetMachine &TM) {
823   TargetLoweringObjectFile::Initialize(Ctx, TM);
824   if (TM.getRelocationModel() == Reloc::Static) {
825     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
826                                             SectionKind::getData());
827     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
828                                             SectionKind::getData());
829   } else {
830     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
831                                             MachO::S_MOD_INIT_FUNC_POINTERS,
832                                             SectionKind::getData());
833     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
834                                             MachO::S_MOD_TERM_FUNC_POINTERS,
835                                             SectionKind::getData());
836   }
837 
838   PersonalityEncoding =
839       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
840   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
841   TTypeEncoding =
842       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
843 }
844 
845 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
846                                                        Module &M) const {
847   // Emit the linker options if present.
848   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
849     for (const auto &Option : LinkerOptions->operands()) {
850       SmallVector<std::string, 4> StrOptions;
851       for (const auto &Piece : cast<MDNode>(Option)->operands())
852         StrOptions.push_back(cast<MDString>(Piece)->getString());
853       Streamer.EmitLinkerOptions(StrOptions);
854     }
855   }
856 
857   unsigned VersionVal = 0;
858   unsigned ImageInfoFlags = 0;
859   StringRef SectionVal;
860 
861   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
862 
863   // The section is mandatory. If we don't have it, then we don't have GC info.
864   if (SectionVal.empty())
865     return;
866 
867   StringRef Segment, Section;
868   unsigned TAA = 0, StubSize = 0;
869   bool TAAParsed;
870   std::string ErrorCode =
871     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
872                                           TAA, TAAParsed, StubSize);
873   if (!ErrorCode.empty())
874     // If invalid, report the error with report_fatal_error.
875     report_fatal_error("Invalid section specifier '" + Section + "': " +
876                        ErrorCode + ".");
877 
878   // Get the section.
879   MCSectionMachO *S = getContext().getMachOSection(
880       Segment, Section, TAA, StubSize, SectionKind::getData());
881   Streamer.SwitchSection(S);
882   Streamer.EmitLabel(getContext().
883                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
884   Streamer.EmitIntValue(VersionVal, 4);
885   Streamer.EmitIntValue(ImageInfoFlags, 4);
886   Streamer.AddBlankLine();
887 }
888 
889 static void checkMachOComdat(const GlobalValue *GV) {
890   const Comdat *C = GV->getComdat();
891   if (!C)
892     return;
893 
894   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
895                      "' cannot be lowered.");
896 }
897 
898 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
899     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
900   // Parse the section specifier and create it if valid.
901   StringRef Segment, Section;
902   unsigned TAA = 0, StubSize = 0;
903   bool TAAParsed;
904 
905   checkMachOComdat(GO);
906 
907   std::string ErrorCode =
908     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
909                                           TAA, TAAParsed, StubSize);
910   if (!ErrorCode.empty()) {
911     // If invalid, report the error with report_fatal_error.
912     report_fatal_error("Global variable '" + GO->getName() +
913                        "' has an invalid section specifier '" +
914                        GO->getSection() + "': " + ErrorCode + ".");
915   }
916 
917   // Get the section.
918   MCSectionMachO *S =
919       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
920 
921   // If TAA wasn't set by ParseSectionSpecifier() above,
922   // use the value returned by getMachOSection() as a default.
923   if (!TAAParsed)
924     TAA = S->getTypeAndAttributes();
925 
926   // Okay, now that we got the section, verify that the TAA & StubSize agree.
927   // If the user declared multiple globals with different section flags, we need
928   // to reject it here.
929   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
930     // If invalid, report the error with report_fatal_error.
931     report_fatal_error("Global variable '" + GO->getName() +
932                        "' section type or attributes does not match previous"
933                        " section specifier");
934   }
935 
936   return S;
937 }
938 
939 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
940     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
941   checkMachOComdat(GO);
942 
943   // Handle thread local data.
944   if (Kind.isThreadBSS()) return TLSBSSSection;
945   if (Kind.isThreadData()) return TLSDataSection;
946 
947   if (Kind.isText())
948     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
949 
950   // If this is weak/linkonce, put this in a coalescable section, either in text
951   // or data depending on if it is writable.
952   if (GO->isWeakForLinker()) {
953     if (Kind.isReadOnly())
954       return ConstTextCoalSection;
955     if (Kind.isReadOnlyWithRel())
956       return ConstDataCoalSection;
957     return DataCoalSection;
958   }
959 
960   // FIXME: Alignment check should be handled by section classifier.
961   if (Kind.isMergeable1ByteCString() &&
962       GO->getParent()->getDataLayout().getPreferredAlignment(
963           cast<GlobalVariable>(GO)) < 32)
964     return CStringSection;
965 
966   // Do not put 16-bit arrays in the UString section if they have an
967   // externally visible label, this runs into issues with certain linker
968   // versions.
969   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
970       GO->getParent()->getDataLayout().getPreferredAlignment(
971           cast<GlobalVariable>(GO)) < 32)
972     return UStringSection;
973 
974   // With MachO only variables whose corresponding symbol starts with 'l' or
975   // 'L' can be merged, so we only try merging GVs with private linkage.
976   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
977     if (Kind.isMergeableConst4())
978       return FourByteConstantSection;
979     if (Kind.isMergeableConst8())
980       return EightByteConstantSection;
981     if (Kind.isMergeableConst16())
982       return SixteenByteConstantSection;
983   }
984 
985   // Otherwise, if it is readonly, but not something we can specially optimize,
986   // just drop it in .const.
987   if (Kind.isReadOnly())
988     return ReadOnlySection;
989 
990   // If this is marked const, put it into a const section.  But if the dynamic
991   // linker needs to write to it, put it in the data segment.
992   if (Kind.isReadOnlyWithRel())
993     return ConstDataSection;
994 
995   // Put zero initialized globals with strong external linkage in the
996   // DATA, __common section with the .zerofill directive.
997   if (Kind.isBSSExtern())
998     return DataCommonSection;
999 
1000   // Put zero initialized globals with local linkage in __DATA,__bss directive
1001   // with the .zerofill directive (aka .lcomm).
1002   if (Kind.isBSSLocal())
1003     return DataBSSSection;
1004 
1005   // Otherwise, just drop the variable in the normal data section.
1006   return DataSection;
1007 }
1008 
1009 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1010     const DataLayout &DL, SectionKind Kind, const Constant *C,
1011     unsigned &Align) const {
1012   // If this constant requires a relocation, we have to put it in the data
1013   // segment, not in the text segment.
1014   if (Kind.isData() || Kind.isReadOnlyWithRel())
1015     return ConstDataSection;
1016 
1017   if (Kind.isMergeableConst4())
1018     return FourByteConstantSection;
1019   if (Kind.isMergeableConst8())
1020     return EightByteConstantSection;
1021   if (Kind.isMergeableConst16())
1022     return SixteenByteConstantSection;
1023   return ReadOnlySection;  // .const
1024 }
1025 
1026 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1027     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1028     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1029   // The mach-o version of this method defaults to returning a stub reference.
1030 
1031   if (Encoding & DW_EH_PE_indirect) {
1032     MachineModuleInfoMachO &MachOMMI =
1033       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1034 
1035     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1036 
1037     // Add information about the stub reference to MachOMMI so that the stub
1038     // gets emitted by the asmprinter.
1039     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1040     if (!StubSym.getPointer()) {
1041       MCSymbol *Sym = TM.getSymbol(GV);
1042       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1043     }
1044 
1045     return TargetLoweringObjectFile::
1046       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1047                         Encoding & ~DW_EH_PE_indirect, Streamer);
1048   }
1049 
1050   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1051                                                            MMI, Streamer);
1052 }
1053 
1054 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1055     const GlobalValue *GV, const TargetMachine &TM,
1056     MachineModuleInfo *MMI) const {
1057   // The mach-o version of this method defaults to returning a stub reference.
1058   MachineModuleInfoMachO &MachOMMI =
1059     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1060 
1061   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1062 
1063   // Add information about the stub reference to MachOMMI so that the stub
1064   // gets emitted by the asmprinter.
1065   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1066   if (!StubSym.getPointer()) {
1067     MCSymbol *Sym = TM.getSymbol(GV);
1068     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1069   }
1070 
1071   return SSym;
1072 }
1073 
1074 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1075     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
1076     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1077   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1078   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1079   // through a non_lazy_ptr stub instead. One advantage is that it allows the
1080   // computation of deltas to final external symbols. Example:
1081   //
1082   //    _extgotequiv:
1083   //       .long   _extfoo
1084   //
1085   //    _delta:
1086   //       .long   _extgotequiv-_delta
1087   //
1088   // is transformed to:
1089   //
1090   //    _delta:
1091   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1092   //
1093   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1094   //    L_extfoo$non_lazy_ptr:
1095   //       .indirect_symbol        _extfoo
1096   //       .long   0
1097   //
1098   MachineModuleInfoMachO &MachOMMI =
1099     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1100   MCContext &Ctx = getContext();
1101 
1102   // The offset must consider the original displacement from the base symbol
1103   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1104   Offset = -MV.getConstant();
1105   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1106 
1107   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1108   // non_lazy_ptr stubs.
1109   SmallString<128> Name;
1110   StringRef Suffix = "$non_lazy_ptr";
1111   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1112   Name += Sym->getName();
1113   Name += Suffix;
1114   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1115 
1116   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1117   if (!StubSym.getPointer())
1118     StubSym = MachineModuleInfoImpl::
1119       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
1120 
1121   const MCExpr *BSymExpr =
1122     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1123   const MCExpr *LHS =
1124     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1125 
1126   if (!Offset)
1127     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1128 
1129   const MCExpr *RHS =
1130     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1131   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1132 }
1133 
1134 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1135                                const MCSection &Section) {
1136   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1137     return true;
1138 
1139   // If it is not dead stripped, it is safe to use private labels.
1140   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1141   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
1142     return true;
1143 
1144   return false;
1145 }
1146 
1147 void TargetLoweringObjectFileMachO::getNameWithPrefix(
1148     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1149     const TargetMachine &TM) const {
1150   bool CannotUsePrivateLabel = true;
1151   if (auto *GO = GV->getBaseObject()) {
1152     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1153     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1154     CannotUsePrivateLabel =
1155         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1156   }
1157   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1158 }
1159 
1160 //===----------------------------------------------------------------------===//
1161 //                                  COFF
1162 //===----------------------------------------------------------------------===//
1163 
1164 static unsigned
1165 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1166   unsigned Flags = 0;
1167   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1168 
1169   if (K.isMetadata())
1170     Flags |=
1171       COFF::IMAGE_SCN_MEM_DISCARDABLE;
1172   else if (K.isText())
1173     Flags |=
1174       COFF::IMAGE_SCN_MEM_EXECUTE |
1175       COFF::IMAGE_SCN_MEM_READ |
1176       COFF::IMAGE_SCN_CNT_CODE |
1177       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1178   else if (K.isBSS())
1179     Flags |=
1180       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1181       COFF::IMAGE_SCN_MEM_READ |
1182       COFF::IMAGE_SCN_MEM_WRITE;
1183   else if (K.isThreadLocal())
1184     Flags |=
1185       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1186       COFF::IMAGE_SCN_MEM_READ |
1187       COFF::IMAGE_SCN_MEM_WRITE;
1188   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1189     Flags |=
1190       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1191       COFF::IMAGE_SCN_MEM_READ;
1192   else if (K.isWriteable())
1193     Flags |=
1194       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1195       COFF::IMAGE_SCN_MEM_READ |
1196       COFF::IMAGE_SCN_MEM_WRITE;
1197 
1198   return Flags;
1199 }
1200 
1201 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1202   const Comdat *C = GV->getComdat();
1203   assert(C && "expected GV to have a Comdat!");
1204 
1205   StringRef ComdatGVName = C->getName();
1206   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1207   if (!ComdatGV)
1208     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1209                        "' does not exist.");
1210 
1211   if (ComdatGV->getComdat() != C)
1212     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1213                        "' is not a key for its COMDAT.");
1214 
1215   return ComdatGV;
1216 }
1217 
1218 static int getSelectionForCOFF(const GlobalValue *GV) {
1219   if (const Comdat *C = GV->getComdat()) {
1220     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1221     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1222       ComdatKey = GA->getBaseObject();
1223     if (ComdatKey == GV) {
1224       switch (C->getSelectionKind()) {
1225       case Comdat::Any:
1226         return COFF::IMAGE_COMDAT_SELECT_ANY;
1227       case Comdat::ExactMatch:
1228         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1229       case Comdat::Largest:
1230         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1231       case Comdat::NoDuplicates:
1232         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1233       case Comdat::SameSize:
1234         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1235       }
1236     } else {
1237       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1238     }
1239   }
1240   return 0;
1241 }
1242 
1243 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1244     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1245   int Selection = 0;
1246   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1247   StringRef Name = GO->getSection();
1248   StringRef COMDATSymName = "";
1249   if (GO->hasComdat()) {
1250     Selection = getSelectionForCOFF(GO);
1251     const GlobalValue *ComdatGV;
1252     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1253       ComdatGV = getComdatGVForCOFF(GO);
1254     else
1255       ComdatGV = GO;
1256 
1257     if (!ComdatGV->hasPrivateLinkage()) {
1258       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1259       COMDATSymName = Sym->getName();
1260       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1261     } else {
1262       Selection = 0;
1263     }
1264   }
1265 
1266   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1267                                      Selection);
1268 }
1269 
1270 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1271   if (Kind.isText())
1272     return ".text";
1273   if (Kind.isBSS())
1274     return ".bss";
1275   if (Kind.isThreadLocal())
1276     return ".tls$";
1277   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1278     return ".rdata";
1279   return ".data";
1280 }
1281 
1282 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1283     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1284   // If we have -ffunction-sections then we should emit the global value to a
1285   // uniqued section specifically for it.
1286   bool EmitUniquedSection;
1287   if (Kind.isText())
1288     EmitUniquedSection = TM.getFunctionSections();
1289   else
1290     EmitUniquedSection = TM.getDataSections();
1291 
1292   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1293     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1294 
1295     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1296 
1297     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1298     int Selection = getSelectionForCOFF(GO);
1299     if (!Selection)
1300       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1301     const GlobalValue *ComdatGV;
1302     if (GO->hasComdat())
1303       ComdatGV = getComdatGVForCOFF(GO);
1304     else
1305       ComdatGV = GO;
1306 
1307     unsigned UniqueID = MCContext::GenericSectionID;
1308     if (EmitUniquedSection)
1309       UniqueID = NextUniqueID++;
1310 
1311     if (!ComdatGV->hasPrivateLinkage()) {
1312       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1313       StringRef COMDATSymName = Sym->getName();
1314 
1315       // Append "$symbol" to the section name when targetting mingw. The ld.bfd
1316       // COFF linker will not properly handle comdats otherwise.
1317       if (getTargetTriple().isWindowsGNUEnvironment())
1318         raw_svector_ostream(Name) << '$' << COMDATSymName;
1319 
1320       return getContext().getCOFFSection(Name, Characteristics, Kind,
1321                                          COMDATSymName, Selection, UniqueID);
1322     } else {
1323       SmallString<256> TmpData;
1324       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1325       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1326                                          Selection, UniqueID);
1327     }
1328   }
1329 
1330   if (Kind.isText())
1331     return TextSection;
1332 
1333   if (Kind.isThreadLocal())
1334     return TLSDataSection;
1335 
1336   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1337     return ReadOnlySection;
1338 
1339   // Note: we claim that common symbols are put in BSSSection, but they are
1340   // really emitted with the magic .comm directive, which creates a symbol table
1341   // entry but not a section.
1342   if (Kind.isBSS() || Kind.isCommon())
1343     return BSSSection;
1344 
1345   return DataSection;
1346 }
1347 
1348 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1349     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1350     const TargetMachine &TM) const {
1351   bool CannotUsePrivateLabel = false;
1352   if (GV->hasPrivateLinkage() &&
1353       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1354        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1355     CannotUsePrivateLabel = true;
1356 
1357   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1358 }
1359 
1360 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1361     const Function &F, const TargetMachine &TM) const {
1362   // If the function can be removed, produce a unique section so that
1363   // the table doesn't prevent the removal.
1364   const Comdat *C = F.getComdat();
1365   bool EmitUniqueSection = TM.getFunctionSections() || C;
1366   if (!EmitUniqueSection)
1367     return ReadOnlySection;
1368 
1369   // FIXME: we should produce a symbol for F instead.
1370   if (F.hasPrivateLinkage())
1371     return ReadOnlySection;
1372 
1373   MCSymbol *Sym = TM.getSymbol(&F);
1374   StringRef COMDATSymName = Sym->getName();
1375 
1376   SectionKind Kind = SectionKind::getReadOnly();
1377   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1378   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1379   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1380   unsigned UniqueID = NextUniqueID++;
1381 
1382   return getContext().getCOFFSection(
1383       SecName, Characteristics, Kind, COMDATSymName,
1384       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1385 }
1386 
1387 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1388                                                       Module &M) const {
1389   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1390     // Emit the linker options to the linker .drectve section.  According to the
1391     // spec, this section is a space-separated string containing flags for
1392     // linker.
1393     MCSection *Sec = getDrectveSection();
1394     Streamer.SwitchSection(Sec);
1395     for (const auto &Option : LinkerOptions->operands()) {
1396       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1397         // Lead with a space for consistency with our dllexport implementation.
1398         std::string Directive(" ");
1399         Directive.append(cast<MDString>(Piece)->getString());
1400         Streamer.EmitBytes(Directive);
1401       }
1402     }
1403   }
1404 
1405   unsigned Version = 0;
1406   unsigned Flags = 0;
1407   StringRef Section;
1408 
1409   GetObjCImageInfo(M, Version, Flags, Section);
1410   if (Section.empty())
1411     return;
1412 
1413   auto &C = getContext();
1414   auto *S = C.getCOFFSection(
1415       Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1416       SectionKind::getReadOnly());
1417   Streamer.SwitchSection(S);
1418   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1419   Streamer.EmitIntValue(Version, 4);
1420   Streamer.EmitIntValue(Flags, 4);
1421   Streamer.AddBlankLine();
1422 }
1423 
1424 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1425                                               const TargetMachine &TM) {
1426   TargetLoweringObjectFile::Initialize(Ctx, TM);
1427   const Triple &T = TM.getTargetTriple();
1428   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1429     StaticCtorSection =
1430         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1431                                            COFF::IMAGE_SCN_MEM_READ,
1432                            SectionKind::getReadOnly());
1433     StaticDtorSection =
1434         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1435                                            COFF::IMAGE_SCN_MEM_READ,
1436                            SectionKind::getReadOnly());
1437   } else {
1438     StaticCtorSection = Ctx.getCOFFSection(
1439         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1440                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1441         SectionKind::getData());
1442     StaticDtorSection = Ctx.getCOFFSection(
1443         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1444                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1445         SectionKind::getData());
1446   }
1447 }
1448 
1449 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1450                                                    const Triple &T, bool IsCtor,
1451                                                    unsigned Priority,
1452                                                    const MCSymbol *KeySym,
1453                                                    MCSectionCOFF *Default) {
1454   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment())
1455     return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1456 
1457   std::string Name = IsCtor ? ".ctors" : ".dtors";
1458   if (Priority != 65535)
1459     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1460 
1461   return Ctx.getAssociativeCOFFSection(
1462       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1463                                    COFF::IMAGE_SCN_MEM_READ |
1464                                    COFF::IMAGE_SCN_MEM_WRITE,
1465                          SectionKind::getData()),
1466       KeySym, 0);
1467 }
1468 
1469 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1470     unsigned Priority, const MCSymbol *KeySym) const {
1471   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1472                                       Priority, KeySym,
1473                                       cast<MCSectionCOFF>(StaticCtorSection));
1474 }
1475 
1476 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1477     unsigned Priority, const MCSymbol *KeySym) const {
1478   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1479                                       Priority, KeySym,
1480                                       cast<MCSectionCOFF>(StaticDtorSection));
1481 }
1482 
1483 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1484     raw_ostream &OS, const GlobalValue *GV) const {
1485   emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1486 }
1487 
1488 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1489     raw_ostream &OS, const GlobalValue *GV) const {
1490   emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1491 }
1492 
1493 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1494     const GlobalValue *LHS, const GlobalValue *RHS,
1495     const TargetMachine &TM) const {
1496   const Triple &T = TM.getTargetTriple();
1497   if (!T.isKnownWindowsMSVCEnvironment() &&
1498       !T.isWindowsItaniumEnvironment() &&
1499       !T.isWindowsCoreCLREnvironment())
1500     return nullptr;
1501 
1502   // Our symbols should exist in address space zero, cowardly no-op if
1503   // otherwise.
1504   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1505       RHS->getType()->getPointerAddressSpace() != 0)
1506     return nullptr;
1507 
1508   // Both ptrtoint instructions must wrap global objects:
1509   // - Only global variables are eligible for image relative relocations.
1510   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1511   // We expect __ImageBase to be a global variable without a section, externally
1512   // defined.
1513   //
1514   // It should look something like this: @__ImageBase = external constant i8
1515   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1516       LHS->isThreadLocal() || RHS->isThreadLocal() ||
1517       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1518       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1519     return nullptr;
1520 
1521   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1522                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
1523                                  getContext());
1524 }
1525 
1526 static std::string APIntToHexString(const APInt &AI) {
1527   unsigned Width = (AI.getBitWidth() / 8) * 2;
1528   std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
1529   unsigned Size = HexString.size();
1530   assert(Width >= Size && "hex string is too large!");
1531   HexString.insert(HexString.begin(), Width - Size, '0');
1532 
1533   return HexString;
1534 }
1535 
1536 static std::string scalarConstantToHexString(const Constant *C) {
1537   Type *Ty = C->getType();
1538   if (isa<UndefValue>(C)) {
1539     return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1540   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1541     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1542   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1543     return APIntToHexString(CI->getValue());
1544   } else {
1545     unsigned NumElements;
1546     if (isa<VectorType>(Ty))
1547       NumElements = Ty->getVectorNumElements();
1548     else
1549       NumElements = Ty->getArrayNumElements();
1550     std::string HexString;
1551     for (int I = NumElements - 1, E = -1; I != E; --I)
1552       HexString += scalarConstantToHexString(C->getAggregateElement(I));
1553     return HexString;
1554   }
1555 }
1556 
1557 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1558     const DataLayout &DL, SectionKind Kind, const Constant *C,
1559     unsigned &Align) const {
1560   if (Kind.isMergeableConst() && C &&
1561       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1562     // This creates comdat sections with the given symbol name, but unless
1563     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1564     // will be created with a null storage class, which makes GNU binutils
1565     // error out.
1566     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1567                                      COFF::IMAGE_SCN_MEM_READ |
1568                                      COFF::IMAGE_SCN_LNK_COMDAT;
1569     std::string COMDATSymName;
1570     if (Kind.isMergeableConst4()) {
1571       if (Align <= 4) {
1572         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1573         Align = 4;
1574       }
1575     } else if (Kind.isMergeableConst8()) {
1576       if (Align <= 8) {
1577         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1578         Align = 8;
1579       }
1580     } else if (Kind.isMergeableConst16()) {
1581       // FIXME: These may not be appropriate for non-x86 architectures.
1582       if (Align <= 16) {
1583         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1584         Align = 16;
1585       }
1586     } else if (Kind.isMergeableConst32()) {
1587       if (Align <= 32) {
1588         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1589         Align = 32;
1590       }
1591     }
1592 
1593     if (!COMDATSymName.empty())
1594       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1595                                          COMDATSymName,
1596                                          COFF::IMAGE_COMDAT_SELECT_ANY);
1597   }
1598 
1599   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1600 }
1601 
1602 
1603 //===----------------------------------------------------------------------===//
1604 //                                  Wasm
1605 //===----------------------------------------------------------------------===//
1606 
1607 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1608   const Comdat *C = GV->getComdat();
1609   if (!C)
1610     return nullptr;
1611 
1612   if (C->getSelectionKind() != Comdat::Any)
1613     report_fatal_error("WebAssembly COMDATs only support "
1614                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
1615                        "lowered.");
1616 
1617   return C;
1618 }
1619 
1620 static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
1621   // If we're told we have function data, then use that.
1622   if (K.isText())
1623     return SectionKind::getText();
1624 
1625   // Otherwise, ignore whatever section type the generic impl detected and use
1626   // a plain data section.
1627   return SectionKind::getData();
1628 }
1629 
1630 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1631     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1632   // We don't support explict section names for functions in the wasm object
1633   // format.  Each function has to be in its own unique section.
1634   if (isa<Function>(GO)) {
1635     return SelectSectionForGlobal(GO, Kind, TM);
1636   }
1637 
1638   StringRef Name = GO->getSection();
1639 
1640   Kind = getWasmKindForNamedSection(Name, Kind);
1641 
1642   StringRef Group = "";
1643   if (const Comdat *C = getWasmComdat(GO)) {
1644     Group = C->getName();
1645   }
1646 
1647   return getContext().getWasmSection(Name, Kind, Group,
1648                                      MCContext::GenericSectionID);
1649 }
1650 
1651 static MCSectionWasm *selectWasmSectionForGlobal(
1652     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1653     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1654   StringRef Group = "";
1655   if (const Comdat *C = getWasmComdat(GO)) {
1656     Group = C->getName();
1657   }
1658 
1659   bool UniqueSectionNames = TM.getUniqueSectionNames();
1660   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1661 
1662   if (const auto *F = dyn_cast<Function>(GO)) {
1663     const auto &OptionalPrefix = F->getSectionPrefix();
1664     if (OptionalPrefix)
1665       Name += *OptionalPrefix;
1666   }
1667 
1668   if (EmitUniqueSection && UniqueSectionNames) {
1669     Name.push_back('.');
1670     TM.getNameWithPrefix(Name, GO, Mang, true);
1671   }
1672   unsigned UniqueID = MCContext::GenericSectionID;
1673   if (EmitUniqueSection && !UniqueSectionNames) {
1674     UniqueID = *NextUniqueID;
1675     (*NextUniqueID)++;
1676   }
1677   return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1678 }
1679 
1680 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1681     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1682 
1683   if (Kind.isCommon())
1684     report_fatal_error("mergable sections not supported yet on wasm");
1685 
1686   // If we have -ffunction-section or -fdata-section then we should emit the
1687   // global value to a uniqued section specifically for it.
1688   bool EmitUniqueSection = false;
1689   if (Kind.isText())
1690     EmitUniqueSection = TM.getFunctionSections();
1691   else
1692     EmitUniqueSection = TM.getDataSections();
1693   EmitUniqueSection |= GO->hasComdat();
1694 
1695   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1696                                     EmitUniqueSection, &NextUniqueID);
1697 }
1698 
1699 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1700     bool UsesLabelDifference, const Function &F) const {
1701   // We can always create relative relocations, so use another section
1702   // that can be marked non-executable.
1703   return false;
1704 }
1705 
1706 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1707     const GlobalValue *LHS, const GlobalValue *RHS,
1708     const TargetMachine &TM) const {
1709   // We may only use a PLT-relative relocation to refer to unnamed_addr
1710   // functions.
1711   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1712     return nullptr;
1713 
1714   // Basic sanity checks.
1715   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1716       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1717       RHS->isThreadLocal())
1718     return nullptr;
1719 
1720   return MCBinaryExpr::createSub(
1721       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1722                               getContext()),
1723       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1724 }
1725 
1726 void TargetLoweringObjectFileWasm::InitializeWasm() {
1727   StaticCtorSection =
1728       getContext().getWasmSection(".init_array", SectionKind::getData());
1729 }
1730 
1731 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1732     unsigned Priority, const MCSymbol *KeySym) const {
1733   return Priority == UINT16_MAX ?
1734          StaticCtorSection :
1735          getContext().getWasmSection(".init_array." + utostr(Priority),
1736                                      SectionKind::getData());
1737 }
1738 
1739 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1740     unsigned Priority, const MCSymbol *KeySym) const {
1741   llvm_unreachable("@llvm.global_dtors should have been lowered already");
1742   return nullptr;
1743 }
1744