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