xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision a97f62837f59620a60b3ed9f29568440c7d0553a)
1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/COFF.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/BinaryFormat/MachO.h"
24 #include "llvm/CodeGen/BasicBlockSectionUtils.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
29 #include "llvm/IR/Comdat.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/DiagnosticPrinter.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalAlias.h"
37 #include "llvm/IR/GlobalObject.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Mangler.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSectionCOFF.h"
48 #include "llvm/MC/MCSectionELF.h"
49 #include "llvm/MC/MCSectionMachO.h"
50 #include "llvm/MC/MCSectionWasm.h"
51 #include "llvm/MC/MCSectionXCOFF.h"
52 #include "llvm/MC/MCStreamer.h"
53 #include "llvm/MC/MCSymbol.h"
54 #include "llvm/MC/MCSymbolELF.h"
55 #include "llvm/MC/MCValue.h"
56 #include "llvm/MC/SectionKind.h"
57 #include "llvm/ProfileData/InstrProf.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/Format.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include <cassert>
65 #include <string>
66 
67 using namespace llvm;
68 using namespace dwarf;
69 
70 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
71                              StringRef &Section) {
72   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
73   M.getModuleFlagsMetadata(ModuleFlags);
74 
75   for (const auto &MFE: ModuleFlags) {
76     // Ignore flags with 'Require' behaviour.
77     if (MFE.Behavior == Module::Require)
78       continue;
79 
80     StringRef Key = MFE.Key->getString();
81     if (Key == "Objective-C Image Info Version") {
82       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
83     } else if (Key == "Objective-C Garbage Collection" ||
84                Key == "Objective-C GC Only" ||
85                Key == "Objective-C Is Simulated" ||
86                Key == "Objective-C Class Properties" ||
87                Key == "Objective-C Image Swift Version") {
88       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
89     } else if (Key == "Objective-C Image Info Section") {
90       Section = cast<MDString>(MFE.Val)->getString();
91     }
92     // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
93     // "Objective-C Garbage Collection".
94     else if (Key == "Swift ABI Version") {
95       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
96     } else if (Key == "Swift Major Version") {
97       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
98     } else if (Key == "Swift Minor Version") {
99       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
100     }
101   }
102 }
103 
104 //===----------------------------------------------------------------------===//
105 //                                  ELF
106 //===----------------------------------------------------------------------===//
107 
108 TargetLoweringObjectFileELF::TargetLoweringObjectFileELF()
109     : TargetLoweringObjectFile() {
110   SupportDSOLocalEquivalentLowering = true;
111 }
112 
113 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
114                                              const TargetMachine &TgtM) {
115   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
116   TM = &TgtM;
117 
118   CodeModel::Model CM = TgtM.getCodeModel();
119   InitializeELF(TgtM.Options.UseInitArray);
120 
121   switch (TgtM.getTargetTriple().getArch()) {
122   case Triple::arm:
123   case Triple::armeb:
124   case Triple::thumb:
125   case Triple::thumbeb:
126     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
127       break;
128     // Fallthrough if not using EHABI
129     LLVM_FALLTHROUGH;
130   case Triple::ppc:
131   case Triple::x86:
132     PersonalityEncoding = isPositionIndependent()
133                               ? dwarf::DW_EH_PE_indirect |
134                                     dwarf::DW_EH_PE_pcrel |
135                                     dwarf::DW_EH_PE_sdata4
136                               : dwarf::DW_EH_PE_absptr;
137     LSDAEncoding = isPositionIndependent()
138                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
139                        : dwarf::DW_EH_PE_absptr;
140     TTypeEncoding = isPositionIndependent()
141                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
142                               dwarf::DW_EH_PE_sdata4
143                         : dwarf::DW_EH_PE_absptr;
144     break;
145   case Triple::x86_64:
146     if (isPositionIndependent()) {
147       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
148         ((CM == CodeModel::Small || CM == CodeModel::Medium)
149          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
150       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
151         (CM == CodeModel::Small
152          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
153       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
154         ((CM == CodeModel::Small || CM == CodeModel::Medium)
155          ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
156     } else {
157       PersonalityEncoding =
158         (CM == CodeModel::Small || CM == CodeModel::Medium)
159         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
160       LSDAEncoding = (CM == CodeModel::Small)
161         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
162       TTypeEncoding = (CM == CodeModel::Small)
163         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
164     }
165     break;
166   case Triple::hexagon:
167     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
168     LSDAEncoding = dwarf::DW_EH_PE_absptr;
169     TTypeEncoding = dwarf::DW_EH_PE_absptr;
170     if (isPositionIndependent()) {
171       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
172       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
173       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
174     }
175     break;
176   case Triple::aarch64:
177   case Triple::aarch64_be:
178   case Triple::aarch64_32:
179     // The small model guarantees static code/data size < 4GB, but not where it
180     // will be in memory. Most of these could end up >2GB away so even a signed
181     // pc-relative 32-bit address is insufficient, theoretically.
182     if (isPositionIndependent()) {
183       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
184         dwarf::DW_EH_PE_sdata8;
185       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
186       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
187         dwarf::DW_EH_PE_sdata8;
188     } else {
189       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
190       LSDAEncoding = dwarf::DW_EH_PE_absptr;
191       TTypeEncoding = dwarf::DW_EH_PE_absptr;
192     }
193     break;
194   case Triple::lanai:
195     LSDAEncoding = dwarf::DW_EH_PE_absptr;
196     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
197     TTypeEncoding = dwarf::DW_EH_PE_absptr;
198     break;
199   case Triple::mips:
200   case Triple::mipsel:
201   case Triple::mips64:
202   case Triple::mips64el:
203     // MIPS uses indirect pointer to refer personality functions and types, so
204     // that the eh_frame section can be read-only. DW.ref.personality will be
205     // generated for relocation.
206     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
207     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
208     //        identify N64 from just a triple.
209     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
210                     dwarf::DW_EH_PE_sdata4;
211     // We don't support PC-relative LSDA references in GAS so we use the default
212     // DW_EH_PE_absptr for those.
213 
214     // FreeBSD must be explicit about the data size and using pcrel since it's
215     // assembler/linker won't do the automatic conversion that the Linux tools
216     // do.
217     if (TgtM.getTargetTriple().isOSFreeBSD()) {
218       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
219       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
220     }
221     break;
222   case Triple::ppc64:
223   case Triple::ppc64le:
224     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
225       dwarf::DW_EH_PE_udata8;
226     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
227     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
228       dwarf::DW_EH_PE_udata8;
229     break;
230   case Triple::sparcel:
231   case Triple::sparc:
232     if (isPositionIndependent()) {
233       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
234       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
235         dwarf::DW_EH_PE_sdata4;
236       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
237         dwarf::DW_EH_PE_sdata4;
238     } else {
239       LSDAEncoding = dwarf::DW_EH_PE_absptr;
240       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
241       TTypeEncoding = dwarf::DW_EH_PE_absptr;
242     }
243     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
244     break;
245   case Triple::riscv32:
246   case Triple::riscv64:
247     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
248     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
249                           dwarf::DW_EH_PE_sdata4;
250     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
251                     dwarf::DW_EH_PE_sdata4;
252     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
253     break;
254   case Triple::sparcv9:
255     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
256     if (isPositionIndependent()) {
257       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
258         dwarf::DW_EH_PE_sdata4;
259       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
260         dwarf::DW_EH_PE_sdata4;
261     } else {
262       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
263       TTypeEncoding = dwarf::DW_EH_PE_absptr;
264     }
265     break;
266   case Triple::systemz:
267     // All currently-defined code models guarantee that 4-byte PC-relative
268     // values will be in range.
269     if (isPositionIndependent()) {
270       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
271         dwarf::DW_EH_PE_sdata4;
272       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
273       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
274         dwarf::DW_EH_PE_sdata4;
275     } else {
276       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
277       LSDAEncoding = dwarf::DW_EH_PE_absptr;
278       TTypeEncoding = dwarf::DW_EH_PE_absptr;
279     }
280     break;
281   default:
282     break;
283   }
284 }
285 
286 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
287                                                      Module &M) const {
288   auto &C = getContext();
289 
290   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
291     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
292                               ELF::SHF_EXCLUDE);
293 
294     Streamer.SwitchSection(S);
295 
296     for (const auto *Operand : LinkerOptions->operands()) {
297       if (cast<MDNode>(Operand)->getNumOperands() != 2)
298         report_fatal_error("invalid llvm.linker.options");
299       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
300         Streamer.emitBytes(cast<MDString>(Option)->getString());
301         Streamer.emitInt8(0);
302       }
303     }
304   }
305 
306   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
307     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
308                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
309 
310     Streamer.SwitchSection(S);
311 
312     for (const auto *Operand : DependentLibraries->operands()) {
313       Streamer.emitBytes(
314           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
315       Streamer.emitInt8(0);
316     }
317   }
318 
319   unsigned Version = 0;
320   unsigned Flags = 0;
321   StringRef Section;
322 
323   GetObjCImageInfo(M, Version, Flags, Section);
324   if (!Section.empty()) {
325     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
326     Streamer.SwitchSection(S);
327     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
328     Streamer.emitInt32(Version);
329     Streamer.emitInt32(Flags);
330     Streamer.AddBlankLine();
331   }
332 
333   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
334   M.getModuleFlagsMetadata(ModuleFlags);
335 
336   MDNode *CFGProfile = nullptr;
337 
338   for (const auto &MFE : ModuleFlags) {
339     StringRef Key = MFE.Key->getString();
340     if (Key == "CG Profile") {
341       CFGProfile = cast<MDNode>(MFE.Val);
342       break;
343     }
344   }
345 
346   if (!CFGProfile)
347     return;
348 
349   auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
350     if (!MDO)
351       return nullptr;
352     auto V = cast<ValueAsMetadata>(MDO);
353     const Function *F = cast<Function>(V->getValue()->stripPointerCasts());
354     return TM->getSymbol(F);
355   };
356 
357   for (const auto &Edge : CFGProfile->operands()) {
358     MDNode *E = cast<MDNode>(Edge);
359     const MCSymbol *From = GetSym(E->getOperand(0));
360     const MCSymbol *To = GetSym(E->getOperand(1));
361     // Skip null functions. This can happen if functions are dead stripped after
362     // the CGProfile pass has been run.
363     if (!From || !To)
364       continue;
365     uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
366                          ->getValue()
367                          ->getUniqueInteger()
368                          .getZExtValue();
369     Streamer.emitCGProfileEntry(
370         MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
371         MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
372   }
373 }
374 
375 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
376     const GlobalValue *GV, const TargetMachine &TM,
377     MachineModuleInfo *MMI) const {
378   unsigned Encoding = getPersonalityEncoding();
379   if ((Encoding & 0x80) == DW_EH_PE_indirect)
380     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
381                                           TM.getSymbol(GV)->getName());
382   if ((Encoding & 0x70) == DW_EH_PE_absptr)
383     return TM.getSymbol(GV);
384   report_fatal_error("We do not support this DWARF encoding yet!");
385 }
386 
387 void TargetLoweringObjectFileELF::emitPersonalityValue(
388     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
389   SmallString<64> NameData("DW.ref.");
390   NameData += Sym->getName();
391   MCSymbolELF *Label =
392       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
393   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
394   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
395   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
396   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
397                                                    ELF::SHT_PROGBITS, Flags, 0);
398   unsigned Size = DL.getPointerSize();
399   Streamer.SwitchSection(Sec);
400   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
401   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
402   const MCExpr *E = MCConstantExpr::create(Size, getContext());
403   Streamer.emitELFSize(Label, E);
404   Streamer.emitLabel(Label);
405 
406   Streamer.emitSymbolValue(Sym, Size);
407 }
408 
409 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
410     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
411     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
412   if (Encoding & DW_EH_PE_indirect) {
413     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
414 
415     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
416 
417     // Add information about the stub reference to ELFMMI so that the stub
418     // gets emitted by the asmprinter.
419     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
420     if (!StubSym.getPointer()) {
421       MCSymbol *Sym = TM.getSymbol(GV);
422       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
423     }
424 
425     return TargetLoweringObjectFile::
426       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
427                         Encoding & ~DW_EH_PE_indirect, Streamer);
428   }
429 
430   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
431                                                            MMI, Streamer);
432 }
433 
434 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
435   // N.B.: The defaults used in here are not the same ones used in MC.
436   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
437   // both gas and MC will produce a section with no flags. Given
438   // section(".eh_frame") gcc will produce:
439   //
440   //   .section   .eh_frame,"a",@progbits
441 
442   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
443                                       /*AddSegmentInfo=*/false) ||
444       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
445                                       /*AddSegmentInfo=*/false) ||
446       Name == ".llvmbc" || Name == ".llvmcmd")
447     return SectionKind::getMetadata();
448 
449   if (Name.empty() || Name[0] != '.') return K;
450 
451   // Default implementation based on some magic section names.
452   if (Name == ".bss" ||
453       Name.startswith(".bss.") ||
454       Name.startswith(".gnu.linkonce.b.") ||
455       Name.startswith(".llvm.linkonce.b.") ||
456       Name == ".sbss" ||
457       Name.startswith(".sbss.") ||
458       Name.startswith(".gnu.linkonce.sb.") ||
459       Name.startswith(".llvm.linkonce.sb."))
460     return SectionKind::getBSS();
461 
462   if (Name == ".tdata" ||
463       Name.startswith(".tdata.") ||
464       Name.startswith(".gnu.linkonce.td.") ||
465       Name.startswith(".llvm.linkonce.td."))
466     return SectionKind::getThreadData();
467 
468   if (Name == ".tbss" ||
469       Name.startswith(".tbss.") ||
470       Name.startswith(".gnu.linkonce.tb.") ||
471       Name.startswith(".llvm.linkonce.tb."))
472     return SectionKind::getThreadBSS();
473 
474   return K;
475 }
476 
477 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
478   // Use SHT_NOTE for section whose name starts with ".note" to allow
479   // emitting ELF notes from C variable declaration.
480   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
481   if (Name.startswith(".note"))
482     return ELF::SHT_NOTE;
483 
484   if (Name == ".init_array")
485     return ELF::SHT_INIT_ARRAY;
486 
487   if (Name == ".fini_array")
488     return ELF::SHT_FINI_ARRAY;
489 
490   if (Name == ".preinit_array")
491     return ELF::SHT_PREINIT_ARRAY;
492 
493   if (K.isBSS() || K.isThreadBSS())
494     return ELF::SHT_NOBITS;
495 
496   return ELF::SHT_PROGBITS;
497 }
498 
499 static unsigned getELFSectionFlags(SectionKind K) {
500   unsigned Flags = 0;
501 
502   if (!K.isMetadata())
503     Flags |= ELF::SHF_ALLOC;
504 
505   if (K.isText())
506     Flags |= ELF::SHF_EXECINSTR;
507 
508   if (K.isExecuteOnly())
509     Flags |= ELF::SHF_ARM_PURECODE;
510 
511   if (K.isWriteable())
512     Flags |= ELF::SHF_WRITE;
513 
514   if (K.isThreadLocal())
515     Flags |= ELF::SHF_TLS;
516 
517   if (K.isMergeableCString() || K.isMergeableConst())
518     Flags |= ELF::SHF_MERGE;
519 
520   if (K.isMergeableCString())
521     Flags |= ELF::SHF_STRINGS;
522 
523   return Flags;
524 }
525 
526 static const Comdat *getELFComdat(const GlobalValue *GV) {
527   const Comdat *C = GV->getComdat();
528   if (!C)
529     return nullptr;
530 
531   if (C->getSelectionKind() != Comdat::Any)
532     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
533                        C->getName() + "' cannot be lowered.");
534 
535   return C;
536 }
537 
538 static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
539                                             const TargetMachine &TM) {
540   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
541   if (!MD)
542     return nullptr;
543 
544   const MDOperand &Op = MD->getOperand(0);
545   if (!Op.get())
546     return nullptr;
547 
548   auto *VM = dyn_cast<ValueAsMetadata>(Op);
549   if (!VM)
550     report_fatal_error("MD_associated operand is not ValueAsMetadata");
551 
552   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
553   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
554 }
555 
556 static unsigned getEntrySizeForKind(SectionKind Kind) {
557   if (Kind.isMergeable1ByteCString())
558     return 1;
559   else if (Kind.isMergeable2ByteCString())
560     return 2;
561   else if (Kind.isMergeable4ByteCString())
562     return 4;
563   else if (Kind.isMergeableConst4())
564     return 4;
565   else if (Kind.isMergeableConst8())
566     return 8;
567   else if (Kind.isMergeableConst16())
568     return 16;
569   else if (Kind.isMergeableConst32())
570     return 32;
571   else {
572     // We shouldn't have mergeable C strings or mergeable constants that we
573     // didn't handle above.
574     assert(!Kind.isMergeableCString() && "unknown string width");
575     assert(!Kind.isMergeableConst() && "unknown data width");
576     return 0;
577   }
578 }
579 
580 /// Return the section prefix name used by options FunctionsSections and
581 /// DataSections.
582 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
583   if (Kind.isText())
584     return ".text";
585   if (Kind.isReadOnly())
586     return ".rodata";
587   if (Kind.isBSS())
588     return ".bss";
589   if (Kind.isThreadData())
590     return ".tdata";
591   if (Kind.isThreadBSS())
592     return ".tbss";
593   if (Kind.isData())
594     return ".data";
595   if (Kind.isReadOnlyWithRel())
596     return ".data.rel.ro";
597   llvm_unreachable("Unknown section kind");
598 }
599 
600 static SmallString<128>
601 getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
602                            Mangler &Mang, const TargetMachine &TM,
603                            unsigned EntrySize, bool UniqueSectionName) {
604   SmallString<128> Name;
605   if (Kind.isMergeableCString()) {
606     // We also need alignment here.
607     // FIXME: this is getting the alignment of the character, not the
608     // alignment of the global!
609     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
610         cast<GlobalVariable>(GO));
611 
612     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
613     Name = SizeSpec + utostr(Alignment.value());
614   } else if (Kind.isMergeableConst()) {
615     Name = ".rodata.cst";
616     Name += utostr(EntrySize);
617   } else {
618     Name = getSectionPrefixForGlobal(Kind);
619   }
620 
621   bool HasPrefix = false;
622   if (const auto *F = dyn_cast<Function>(GO)) {
623     if (Optional<StringRef> Prefix = F->getSectionPrefix()) {
624       Name += *Prefix;
625       HasPrefix = true;
626     }
627   }
628 
629   if (UniqueSectionName) {
630     Name.push_back('.');
631     TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
632   } else if (HasPrefix)
633     Name.push_back('.');
634   return Name;
635 }
636 
637 namespace {
638 class LoweringDiagnosticInfo : public DiagnosticInfo {
639   const Twine &Msg;
640 
641 public:
642   LoweringDiagnosticInfo(const Twine &DiagMsg,
643                          DiagnosticSeverity Severity = DS_Error)
644       : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
645   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
646 };
647 }
648 
649 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
650     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
651   StringRef SectionName = GO->getSection();
652 
653   // Check if '#pragma clang section' name is applicable.
654   // Note that pragma directive overrides -ffunction-section, -fdata-section
655   // and so section name is exactly as user specified and not uniqued.
656   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
657   if (GV && GV->hasImplicitSection()) {
658     auto Attrs = GV->getAttributes();
659     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
660       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
661     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
662       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
663     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
664       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
665     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
666       SectionName = Attrs.getAttribute("data-section").getValueAsString();
667     }
668   }
669   const Function *F = dyn_cast<Function>(GO);
670   if (F && F->hasFnAttribute("implicit-section-name")) {
671     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
672   }
673 
674   // Infer section flags from the section name if we can.
675   Kind = getELFKindForNamedSection(SectionName, Kind);
676 
677   StringRef Group = "";
678   unsigned Flags = getELFSectionFlags(Kind);
679   if (const Comdat *C = getELFComdat(GO)) {
680     Group = C->getName();
681     Flags |= ELF::SHF_GROUP;
682   }
683 
684   unsigned EntrySize = getEntrySizeForKind(Kind);
685 
686   // A section can have at most one associated section. Put each global with
687   // MD_associated in a unique section.
688   unsigned UniqueID = MCContext::GenericSectionID;
689   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
690   if (GO->getMetadata(LLVMContext::MD_associated)) {
691     UniqueID = NextUniqueID++;
692     Flags |= ELF::SHF_LINK_ORDER;
693   } else {
694     if (getContext().getAsmInfo()->useIntegratedAssembler()) {
695       // Symbols must be placed into sections with compatible entry
696       // sizes. Generate unique sections for symbols that have not
697       // been assigned to compatible sections.
698       if (Flags & ELF::SHF_MERGE) {
699         auto maybeID = getContext().getELFUniqueIDForEntsize(SectionName, Flags,
700                                                              EntrySize);
701         if (maybeID)
702           UniqueID = *maybeID;
703         else {
704           // If the user has specified the same section name as would be created
705           // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
706           // to unique the section as the entry size for this symbol will be
707           // compatible with implicitly created sections.
708           SmallString<128> ImplicitSectionNameStem = getELFSectionNameForGlobal(
709               GO, Kind, getMangler(), TM, EntrySize, false);
710           if (!(getContext().isELFImplicitMergeableSectionNamePrefix(
711                     SectionName) &&
712                 SectionName.startswith(ImplicitSectionNameStem)))
713             UniqueID = NextUniqueID++;
714         }
715       } else {
716         // We need to unique the section if the user has explicity
717         // assigned a non-mergeable symbol to a section name for
718         // a generic mergeable section.
719         if (getContext().isELFGenericMergeableSection(SectionName)) {
720           auto maybeID = getContext().getELFUniqueIDForEntsize(
721               SectionName, Flags, EntrySize);
722           UniqueID = maybeID ? *maybeID : NextUniqueID++;
723         }
724       }
725     } else {
726       // If two symbols with differing sizes end up in the same mergeable
727       // section that section can be assigned an incorrect entry size. To avoid
728       // this we usually put symbols of the same size into distinct mergeable
729       // sections with the same name. Doing so relies on the ",unique ,"
730       // assembly feature. This feature is not avalible until bintuils
731       // version 2.35 (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
732       Flags &= ~ELF::SHF_MERGE;
733       EntrySize = 0;
734     }
735   }
736 
737   MCSectionELF *Section = getContext().getELFSection(
738       SectionName, getELFSectionType(SectionName, Kind), Flags,
739       EntrySize, Group, UniqueID, LinkedToSym);
740   // Make sure that we did not get some other section with incompatible sh_link.
741   // This should not be possible due to UniqueID code above.
742   assert(Section->getLinkedToSymbol() == LinkedToSym &&
743          "Associated symbol mismatch between sections");
744 
745   if (!getContext().getAsmInfo()->useIntegratedAssembler()) {
746     // If we are not using the integrated assembler then this symbol might have
747     // been placed in an incompatible mergeable section. Emit an error if this
748     // is the case to avoid creating broken output.
749     if ((Section->getFlags() & ELF::SHF_MERGE) &&
750         (Section->getEntrySize() != getEntrySizeForKind(Kind)))
751       GO->getContext().diagnose(LoweringDiagnosticInfo(
752           "Symbol '" + GO->getName() + "' from module '" +
753           (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
754           "' required a section with entry-size=" +
755           Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
756           SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
757           ": Explicit assignment by pragma or attribute of an incompatible "
758           "symbol to this section?"));
759   }
760 
761   return Section;
762 }
763 
764 static MCSectionELF *selectELFSectionForGlobal(
765     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
766     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
767     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
768 
769   StringRef Group = "";
770   if (const Comdat *C = getELFComdat(GO)) {
771     Flags |= ELF::SHF_GROUP;
772     Group = C->getName();
773   }
774 
775   // Get the section entry size based on the kind.
776   unsigned EntrySize = getEntrySizeForKind(Kind);
777 
778   bool UniqueSectionName = false;
779   unsigned UniqueID = MCContext::GenericSectionID;
780   if (EmitUniqueSection) {
781     if (TM.getUniqueSectionNames()) {
782       UniqueSectionName = true;
783     } else {
784       UniqueID = *NextUniqueID;
785       (*NextUniqueID)++;
786     }
787   }
788   SmallString<128> Name = getELFSectionNameForGlobal(
789       GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
790 
791   // Use 0 as the unique ID for execute-only text.
792   if (Kind.isExecuteOnly())
793     UniqueID = 0;
794   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
795                            EntrySize, Group, UniqueID, AssociatedSymbol);
796 }
797 
798 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
799     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
800   unsigned Flags = getELFSectionFlags(Kind);
801 
802   // If we have -ffunction-section or -fdata-section then we should emit the
803   // global value to a uniqued section specifically for it.
804   bool EmitUniqueSection = false;
805   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
806     if (Kind.isText())
807       EmitUniqueSection = TM.getFunctionSections();
808     else
809       EmitUniqueSection = TM.getDataSections();
810   }
811   EmitUniqueSection |= GO->hasComdat();
812 
813   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
814   if (LinkedToSym) {
815     EmitUniqueSection = true;
816     Flags |= ELF::SHF_LINK_ORDER;
817   }
818 
819   MCSectionELF *Section = selectELFSectionForGlobal(
820       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
821       &NextUniqueID, LinkedToSym);
822   assert(Section->getLinkedToSymbol() == LinkedToSym);
823   return Section;
824 }
825 
826 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
827     const Function &F, const TargetMachine &TM) const {
828   // If the function can be removed, produce a unique section so that
829   // the table doesn't prevent the removal.
830   const Comdat *C = F.getComdat();
831   bool EmitUniqueSection = TM.getFunctionSections() || C;
832   if (!EmitUniqueSection)
833     return ReadOnlySection;
834 
835   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
836                                    getMangler(), TM, EmitUniqueSection,
837                                    ELF::SHF_ALLOC, &NextUniqueID,
838                                    /* AssociatedSymbol */ nullptr);
839 }
840 
841 MCSection *
842 TargetLoweringObjectFileELF::getSectionForLSDA(const Function &F,
843                                                const TargetMachine &TM) const {
844   // If neither COMDAT nor function sections, use the monolithic LSDA section.
845   // Re-use this path if LSDASection is null as in the Arm EHABI.
846   if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
847     return LSDASection;
848 
849   const auto *LSDA = cast<MCSectionELF>(LSDASection);
850   unsigned Flags = LSDA->getFlags();
851   StringRef Group;
852   if (F.hasComdat()) {
853     Group = F.getComdat()->getName();
854     Flags |= ELF::SHF_GROUP;
855   }
856 
857   // Append the function name as the suffix like GCC, assuming
858   // -funique-section-names applies to .gcc_except_table sections.
859   if (TM.getUniqueSectionNames())
860     return getContext().getELFSection(LSDA->getName() + "." + F.getName(),
861                                       LSDA->getType(), Flags, 0, Group,
862                                       MCSection::NonUniqueID, nullptr);
863 
864   // Allocate a unique ID if function sections && (integrated assembler or GNU
865   // as>=2.35). Note we could use SHF_LINK_ORDER to facilitate --gc-sections but
866   // that would require that we know the linker is a modern LLD (12.0 or later).
867   // GNU ld as of 2.35 does not support mixed SHF_LINK_ORDER &
868   // non-SHF_LINK_ORDER components in an output section
869   // https://sourceware.org/bugzilla/show_bug.cgi?id=26256
870   unsigned ID = TM.getFunctionSections() &&
871                         getContext().getAsmInfo()->useIntegratedAssembler()
872                     ? NextUniqueID++
873                     : MCSection::NonUniqueID;
874   return getContext().getELFSection(LSDA->getName(), LSDA->getType(), Flags, 0,
875                                     Group, ID, nullptr);
876 }
877 
878 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
879     bool UsesLabelDifference, const Function &F) const {
880   // We can always create relative relocations, so use another section
881   // that can be marked non-executable.
882   return false;
883 }
884 
885 /// Given a mergeable constant with the specified size and relocation
886 /// information, return a section that it should be placed in.
887 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
888     const DataLayout &DL, SectionKind Kind, const Constant *C,
889     Align &Alignment) const {
890   if (Kind.isMergeableConst4() && MergeableConst4Section)
891     return MergeableConst4Section;
892   if (Kind.isMergeableConst8() && MergeableConst8Section)
893     return MergeableConst8Section;
894   if (Kind.isMergeableConst16() && MergeableConst16Section)
895     return MergeableConst16Section;
896   if (Kind.isMergeableConst32() && MergeableConst32Section)
897     return MergeableConst32Section;
898   if (Kind.isReadOnly())
899     return ReadOnlySection;
900 
901   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
902   return DataRelROSection;
903 }
904 
905 /// Returns a unique section for the given machine basic block.
906 MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
907     const Function &F, const MachineBasicBlock &MBB,
908     const TargetMachine &TM) const {
909   assert(MBB.isBeginSection() && "Basic block does not start a section!");
910   unsigned UniqueID = MCContext::GenericSectionID;
911 
912   // For cold sections use the .text.split. prefix along with the parent
913   // function name. All cold blocks for the same function go to the same
914   // section. Similarly all exception blocks are grouped by symbol name
915   // under the .text.eh prefix. For regular sections, we either use a unique
916   // name, or a unique ID for the section.
917   SmallString<128> Name;
918   if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
919     Name += BBSectionsColdTextPrefix;
920     Name += MBB.getParent()->getName();
921   } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
922     Name += ".text.eh.";
923     Name += MBB.getParent()->getName();
924   } else {
925     Name += MBB.getParent()->getSection()->getName();
926     if (TM.getUniqueBasicBlockSectionNames()) {
927       Name += ".";
928       Name += MBB.getSymbol()->getName();
929     } else {
930       UniqueID = NextUniqueID++;
931     }
932   }
933 
934   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
935   std::string GroupName = "";
936   if (F.hasComdat()) {
937     Flags |= ELF::SHF_GROUP;
938     GroupName = F.getComdat()->getName().str();
939   }
940   return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
941                                     0 /* Entry Size */, GroupName, UniqueID,
942                                     nullptr);
943 }
944 
945 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
946                                               bool IsCtor, unsigned Priority,
947                                               const MCSymbol *KeySym) {
948   std::string Name;
949   unsigned Type;
950   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
951   StringRef COMDAT = KeySym ? KeySym->getName() : "";
952 
953   if (KeySym)
954     Flags |= ELF::SHF_GROUP;
955 
956   if (UseInitArray) {
957     if (IsCtor) {
958       Type = ELF::SHT_INIT_ARRAY;
959       Name = ".init_array";
960     } else {
961       Type = ELF::SHT_FINI_ARRAY;
962       Name = ".fini_array";
963     }
964     if (Priority != 65535) {
965       Name += '.';
966       Name += utostr(Priority);
967     }
968   } else {
969     // The default scheme is .ctor / .dtor, so we have to invert the priority
970     // numbering.
971     if (IsCtor)
972       Name = ".ctors";
973     else
974       Name = ".dtors";
975     if (Priority != 65535)
976       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
977     Type = ELF::SHT_PROGBITS;
978   }
979 
980   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
981 }
982 
983 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
984     unsigned Priority, const MCSymbol *KeySym) const {
985   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
986                                   KeySym);
987 }
988 
989 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
990     unsigned Priority, const MCSymbol *KeySym) const {
991   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
992                                   KeySym);
993 }
994 
995 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
996     const GlobalValue *LHS, const GlobalValue *RHS,
997     const TargetMachine &TM) const {
998   // We may only use a PLT-relative relocation to refer to unnamed_addr
999   // functions.
1000   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1001     return nullptr;
1002 
1003   // Basic sanity checks.
1004   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1005       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1006       RHS->isThreadLocal())
1007     return nullptr;
1008 
1009   return MCBinaryExpr::createSub(
1010       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
1011                               getContext()),
1012       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1013 }
1014 
1015 const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
1016     const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1017   assert(supportDSOLocalEquivalentLowering());
1018 
1019   const auto *GV = Equiv->getGlobalValue();
1020 
1021   // A PLT entry is not needed for dso_local globals.
1022   if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1023     return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
1024 
1025   return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
1026                                  getContext());
1027 }
1028 
1029 MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
1030   // Use ".GCC.command.line" since this feature is to support clang's
1031   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1032   // same name.
1033   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1034                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
1035 }
1036 
1037 void
1038 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
1039   UseInitArray = UseInitArray_;
1040   MCContext &Ctx = getContext();
1041   if (!UseInitArray) {
1042     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1043                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1044 
1045     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1046                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1047     return;
1048   }
1049 
1050   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1051                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1052   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1053                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1054 }
1055 
1056 //===----------------------------------------------------------------------===//
1057 //                                 MachO
1058 //===----------------------------------------------------------------------===//
1059 
1060 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
1061   : TargetLoweringObjectFile() {
1062   SupportIndirectSymViaGOTPCRel = true;
1063 }
1064 
1065 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
1066                                                const TargetMachine &TM) {
1067   TargetLoweringObjectFile::Initialize(Ctx, TM);
1068   if (TM.getRelocationModel() == Reloc::Static) {
1069     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1070                                             SectionKind::getData());
1071     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1072                                             SectionKind::getData());
1073   } else {
1074     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1075                                             MachO::S_MOD_INIT_FUNC_POINTERS,
1076                                             SectionKind::getData());
1077     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1078                                             MachO::S_MOD_TERM_FUNC_POINTERS,
1079                                             SectionKind::getData());
1080   }
1081 
1082   PersonalityEncoding =
1083       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1084   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
1085   TTypeEncoding =
1086       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1087 }
1088 
1089 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
1090                                                        Module &M) const {
1091   // Emit the linker options if present.
1092   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1093     for (const auto *Option : LinkerOptions->operands()) {
1094       SmallVector<std::string, 4> StrOptions;
1095       for (const auto &Piece : cast<MDNode>(Option)->operands())
1096         StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1097       Streamer.emitLinkerOptions(StrOptions);
1098     }
1099   }
1100 
1101   unsigned VersionVal = 0;
1102   unsigned ImageInfoFlags = 0;
1103   StringRef SectionVal;
1104 
1105   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1106 
1107   // The section is mandatory. If we don't have it, then we don't have GC info.
1108   if (SectionVal.empty())
1109     return;
1110 
1111   StringRef Segment, Section;
1112   unsigned TAA = 0, StubSize = 0;
1113   bool TAAParsed;
1114   std::string ErrorCode =
1115     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
1116                                           TAA, TAAParsed, StubSize);
1117   if (!ErrorCode.empty())
1118     // If invalid, report the error with report_fatal_error.
1119     report_fatal_error("Invalid section specifier '" + Section + "': " +
1120                        ErrorCode + ".");
1121 
1122   // Get the section.
1123   MCSectionMachO *S = getContext().getMachOSection(
1124       Segment, Section, TAA, StubSize, SectionKind::getData());
1125   Streamer.SwitchSection(S);
1126   Streamer.emitLabel(getContext().
1127                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1128   Streamer.emitInt32(VersionVal);
1129   Streamer.emitInt32(ImageInfoFlags);
1130   Streamer.AddBlankLine();
1131 }
1132 
1133 static void checkMachOComdat(const GlobalValue *GV) {
1134   const Comdat *C = GV->getComdat();
1135   if (!C)
1136     return;
1137 
1138   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1139                      "' cannot be lowered.");
1140 }
1141 
1142 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
1143     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1144   // Parse the section specifier and create it if valid.
1145   StringRef Segment, Section;
1146   unsigned TAA = 0, StubSize = 0;
1147   bool TAAParsed;
1148 
1149   checkMachOComdat(GO);
1150 
1151   std::string ErrorCode =
1152     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
1153                                           TAA, TAAParsed, StubSize);
1154   if (!ErrorCode.empty()) {
1155     // If invalid, report the error with report_fatal_error.
1156     report_fatal_error("Global variable '" + GO->getName() +
1157                        "' has an invalid section specifier '" +
1158                        GO->getSection() + "': " + ErrorCode + ".");
1159   }
1160 
1161   // Get the section.
1162   MCSectionMachO *S =
1163       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1164 
1165   // If TAA wasn't set by ParseSectionSpecifier() above,
1166   // use the value returned by getMachOSection() as a default.
1167   if (!TAAParsed)
1168     TAA = S->getTypeAndAttributes();
1169 
1170   // Okay, now that we got the section, verify that the TAA & StubSize agree.
1171   // If the user declared multiple globals with different section flags, we need
1172   // to reject it here.
1173   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1174     // If invalid, report the error with report_fatal_error.
1175     report_fatal_error("Global variable '" + GO->getName() +
1176                        "' section type or attributes does not match previous"
1177                        " section specifier");
1178   }
1179 
1180   return S;
1181 }
1182 
1183 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
1184     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1185   checkMachOComdat(GO);
1186 
1187   // Handle thread local data.
1188   if (Kind.isThreadBSS()) return TLSBSSSection;
1189   if (Kind.isThreadData()) return TLSDataSection;
1190 
1191   if (Kind.isText())
1192     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
1193 
1194   // If this is weak/linkonce, put this in a coalescable section, either in text
1195   // or data depending on if it is writable.
1196   if (GO->isWeakForLinker()) {
1197     if (Kind.isReadOnly())
1198       return ConstTextCoalSection;
1199     if (Kind.isReadOnlyWithRel())
1200       return ConstDataCoalSection;
1201     return DataCoalSection;
1202   }
1203 
1204   // FIXME: Alignment check should be handled by section classifier.
1205   if (Kind.isMergeable1ByteCString() &&
1206       GO->getParent()->getDataLayout().getPreferredAlign(
1207           cast<GlobalVariable>(GO)) < Align(32))
1208     return CStringSection;
1209 
1210   // Do not put 16-bit arrays in the UString section if they have an
1211   // externally visible label, this runs into issues with certain linker
1212   // versions.
1213   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1214       GO->getParent()->getDataLayout().getPreferredAlign(
1215           cast<GlobalVariable>(GO)) < Align(32))
1216     return UStringSection;
1217 
1218   // With MachO only variables whose corresponding symbol starts with 'l' or
1219   // 'L' can be merged, so we only try merging GVs with private linkage.
1220   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1221     if (Kind.isMergeableConst4())
1222       return FourByteConstantSection;
1223     if (Kind.isMergeableConst8())
1224       return EightByteConstantSection;
1225     if (Kind.isMergeableConst16())
1226       return SixteenByteConstantSection;
1227   }
1228 
1229   // Otherwise, if it is readonly, but not something we can specially optimize,
1230   // just drop it in .const.
1231   if (Kind.isReadOnly())
1232     return ReadOnlySection;
1233 
1234   // If this is marked const, put it into a const section.  But if the dynamic
1235   // linker needs to write to it, put it in the data segment.
1236   if (Kind.isReadOnlyWithRel())
1237     return ConstDataSection;
1238 
1239   // Put zero initialized globals with strong external linkage in the
1240   // DATA, __common section with the .zerofill directive.
1241   if (Kind.isBSSExtern())
1242     return DataCommonSection;
1243 
1244   // Put zero initialized globals with local linkage in __DATA,__bss directive
1245   // with the .zerofill directive (aka .lcomm).
1246   if (Kind.isBSSLocal())
1247     return DataBSSSection;
1248 
1249   // Otherwise, just drop the variable in the normal data section.
1250   return DataSection;
1251 }
1252 
1253 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1254     const DataLayout &DL, SectionKind Kind, const Constant *C,
1255     Align &Alignment) const {
1256   // If this constant requires a relocation, we have to put it in the data
1257   // segment, not in the text segment.
1258   if (Kind.isData() || Kind.isReadOnlyWithRel())
1259     return ConstDataSection;
1260 
1261   if (Kind.isMergeableConst4())
1262     return FourByteConstantSection;
1263   if (Kind.isMergeableConst8())
1264     return EightByteConstantSection;
1265   if (Kind.isMergeableConst16())
1266     return SixteenByteConstantSection;
1267   return ReadOnlySection;  // .const
1268 }
1269 
1270 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1271     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1272     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1273   // The mach-o version of this method defaults to returning a stub reference.
1274 
1275   if (Encoding & DW_EH_PE_indirect) {
1276     MachineModuleInfoMachO &MachOMMI =
1277       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1278 
1279     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1280 
1281     // Add information about the stub reference to MachOMMI so that the stub
1282     // gets emitted by the asmprinter.
1283     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1284     if (!StubSym.getPointer()) {
1285       MCSymbol *Sym = TM.getSymbol(GV);
1286       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1287     }
1288 
1289     return TargetLoweringObjectFile::
1290       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1291                         Encoding & ~DW_EH_PE_indirect, Streamer);
1292   }
1293 
1294   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1295                                                            MMI, Streamer);
1296 }
1297 
1298 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1299     const GlobalValue *GV, const TargetMachine &TM,
1300     MachineModuleInfo *MMI) const {
1301   // The mach-o version of this method defaults to returning a stub reference.
1302   MachineModuleInfoMachO &MachOMMI =
1303     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1304 
1305   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1306 
1307   // Add information about the stub reference to MachOMMI so that the stub
1308   // gets emitted by the asmprinter.
1309   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1310   if (!StubSym.getPointer()) {
1311     MCSymbol *Sym = TM.getSymbol(GV);
1312     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1313   }
1314 
1315   return SSym;
1316 }
1317 
1318 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1319     const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1320     int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1321   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1322   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1323   // through a non_lazy_ptr stub instead. One advantage is that it allows the
1324   // computation of deltas to final external symbols. Example:
1325   //
1326   //    _extgotequiv:
1327   //       .long   _extfoo
1328   //
1329   //    _delta:
1330   //       .long   _extgotequiv-_delta
1331   //
1332   // is transformed to:
1333   //
1334   //    _delta:
1335   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1336   //
1337   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1338   //    L_extfoo$non_lazy_ptr:
1339   //       .indirect_symbol        _extfoo
1340   //       .long   0
1341   //
1342   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1343   // may point to both local (same translation unit) and global (other
1344   // translation units) symbols. Example:
1345   //
1346   // .section __DATA,__pointers,non_lazy_symbol_pointers
1347   // L1:
1348   //    .indirect_symbol _myGlobal
1349   //    .long 0
1350   // L2:
1351   //    .indirect_symbol _myLocal
1352   //    .long _myLocal
1353   //
1354   // If the symbol is local, instead of the symbol's index, the assembler
1355   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1356   // Then the linker will notice the constant in the table and will look at the
1357   // content of the symbol.
1358   MachineModuleInfoMachO &MachOMMI =
1359     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1360   MCContext &Ctx = getContext();
1361 
1362   // The offset must consider the original displacement from the base symbol
1363   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1364   Offset = -MV.getConstant();
1365   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1366 
1367   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1368   // non_lazy_ptr stubs.
1369   SmallString<128> Name;
1370   StringRef Suffix = "$non_lazy_ptr";
1371   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1372   Name += Sym->getName();
1373   Name += Suffix;
1374   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1375 
1376   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1377 
1378   if (!StubSym.getPointer())
1379     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1380                                                  !GV->hasLocalLinkage());
1381 
1382   const MCExpr *BSymExpr =
1383     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1384   const MCExpr *LHS =
1385     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1386 
1387   if (!Offset)
1388     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1389 
1390   const MCExpr *RHS =
1391     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1392   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1393 }
1394 
1395 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1396                                const MCSection &Section) {
1397   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1398     return true;
1399 
1400   // If it is not dead stripped, it is safe to use private labels.
1401   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1402   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
1403     return true;
1404 
1405   return false;
1406 }
1407 
1408 void TargetLoweringObjectFileMachO::getNameWithPrefix(
1409     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1410     const TargetMachine &TM) const {
1411   bool CannotUsePrivateLabel = true;
1412   if (auto *GO = GV->getBaseObject()) {
1413     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1414     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1415     CannotUsePrivateLabel =
1416         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1417   }
1418   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1419 }
1420 
1421 //===----------------------------------------------------------------------===//
1422 //                                  COFF
1423 //===----------------------------------------------------------------------===//
1424 
1425 static unsigned
1426 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1427   unsigned Flags = 0;
1428   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1429 
1430   if (K.isMetadata())
1431     Flags |=
1432       COFF::IMAGE_SCN_MEM_DISCARDABLE;
1433   else if (K.isText())
1434     Flags |=
1435       COFF::IMAGE_SCN_MEM_EXECUTE |
1436       COFF::IMAGE_SCN_MEM_READ |
1437       COFF::IMAGE_SCN_CNT_CODE |
1438       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1439   else if (K.isBSS())
1440     Flags |=
1441       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1442       COFF::IMAGE_SCN_MEM_READ |
1443       COFF::IMAGE_SCN_MEM_WRITE;
1444   else if (K.isThreadLocal())
1445     Flags |=
1446       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1447       COFF::IMAGE_SCN_MEM_READ |
1448       COFF::IMAGE_SCN_MEM_WRITE;
1449   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1450     Flags |=
1451       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1452       COFF::IMAGE_SCN_MEM_READ;
1453   else if (K.isWriteable())
1454     Flags |=
1455       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1456       COFF::IMAGE_SCN_MEM_READ |
1457       COFF::IMAGE_SCN_MEM_WRITE;
1458 
1459   return Flags;
1460 }
1461 
1462 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1463   const Comdat *C = GV->getComdat();
1464   assert(C && "expected GV to have a Comdat!");
1465 
1466   StringRef ComdatGVName = C->getName();
1467   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1468   if (!ComdatGV)
1469     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1470                        "' does not exist.");
1471 
1472   if (ComdatGV->getComdat() != C)
1473     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1474                        "' is not a key for its COMDAT.");
1475 
1476   return ComdatGV;
1477 }
1478 
1479 static int getSelectionForCOFF(const GlobalValue *GV) {
1480   if (const Comdat *C = GV->getComdat()) {
1481     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1482     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1483       ComdatKey = GA->getBaseObject();
1484     if (ComdatKey == GV) {
1485       switch (C->getSelectionKind()) {
1486       case Comdat::Any:
1487         return COFF::IMAGE_COMDAT_SELECT_ANY;
1488       case Comdat::ExactMatch:
1489         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1490       case Comdat::Largest:
1491         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1492       case Comdat::NoDuplicates:
1493         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1494       case Comdat::SameSize:
1495         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1496       }
1497     } else {
1498       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1499     }
1500   }
1501   return 0;
1502 }
1503 
1504 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1505     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1506   int Selection = 0;
1507   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1508   StringRef Name = GO->getSection();
1509   StringRef COMDATSymName = "";
1510   if (GO->hasComdat()) {
1511     Selection = getSelectionForCOFF(GO);
1512     const GlobalValue *ComdatGV;
1513     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1514       ComdatGV = getComdatGVForCOFF(GO);
1515     else
1516       ComdatGV = GO;
1517 
1518     if (!ComdatGV->hasPrivateLinkage()) {
1519       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1520       COMDATSymName = Sym->getName();
1521       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1522     } else {
1523       Selection = 0;
1524     }
1525   }
1526 
1527   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1528                                      Selection);
1529 }
1530 
1531 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1532   if (Kind.isText())
1533     return ".text";
1534   if (Kind.isBSS())
1535     return ".bss";
1536   if (Kind.isThreadLocal())
1537     return ".tls$";
1538   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1539     return ".rdata";
1540   return ".data";
1541 }
1542 
1543 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1544     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1545   // If we have -ffunction-sections then we should emit the global value to a
1546   // uniqued section specifically for it.
1547   bool EmitUniquedSection;
1548   if (Kind.isText())
1549     EmitUniquedSection = TM.getFunctionSections();
1550   else
1551     EmitUniquedSection = TM.getDataSections();
1552 
1553   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1554     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1555 
1556     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1557 
1558     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1559     int Selection = getSelectionForCOFF(GO);
1560     if (!Selection)
1561       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1562     const GlobalValue *ComdatGV;
1563     if (GO->hasComdat())
1564       ComdatGV = getComdatGVForCOFF(GO);
1565     else
1566       ComdatGV = GO;
1567 
1568     unsigned UniqueID = MCContext::GenericSectionID;
1569     if (EmitUniquedSection)
1570       UniqueID = NextUniqueID++;
1571 
1572     if (!ComdatGV->hasPrivateLinkage()) {
1573       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1574       StringRef COMDATSymName = Sym->getName();
1575 
1576       // Append "$symbol" to the section name *before* IR-level mangling is
1577       // applied when targetting mingw. This is what GCC does, and the ld.bfd
1578       // COFF linker will not properly handle comdats otherwise.
1579       if (getTargetTriple().isWindowsGNUEnvironment())
1580         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1581 
1582       return getContext().getCOFFSection(Name, Characteristics, Kind,
1583                                          COMDATSymName, Selection, UniqueID);
1584     } else {
1585       SmallString<256> TmpData;
1586       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1587       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1588                                          Selection, UniqueID);
1589     }
1590   }
1591 
1592   if (Kind.isText())
1593     return TextSection;
1594 
1595   if (Kind.isThreadLocal())
1596     return TLSDataSection;
1597 
1598   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1599     return ReadOnlySection;
1600 
1601   // Note: we claim that common symbols are put in BSSSection, but they are
1602   // really emitted with the magic .comm directive, which creates a symbol table
1603   // entry but not a section.
1604   if (Kind.isBSS() || Kind.isCommon())
1605     return BSSSection;
1606 
1607   return DataSection;
1608 }
1609 
1610 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1611     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1612     const TargetMachine &TM) const {
1613   bool CannotUsePrivateLabel = false;
1614   if (GV->hasPrivateLinkage() &&
1615       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1616        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1617     CannotUsePrivateLabel = true;
1618 
1619   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1620 }
1621 
1622 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1623     const Function &F, const TargetMachine &TM) const {
1624   // If the function can be removed, produce a unique section so that
1625   // the table doesn't prevent the removal.
1626   const Comdat *C = F.getComdat();
1627   bool EmitUniqueSection = TM.getFunctionSections() || C;
1628   if (!EmitUniqueSection)
1629     return ReadOnlySection;
1630 
1631   // FIXME: we should produce a symbol for F instead.
1632   if (F.hasPrivateLinkage())
1633     return ReadOnlySection;
1634 
1635   MCSymbol *Sym = TM.getSymbol(&F);
1636   StringRef COMDATSymName = Sym->getName();
1637 
1638   SectionKind Kind = SectionKind::getReadOnly();
1639   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1640   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1641   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1642   unsigned UniqueID = NextUniqueID++;
1643 
1644   return getContext().getCOFFSection(
1645       SecName, Characteristics, Kind, COMDATSymName,
1646       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1647 }
1648 
1649 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1650                                                       Module &M) const {
1651   emitLinkerDirectives(Streamer, M);
1652 
1653   unsigned Version = 0;
1654   unsigned Flags = 0;
1655   StringRef Section;
1656 
1657   GetObjCImageInfo(M, Version, Flags, Section);
1658   if (!Section.empty()) {
1659     auto &C = getContext();
1660     auto *S = C.getCOFFSection(Section,
1661                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1662                                    COFF::IMAGE_SCN_MEM_READ,
1663                                SectionKind::getReadOnly());
1664     Streamer.SwitchSection(S);
1665     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1666     Streamer.emitInt32(Version);
1667     Streamer.emitInt32(Flags);
1668     Streamer.AddBlankLine();
1669   }
1670 
1671   auto &C = getContext();
1672   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1673   M.getModuleFlagsMetadata(ModuleFlags);
1674 
1675   MDNode *CFGProfile = nullptr;
1676 
1677   for (const auto &MFE : ModuleFlags) {
1678     StringRef Key = MFE.Key->getString();
1679     if (Key == "CG Profile") {
1680       CFGProfile = cast<MDNode>(MFE.Val);
1681       break;
1682     }
1683   }
1684 
1685   if (!CFGProfile)
1686     return;
1687 
1688   auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
1689     if (!MDO)
1690       return nullptr;
1691     auto V = cast<ValueAsMetadata>(MDO);
1692     const Function *F = cast<Function>(V->getValue());
1693     if (F->hasDLLImportStorageClass())
1694       return nullptr;
1695     return TM->getSymbol(F);
1696   };
1697 
1698   for (const auto &Edge : CFGProfile->operands()) {
1699     MDNode *E = cast<MDNode>(Edge);
1700     const MCSymbol *From = GetSym(E->getOperand(0));
1701     const MCSymbol *To = GetSym(E->getOperand(1));
1702     // Skip null functions. This can happen if functions are dead stripped after
1703     // the CGProfile pass has been run.
1704     if (!From || !To)
1705       continue;
1706     uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
1707                          ->getValue()
1708                          ->getUniqueInteger()
1709                          .getZExtValue();
1710     Streamer.emitCGProfileEntry(
1711         MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
1712         MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
1713   }
1714 }
1715 
1716 void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1717     MCStreamer &Streamer, Module &M) const {
1718   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1719     // Emit the linker options to the linker .drectve section.  According to the
1720     // spec, this section is a space-separated string containing flags for
1721     // linker.
1722     MCSection *Sec = getDrectveSection();
1723     Streamer.SwitchSection(Sec);
1724     for (const auto *Option : LinkerOptions->operands()) {
1725       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1726         // Lead with a space for consistency with our dllexport implementation.
1727         std::string Directive(" ");
1728         Directive.append(std::string(cast<MDString>(Piece)->getString()));
1729         Streamer.emitBytes(Directive);
1730       }
1731     }
1732   }
1733 
1734   // Emit /EXPORT: flags for each exported global as necessary.
1735   std::string Flags;
1736   for (const GlobalValue &GV : M.global_values()) {
1737     raw_string_ostream OS(Flags);
1738     emitLinkerFlagsForGlobalCOFF(OS, &GV, getTargetTriple(), getMangler());
1739     OS.flush();
1740     if (!Flags.empty()) {
1741       Streamer.SwitchSection(getDrectveSection());
1742       Streamer.emitBytes(Flags);
1743     }
1744     Flags.clear();
1745   }
1746 
1747   // Emit /INCLUDE: flags for each used global as necessary.
1748   if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1749     assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1750     assert(isa<ArrayType>(LU->getValueType()) &&
1751            "expected llvm.used to be an array type");
1752     if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1753       for (const Value *Op : A->operands()) {
1754         const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1755         // Global symbols with internal or private linkage are not visible to
1756         // the linker, and thus would cause an error when the linker tried to
1757         // preserve the symbol due to the `/include:` directive.
1758         if (GV->hasLocalLinkage())
1759           continue;
1760 
1761         raw_string_ostream OS(Flags);
1762         emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1763         OS.flush();
1764 
1765         if (!Flags.empty()) {
1766           Streamer.SwitchSection(getDrectveSection());
1767           Streamer.emitBytes(Flags);
1768         }
1769         Flags.clear();
1770       }
1771     }
1772   }
1773 }
1774 
1775 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1776                                               const TargetMachine &TM) {
1777   TargetLoweringObjectFile::Initialize(Ctx, TM);
1778   this->TM = &TM;
1779   const Triple &T = TM.getTargetTriple();
1780   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1781     StaticCtorSection =
1782         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1783                                            COFF::IMAGE_SCN_MEM_READ,
1784                            SectionKind::getReadOnly());
1785     StaticDtorSection =
1786         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1787                                            COFF::IMAGE_SCN_MEM_READ,
1788                            SectionKind::getReadOnly());
1789   } else {
1790     StaticCtorSection = Ctx.getCOFFSection(
1791         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1792                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1793         SectionKind::getData());
1794     StaticDtorSection = Ctx.getCOFFSection(
1795         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1796                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1797         SectionKind::getData());
1798   }
1799 }
1800 
1801 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1802                                                    const Triple &T, bool IsCtor,
1803                                                    unsigned Priority,
1804                                                    const MCSymbol *KeySym,
1805                                                    MCSectionCOFF *Default) {
1806   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1807     // If the priority is the default, use .CRT$XCU, possibly associative.
1808     if (Priority == 65535)
1809       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1810 
1811     // Otherwise, we need to compute a new section name. Low priorities should
1812     // run earlier. The linker will sort sections ASCII-betically, and we need a
1813     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1814     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1815     // low priorities need to sort before 'L', since the CRT uses that
1816     // internally, so we use ".CRT$XCA00001" for them.
1817     SmallString<24> Name;
1818     raw_svector_ostream OS(Name);
1819     OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
1820         (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1821     MCSectionCOFF *Sec = Ctx.getCOFFSection(
1822         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1823         SectionKind::getReadOnly());
1824     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1825   }
1826 
1827   std::string Name = IsCtor ? ".ctors" : ".dtors";
1828   if (Priority != 65535)
1829     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1830 
1831   return Ctx.getAssociativeCOFFSection(
1832       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1833                                    COFF::IMAGE_SCN_MEM_READ |
1834                                    COFF::IMAGE_SCN_MEM_WRITE,
1835                          SectionKind::getData()),
1836       KeySym, 0);
1837 }
1838 
1839 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1840     unsigned Priority, const MCSymbol *KeySym) const {
1841   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1842                                       Priority, KeySym,
1843                                       cast<MCSectionCOFF>(StaticCtorSection));
1844 }
1845 
1846 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1847     unsigned Priority, const MCSymbol *KeySym) const {
1848   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1849                                       Priority, KeySym,
1850                                       cast<MCSectionCOFF>(StaticDtorSection));
1851 }
1852 
1853 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1854     const GlobalValue *LHS, const GlobalValue *RHS,
1855     const TargetMachine &TM) const {
1856   const Triple &T = TM.getTargetTriple();
1857   if (T.isOSCygMing())
1858     return nullptr;
1859 
1860   // Our symbols should exist in address space zero, cowardly no-op if
1861   // otherwise.
1862   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1863       RHS->getType()->getPointerAddressSpace() != 0)
1864     return nullptr;
1865 
1866   // Both ptrtoint instructions must wrap global objects:
1867   // - Only global variables are eligible for image relative relocations.
1868   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1869   // We expect __ImageBase to be a global variable without a section, externally
1870   // defined.
1871   //
1872   // It should look something like this: @__ImageBase = external constant i8
1873   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1874       LHS->isThreadLocal() || RHS->isThreadLocal() ||
1875       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1876       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1877     return nullptr;
1878 
1879   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1880                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
1881                                  getContext());
1882 }
1883 
1884 static std::string APIntToHexString(const APInt &AI) {
1885   unsigned Width = (AI.getBitWidth() / 8) * 2;
1886   std::string HexString = AI.toString(16, /*Signed=*/false);
1887   llvm::transform(HexString, HexString.begin(), tolower);
1888   unsigned Size = HexString.size();
1889   assert(Width >= Size && "hex string is too large!");
1890   HexString.insert(HexString.begin(), Width - Size, '0');
1891 
1892   return HexString;
1893 }
1894 
1895 static std::string scalarConstantToHexString(const Constant *C) {
1896   Type *Ty = C->getType();
1897   if (isa<UndefValue>(C)) {
1898     return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1899   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1900     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1901   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1902     return APIntToHexString(CI->getValue());
1903   } else {
1904     unsigned NumElements;
1905     if (auto *VTy = dyn_cast<VectorType>(Ty))
1906       NumElements = cast<FixedVectorType>(VTy)->getNumElements();
1907     else
1908       NumElements = Ty->getArrayNumElements();
1909     std::string HexString;
1910     for (int I = NumElements - 1, E = -1; I != E; --I)
1911       HexString += scalarConstantToHexString(C->getAggregateElement(I));
1912     return HexString;
1913   }
1914 }
1915 
1916 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1917     const DataLayout &DL, SectionKind Kind, const Constant *C,
1918     Align &Alignment) const {
1919   if (Kind.isMergeableConst() && C &&
1920       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1921     // This creates comdat sections with the given symbol name, but unless
1922     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1923     // will be created with a null storage class, which makes GNU binutils
1924     // error out.
1925     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1926                                      COFF::IMAGE_SCN_MEM_READ |
1927                                      COFF::IMAGE_SCN_LNK_COMDAT;
1928     std::string COMDATSymName;
1929     if (Kind.isMergeableConst4()) {
1930       if (Alignment <= 4) {
1931         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1932         Alignment = Align(4);
1933       }
1934     } else if (Kind.isMergeableConst8()) {
1935       if (Alignment <= 8) {
1936         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1937         Alignment = Align(8);
1938       }
1939     } else if (Kind.isMergeableConst16()) {
1940       // FIXME: These may not be appropriate for non-x86 architectures.
1941       if (Alignment <= 16) {
1942         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1943         Alignment = Align(16);
1944       }
1945     } else if (Kind.isMergeableConst32()) {
1946       if (Alignment <= 32) {
1947         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1948         Alignment = Align(32);
1949       }
1950     }
1951 
1952     if (!COMDATSymName.empty())
1953       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1954                                          COMDATSymName,
1955                                          COFF::IMAGE_COMDAT_SELECT_ANY);
1956   }
1957 
1958   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
1959                                                          Alignment);
1960 }
1961 
1962 //===----------------------------------------------------------------------===//
1963 //                                  Wasm
1964 //===----------------------------------------------------------------------===//
1965 
1966 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1967   const Comdat *C = GV->getComdat();
1968   if (!C)
1969     return nullptr;
1970 
1971   if (C->getSelectionKind() != Comdat::Any)
1972     report_fatal_error("WebAssembly COMDATs only support "
1973                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
1974                        "lowered.");
1975 
1976   return C;
1977 }
1978 
1979 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1980     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1981   // We don't support explict section names for functions in the wasm object
1982   // format.  Each function has to be in its own unique section.
1983   if (isa<Function>(GO)) {
1984     return SelectSectionForGlobal(GO, Kind, TM);
1985   }
1986 
1987   StringRef Name = GO->getSection();
1988 
1989   // Certain data sections we treat as named custom sections rather than
1990   // segments within the data section.
1991   // This could be avoided if all data segements (the wasm sense) were
1992   // represented as their own sections (in the llvm sense).
1993   // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
1994   if (Name == ".llvmcmd" || Name == ".llvmbc")
1995     Kind = SectionKind::getMetadata();
1996 
1997   StringRef Group = "";
1998   if (const Comdat *C = getWasmComdat(GO)) {
1999     Group = C->getName();
2000   }
2001 
2002   MCSectionWasm* Section =
2003       getContext().getWasmSection(Name, Kind, Group,
2004                                   MCContext::GenericSectionID);
2005 
2006   return Section;
2007 }
2008 
2009 static MCSectionWasm *selectWasmSectionForGlobal(
2010     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
2011     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
2012   StringRef Group = "";
2013   if (const Comdat *C = getWasmComdat(GO)) {
2014     Group = C->getName();
2015   }
2016 
2017   bool UniqueSectionNames = TM.getUniqueSectionNames();
2018   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
2019 
2020   if (const auto *F = dyn_cast<Function>(GO)) {
2021     const auto &OptionalPrefix = F->getSectionPrefix();
2022     if (OptionalPrefix)
2023       Name += *OptionalPrefix;
2024   }
2025 
2026   if (EmitUniqueSection && UniqueSectionNames) {
2027     Name.push_back('.');
2028     TM.getNameWithPrefix(Name, GO, Mang, true);
2029   }
2030   unsigned UniqueID = MCContext::GenericSectionID;
2031   if (EmitUniqueSection && !UniqueSectionNames) {
2032     UniqueID = *NextUniqueID;
2033     (*NextUniqueID)++;
2034   }
2035 
2036   return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
2037 }
2038 
2039 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
2040     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2041 
2042   if (Kind.isCommon())
2043     report_fatal_error("mergable sections not supported yet on wasm");
2044 
2045   // If we have -ffunction-section or -fdata-section then we should emit the
2046   // global value to a uniqued section specifically for it.
2047   bool EmitUniqueSection = false;
2048   if (Kind.isText())
2049     EmitUniqueSection = TM.getFunctionSections();
2050   else
2051     EmitUniqueSection = TM.getDataSections();
2052   EmitUniqueSection |= GO->hasComdat();
2053 
2054   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2055                                     EmitUniqueSection, &NextUniqueID);
2056 }
2057 
2058 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
2059     bool UsesLabelDifference, const Function &F) const {
2060   // We can always create relative relocations, so use another section
2061   // that can be marked non-executable.
2062   return false;
2063 }
2064 
2065 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
2066     const GlobalValue *LHS, const GlobalValue *RHS,
2067     const TargetMachine &TM) const {
2068   // We may only use a PLT-relative relocation to refer to unnamed_addr
2069   // functions.
2070   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2071     return nullptr;
2072 
2073   // Basic sanity checks.
2074   if (LHS->getType()->getPointerAddressSpace() != 0 ||
2075       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2076       RHS->isThreadLocal())
2077     return nullptr;
2078 
2079   return MCBinaryExpr::createSub(
2080       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
2081                               getContext()),
2082       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
2083 }
2084 
2085 void TargetLoweringObjectFileWasm::InitializeWasm() {
2086   StaticCtorSection =
2087       getContext().getWasmSection(".init_array", SectionKind::getData());
2088 
2089   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2090   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2091   TTypeEncoding = dwarf::DW_EH_PE_absptr;
2092 }
2093 
2094 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
2095     unsigned Priority, const MCSymbol *KeySym) const {
2096   return Priority == UINT16_MAX ?
2097          StaticCtorSection :
2098          getContext().getWasmSection(".init_array." + utostr(Priority),
2099                                      SectionKind::getData());
2100 }
2101 
2102 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
2103     unsigned Priority, const MCSymbol *KeySym) const {
2104   llvm_unreachable("@llvm.global_dtors should have been lowered already");
2105   return nullptr;
2106 }
2107 
2108 //===----------------------------------------------------------------------===//
2109 //                                  XCOFF
2110 //===----------------------------------------------------------------------===//
2111 MCSymbol *
2112 TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
2113                                                const TargetMachine &TM) const {
2114   // We always use a qualname symbol for a GV that represents
2115   // a declaration, a function descriptor, or a common symbol.
2116   // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2117   // also return a qualname so that a label symbol could be avoided.
2118   // It is inherently ambiguous when the GO represents the address of a
2119   // function, as the GO could either represent a function descriptor or a
2120   // function entry point. We choose to always return a function descriptor
2121   // here.
2122   if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2123     if (GO->isDeclarationForLinker())
2124       return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
2125           ->getQualNameSymbol();
2126 
2127     SectionKind GOKind = getKindForGlobal(GO, TM);
2128     if (GOKind.isText())
2129       return cast<MCSectionXCOFF>(
2130                  getSectionForFunctionDescriptor(cast<Function>(GO), TM))
2131           ->getQualNameSymbol();
2132     if ((TM.getDataSections() && !GO->hasSection()) || GOKind.isCommon() ||
2133         GOKind.isBSSLocal())
2134       return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
2135           ->getQualNameSymbol();
2136   }
2137 
2138   // For all other cases, fall back to getSymbol to return the unqualified name.
2139   return nullptr;
2140 }
2141 
2142 MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
2143     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2144   if (!GO->hasSection())
2145     report_fatal_error("#pragma clang section is not yet supported");
2146 
2147   StringRef SectionName = GO->getSection();
2148   XCOFF::StorageMappingClass MappingClass;
2149   if (Kind.isText())
2150     MappingClass = XCOFF::XMC_PR;
2151   else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
2152     MappingClass = XCOFF::XMC_RW;
2153   else if (Kind.isReadOnly())
2154     MappingClass = XCOFF::XMC_RO;
2155   else
2156     report_fatal_error("XCOFF other section types not yet implemented.");
2157 
2158   return getContext().getXCOFFSection(SectionName, MappingClass, XCOFF::XTY_SD,
2159                                       Kind, /* MultiSymbolsAllowed*/ true);
2160 }
2161 
2162 MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
2163     const GlobalObject *GO, const TargetMachine &TM) const {
2164   assert(GO->isDeclarationForLinker() &&
2165          "Tried to get ER section for a defined global.");
2166 
2167   SmallString<128> Name;
2168   getNameWithPrefix(Name, GO, TM);
2169 
2170   // Externals go into a csect of type ER.
2171   return getContext().getXCOFFSection(
2172       Name, isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA, XCOFF::XTY_ER,
2173       SectionKind::getMetadata());
2174 }
2175 
2176 MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
2177     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2178   // Common symbols go into a csect with matching name which will get mapped
2179   // into the .bss section.
2180   if (Kind.isBSSLocal() || Kind.isCommon()) {
2181     SmallString<128> Name;
2182     getNameWithPrefix(Name, GO, TM);
2183     return getContext().getXCOFFSection(
2184         Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM,
2185         Kind);
2186   }
2187 
2188   if (Kind.isMergeableCString()) {
2189     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
2190         cast<GlobalVariable>(GO));
2191 
2192     unsigned EntrySize = getEntrySizeForKind(Kind);
2193     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
2194     SmallString<128> Name;
2195     Name = SizeSpec + utostr(Alignment.value());
2196 
2197     if (TM.getDataSections())
2198       getNameWithPrefix(Name, GO, TM);
2199 
2200     return getContext().getXCOFFSection(
2201         Name, XCOFF::XMC_RO, XCOFF::XTY_SD, Kind,
2202         /* MultiSymbolsAllowed*/ !TM.getDataSections());
2203   }
2204 
2205   if (Kind.isText()) {
2206     if (TM.getFunctionSections()) {
2207       return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2208           ->getRepresentedCsect();
2209     }
2210     return TextSection;
2211   }
2212 
2213   // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
2214   // user may want to have read-only data with relocations placed into a
2215   // read-only section by the compiler.
2216   // For BSS kind, zero initialized data must be emitted to the .data section
2217   // because external linkage control sections that get mapped to the .bss
2218   // section will be linked as tentative defintions, which is only appropriate
2219   // for SectionKind::Common.
2220   if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2221     if (TM.getDataSections()) {
2222       SmallString<128> Name;
2223       getNameWithPrefix(Name, GO, TM);
2224       return getContext().getXCOFFSection(Name, XCOFF::XMC_RW, XCOFF::XTY_SD,
2225                                           SectionKind::getData());
2226     }
2227     return DataSection;
2228   }
2229 
2230   if (Kind.isReadOnly()) {
2231     if (TM.getDataSections()) {
2232       SmallString<128> Name;
2233       getNameWithPrefix(Name, GO, TM);
2234       return getContext().getXCOFFSection(Name, XCOFF::XMC_RO, XCOFF::XTY_SD,
2235                                           SectionKind::getReadOnly());
2236     }
2237     return ReadOnlySection;
2238   }
2239 
2240   report_fatal_error("XCOFF other section types not yet implemented.");
2241 }
2242 
2243 MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2244     const Function &F, const TargetMachine &TM) const {
2245   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2246 
2247   if (!TM.getFunctionSections())
2248     return ReadOnlySection;
2249 
2250   // If the function can be removed, produce a unique section so that
2251   // the table doesn't prevent the removal.
2252   SmallString<128> NameStr(".rodata.jmp..");
2253   getNameWithPrefix(NameStr, &F, TM);
2254   return getContext().getXCOFFSection(NameStr, XCOFF::XMC_RO, XCOFF::XTY_SD,
2255                                       SectionKind::getReadOnly());
2256 }
2257 
2258 bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
2259     bool UsesLabelDifference, const Function &F) const {
2260   return false;
2261 }
2262 
2263 /// Given a mergeable constant with the specified size and relocation
2264 /// information, return a section that it should be placed in.
2265 MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
2266     const DataLayout &DL, SectionKind Kind, const Constant *C,
2267     Align &Alignment) const {
2268   //TODO: Enable emiting constant pool to unique sections when we support it.
2269   return ReadOnlySection;
2270 }
2271 
2272 void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
2273                                                const TargetMachine &TgtM) {
2274   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2275   TTypeEncoding = 0;
2276   PersonalityEncoding = 0;
2277   LSDAEncoding = 0;
2278 }
2279 
2280 MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
2281 	unsigned Priority, const MCSymbol *KeySym) const {
2282   report_fatal_error("no static constructor section on AIX");
2283 }
2284 
2285 MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
2286 	unsigned Priority, const MCSymbol *KeySym) const {
2287   report_fatal_error("no static destructor section on AIX");
2288 }
2289 
2290 const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
2291     const GlobalValue *LHS, const GlobalValue *RHS,
2292     const TargetMachine &TM) const {
2293   report_fatal_error("XCOFF not yet implemented.");
2294 }
2295 
2296 XCOFF::StorageClass
2297 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
2298   assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2299 
2300   switch (GV->getLinkage()) {
2301   case GlobalValue::InternalLinkage:
2302   case GlobalValue::PrivateLinkage:
2303     return XCOFF::C_HIDEXT;
2304   case GlobalValue::ExternalLinkage:
2305   case GlobalValue::CommonLinkage:
2306   case GlobalValue::AvailableExternallyLinkage:
2307     return XCOFF::C_EXT;
2308   case GlobalValue::ExternalWeakLinkage:
2309   case GlobalValue::LinkOnceAnyLinkage:
2310   case GlobalValue::LinkOnceODRLinkage:
2311   case GlobalValue::WeakAnyLinkage:
2312   case GlobalValue::WeakODRLinkage:
2313     return XCOFF::C_WEAKEXT;
2314   case GlobalValue::AppendingLinkage:
2315     report_fatal_error(
2316         "There is no mapping that implements AppendingLinkage for XCOFF.");
2317   }
2318   llvm_unreachable("Unknown linkage type!");
2319 }
2320 
2321 MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2322     const GlobalValue *Func, const TargetMachine &TM) const {
2323   assert(
2324       (isa<Function>(Func) ||
2325        (isa<GlobalAlias>(Func) &&
2326         isa_and_nonnull<Function>(cast<GlobalAlias>(Func)->getBaseObject()))) &&
2327       "Func must be a function or an alias which has a function as base "
2328       "object.");
2329 
2330   SmallString<128> NameStr;
2331   NameStr.push_back('.');
2332   getNameWithPrefix(NameStr, Func, TM);
2333 
2334   // When -function-sections is enabled and explicit section is not specified,
2335   // it's not necessary to emit function entry point label any more. We will use
2336   // function entry point csect instead. And for function delcarations, the
2337   // undefined symbols gets treated as csect with XTY_ER property.
2338   if (((TM.getFunctionSections() && !Func->hasSection()) ||
2339        Func->isDeclaration()) &&
2340       isa<Function>(Func)) {
2341     return getContext()
2342         .getXCOFFSection(NameStr, XCOFF::XMC_PR,
2343                          Func->isDeclaration() ? XCOFF::XTY_ER : XCOFF::XTY_SD,
2344                          SectionKind::getText())
2345         ->getQualNameSymbol();
2346   }
2347 
2348   return getContext().getOrCreateSymbol(NameStr);
2349 }
2350 
2351 MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
2352     const Function *F, const TargetMachine &TM) const {
2353   SmallString<128> NameStr;
2354   getNameWithPrefix(NameStr, F, TM);
2355   return getContext().getXCOFFSection(NameStr, XCOFF::XMC_DS, XCOFF::XTY_SD,
2356                                       SectionKind::getData());
2357 }
2358 
2359 MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2360     const MCSymbol *Sym, const TargetMachine &TM) const {
2361   // Use TE storage-mapping class when large code model is enabled so that
2362   // the chance of needing -bbigtoc is decreased.
2363   return getContext().getXCOFFSection(
2364       cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(),
2365       TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
2366       XCOFF::XTY_SD, SectionKind::getData());
2367 }
2368