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