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