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