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