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