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