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