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