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