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