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