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