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