LLVM 21.0.0git
TargetLoweringObjectFileImpl.cpp
Go to the documentation of this file.
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
18#include "llvm/ADT/StringRef.h"
30#include "llvm/IR/Comdat.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalAlias.h"
39#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/Mangler.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/PseudoProbe.h"
45#include "llvm/IR/Type.h"
46#include "llvm/MC/MCAsmInfo.h"
48#include "llvm/MC/MCContext.h"
49#include "llvm/MC/MCExpr.h"
56#include "llvm/MC/MCStreamer.h"
57#include "llvm/MC/MCSymbol.h"
58#include "llvm/MC/MCSymbolELF.h"
59#include "llvm/MC/MCValue.h"
60#include "llvm/MC/SectionKind.h"
62#include "llvm/Support/Base64.h"
66#include "llvm/Support/Format.h"
70#include <cassert>
71#include <string>
72
73using namespace llvm;
74using namespace dwarf;
75
77 "jumptable-in-function-section", cl::Hidden, cl::init(false),
78 cl::desc("Putting Jump Table in function section"));
79
80static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
81 StringRef &Section) {
83 M.getModuleFlagsMetadata(ModuleFlags);
84
85 for (const auto &MFE: ModuleFlags) {
86 // Ignore flags with 'Require' behaviour.
87 if (MFE.Behavior == Module::Require)
88 continue;
89
90 StringRef Key = MFE.Key->getString();
91 if (Key == "Objective-C Image Info Version") {
92 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
93 } else if (Key == "Objective-C Garbage Collection" ||
94 Key == "Objective-C GC Only" ||
95 Key == "Objective-C Is Simulated" ||
96 Key == "Objective-C Class Properties" ||
97 Key == "Objective-C Image Swift Version") {
98 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
99 } else if (Key == "Objective-C Image Info Section") {
100 Section = cast<MDString>(MFE.Val)->getString();
101 }
102 // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
103 // "Objective-C Garbage Collection".
104 else if (Key == "Swift ABI Version") {
105 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
106 } else if (Key == "Swift Major Version") {
107 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
108 } else if (Key == "Swift Minor Version") {
109 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
110 }
111 }
112}
113
114//===----------------------------------------------------------------------===//
115// ELF
116//===----------------------------------------------------------------------===//
117
120}
121
123 const TargetMachine &TgtM) {
125
126 CodeModel::Model CM = TgtM.getCodeModel();
128
129 switch (TgtM.getTargetTriple().getArch()) {
130 case Triple::arm:
131 case Triple::armeb:
132 case Triple::thumb:
133 case Triple::thumbeb:
135 break;
136 // Fallthrough if not using EHABI
137 [[fallthrough]];
138 case Triple::ppc:
139 case Triple::ppcle:
140 case Triple::x86:
153 break;
154 case Triple::x86_64:
155 if (isPositionIndependent()) {
157 ((CM == CodeModel::Small || CM == CodeModel::Medium)
160 (CM == CodeModel::Small
163 ((CM == CodeModel::Small || CM == CodeModel::Medium)
165 } else {
167 (CM == CodeModel::Small || CM == CodeModel::Medium)
173 }
174 break;
175 case Triple::hexagon:
179 if (isPositionIndependent()) {
183 }
184 break;
185 case Triple::aarch64:
188 // The small model guarantees static code/data size < 4GB, but not where it
189 // will be in memory. Most of these could end up >2GB away so even a signed
190 // pc-relative 32-bit address is insufficient, theoretically.
191 //
192 // Use DW_EH_PE_indirect even for -fno-pic to avoid copy relocations.
199 break;
200 case Triple::lanai:
204 break;
205 case Triple::mips:
206 case Triple::mipsel:
207 case Triple::mips64:
208 case Triple::mips64el:
209 // MIPS uses indirect pointer to refer personality functions and types, so
210 // that the eh_frame section can be read-only. DW.ref.personality will be
211 // generated for relocation.
213 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
214 // identify N64 from just a triple.
217
218 // FreeBSD must be explicit about the data size and using pcrel since it's
219 // assembler/linker won't do the automatic conversion that the Linux tools
220 // do.
224 }
225 break;
226 case Triple::ppc64:
227 case Triple::ppc64le:
233 break;
234 case Triple::sparcel:
235 case Triple::sparc:
236 if (isPositionIndependent()) {
242 } else {
246 }
248 break;
249 case Triple::riscv32:
250 case Triple::riscv64:
257 break;
258 case Triple::sparcv9:
260 if (isPositionIndependent()) {
265 } else {
268 }
269 break;
270 case Triple::systemz:
271 // All currently-defined code models guarantee that 4-byte PC-relative
272 // values will be in range.
273 if (isPositionIndependent()) {
279 } else {
283 }
284 break;
292 break;
293 default:
294 break;
295 }
296}
297
300 collectUsedGlobalVariables(M, Vec, false);
301 for (GlobalValue *GV : Vec)
302 if (auto *GO = dyn_cast<GlobalObject>(GV))
303 Used.insert(GO);
304}
305
307 Module &M) const {
308 auto &C = getContext();
309
310 emitLinkerDirectives(Streamer, M);
311
312 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
313 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
315
316 Streamer.switchSection(S);
317
318 for (const auto *Operand : DependentLibraries->operands()) {
319 Streamer.emitBytes(
320 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
321 Streamer.emitInt8(0);
322 }
323 }
324
325 if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
326 // Emit a descriptor for every function including functions that have an
327 // available external linkage. We may not want this for imported functions
328 // that has code in another thinLTO module but we don't have a good way to
329 // tell them apart from inline functions defined in header files. Therefore
330 // we put each descriptor in a separate comdat section and rely on the
331 // linker to deduplicate.
332 for (const auto *Operand : FuncInfo->operands()) {
333 const auto *MD = cast<MDNode>(Operand);
334 auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
335 auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
336 auto *Name = cast<MDString>(MD->getOperand(2));
337 auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
338 TM->getFunctionSections() ? Name->getString() : StringRef());
339
340 Streamer.switchSection(S);
341 Streamer.emitInt64(GUID->getZExtValue());
342 Streamer.emitInt64(Hash->getZExtValue());
343 Streamer.emitULEB128IntValue(Name->getString().size());
344 Streamer.emitBytes(Name->getString());
345 }
346 }
347
348 if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
349 // Emit the metadata for llvm statistics into .llvm_stats section, which is
350 // formatted as a list of key/value pair, the value is base64 encoded.
351 auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
352 Streamer.switchSection(S);
353 for (const auto *Operand : LLVMStats->operands()) {
354 const auto *MD = cast<MDNode>(Operand);
355 assert(MD->getNumOperands() % 2 == 0 &&
356 ("Operand num should be even for a list of key/value pair"));
357 for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
358 // Encode the key string size.
359 auto *Key = cast<MDString>(MD->getOperand(I));
360 Streamer.emitULEB128IntValue(Key->getString().size());
361 Streamer.emitBytes(Key->getString());
362 // Encode the value into a Base64 string.
363 std::string Value = encodeBase64(
364 Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
365 ->getZExtValue())
366 .str());
367 Streamer.emitULEB128IntValue(Value.size());
368 Streamer.emitBytes(Value);
369 }
370 }
371 }
372
373 unsigned Version = 0;
374 unsigned Flags = 0;
375 StringRef Section;
376
377 GetObjCImageInfo(M, Version, Flags, Section);
378 if (!Section.empty()) {
379 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
380 Streamer.switchSection(S);
381 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
382 Streamer.emitInt32(Version);
383 Streamer.emitInt32(Flags);
384 Streamer.addBlankLine();
385 }
386
387 emitCGProfileMetadata(Streamer, M);
388}
389
391 Module &M) const {
392 auto &C = getContext();
393 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
394 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
396
397 Streamer.switchSection(S);
398
399 for (const auto *Operand : LinkerOptions->operands()) {
400 if (cast<MDNode>(Operand)->getNumOperands() != 2)
401 report_fatal_error("invalid llvm.linker.options");
402 for (const auto &Option : cast<MDNode>(Operand)->operands()) {
403 Streamer.emitBytes(cast<MDString>(Option)->getString());
404 Streamer.emitInt8(0);
405 }
406 }
407 }
408}
409
411 const GlobalValue *GV, const TargetMachine &TM,
412 MachineModuleInfo *MMI) const {
413 unsigned Encoding = getPersonalityEncoding();
414 if ((Encoding & 0x80) == DW_EH_PE_indirect)
415 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
416 TM.getSymbol(GV)->getName());
417 if ((Encoding & 0x70) == DW_EH_PE_absptr)
418 return TM.getSymbol(GV);
419 report_fatal_error("We do not support this DWARF encoding yet!");
420}
421
423 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
424 const MachineModuleInfo *MMI) const {
425 SmallString<64> NameData("DW.ref.");
426 NameData += Sym->getName();
427 MCSymbolELF *Label =
428 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
429 Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
430 Streamer.emitSymbolAttribute(Label, MCSA_Weak);
431 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
432 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
433 ELF::SHT_PROGBITS, Flags, 0);
434 unsigned Size = DL.getPointerSize();
435 Streamer.switchSection(Sec);
436 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
439 Streamer.emitELFSize(Label, E);
440 Streamer.emitLabel(Label);
441
442 emitPersonalityValueImpl(Streamer, DL, Sym, MMI);
443}
444
446 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
447 const MachineModuleInfo *MMI) const {
448 Streamer.emitSymbolValue(Sym, DL.getPointerSize());
449}
450
452 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
453 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
454 if (Encoding & DW_EH_PE_indirect) {
456
457 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
458
459 // Add information about the stub reference to ELFMMI so that the stub
460 // gets emitted by the asmprinter.
462 if (!StubSym.getPointer()) {
463 MCSymbol *Sym = TM.getSymbol(GV);
465 }
466
469 Encoding & ~DW_EH_PE_indirect, Streamer);
470 }
471
473 MMI, Streamer);
474}
475
477 // N.B.: The defaults used in here are not the same ones used in MC.
478 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
479 // both gas and MC will produce a section with no flags. Given
480 // section(".eh_frame") gcc will produce:
481 //
482 // .section .eh_frame,"a",@progbits
483
484 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
485 /*AddSegmentInfo=*/false) ||
487 /*AddSegmentInfo=*/false) ||
489 /*AddSegmentInfo=*/false) ||
491 /*AddSegmentInfo=*/false) ||
492 Name == ".llvmbc" || Name == ".llvmcmd")
494
495 if (!Name.starts_with(".")) return K;
496
497 // Default implementation based on some magic section names.
498 if (Name == ".bss" || Name.starts_with(".bss.") ||
499 Name.starts_with(".gnu.linkonce.b.") ||
500 Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" ||
501 Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") ||
502 Name.starts_with(".llvm.linkonce.sb."))
503 return SectionKind::getBSS();
504
505 if (Name == ".tdata" || Name.starts_with(".tdata.") ||
506 Name.starts_with(".gnu.linkonce.td.") ||
507 Name.starts_with(".llvm.linkonce.td."))
509
510 if (Name == ".tbss" || Name.starts_with(".tbss.") ||
511 Name.starts_with(".gnu.linkonce.tb.") ||
512 Name.starts_with(".llvm.linkonce.tb."))
514
515 return K;
516}
517
519 return SectionName.consume_front(Prefix) &&
520 (SectionName.empty() || SectionName[0] == '.');
521}
522
524 // Use SHT_NOTE for section whose name starts with ".note" to allow
525 // emitting ELF notes from C variable declaration.
526 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
527 if (Name.starts_with(".note"))
528 return ELF::SHT_NOTE;
529
530 if (hasPrefix(Name, ".init_array"))
531 return ELF::SHT_INIT_ARRAY;
532
533 if (hasPrefix(Name, ".fini_array"))
534 return ELF::SHT_FINI_ARRAY;
535
536 if (hasPrefix(Name, ".preinit_array"))
538
539 if (hasPrefix(Name, ".llvm.offloading"))
541 if (Name == ".llvm.lto")
542 return ELF::SHT_LLVM_LTO;
543
544 if (K.isBSS() || K.isThreadBSS())
545 return ELF::SHT_NOBITS;
546
547 return ELF::SHT_PROGBITS;
548}
549
550static unsigned getELFSectionFlags(SectionKind K) {
551 unsigned Flags = 0;
552
553 if (!K.isMetadata() && !K.isExclude())
554 Flags |= ELF::SHF_ALLOC;
555
556 if (K.isExclude())
557 Flags |= ELF::SHF_EXCLUDE;
558
559 if (K.isText())
560 Flags |= ELF::SHF_EXECINSTR;
561
562 if (K.isExecuteOnly())
563 Flags |= ELF::SHF_ARM_PURECODE;
564
565 if (K.isWriteable())
566 Flags |= ELF::SHF_WRITE;
567
568 if (K.isThreadLocal())
569 Flags |= ELF::SHF_TLS;
570
571 if (K.isMergeableCString() || K.isMergeableConst())
572 Flags |= ELF::SHF_MERGE;
573
574 if (K.isMergeableCString())
575 Flags |= ELF::SHF_STRINGS;
576
577 return Flags;
578}
579
580static const Comdat *getELFComdat(const GlobalValue *GV) {
581 const Comdat *C = GV->getComdat();
582 if (!C)
583 return nullptr;
584
585 if (C->getSelectionKind() != Comdat::Any &&
586 C->getSelectionKind() != Comdat::NoDeduplicate)
587 report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
588 "SelectionKind::NoDeduplicate, '" +
589 C->getName() + "' cannot be lowered.");
590
591 return C;
592}
593
595 const TargetMachine &TM) {
596 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
597 if (!MD)
598 return nullptr;
599
600 auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get());
601 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
602 return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
603}
604
605static unsigned getEntrySizeForKind(SectionKind Kind) {
606 if (Kind.isMergeable1ByteCString())
607 return 1;
608 else if (Kind.isMergeable2ByteCString())
609 return 2;
610 else if (Kind.isMergeable4ByteCString())
611 return 4;
612 else if (Kind.isMergeableConst4())
613 return 4;
614 else if (Kind.isMergeableConst8())
615 return 8;
616 else if (Kind.isMergeableConst16())
617 return 16;
618 else if (Kind.isMergeableConst32())
619 return 32;
620 else {
621 // We shouldn't have mergeable C strings or mergeable constants that we
622 // didn't handle above.
623 assert(!Kind.isMergeableCString() && "unknown string width");
624 assert(!Kind.isMergeableConst() && "unknown data width");
625 return 0;
626 }
627}
628
629/// Return the section prefix name used by options FunctionsSections and
630/// DataSections.
632 if (Kind.isText())
633 return IsLarge ? ".ltext" : ".text";
634 if (Kind.isReadOnly())
635 return IsLarge ? ".lrodata" : ".rodata";
636 if (Kind.isBSS())
637 return IsLarge ? ".lbss" : ".bss";
638 if (Kind.isThreadData())
639 return ".tdata";
640 if (Kind.isThreadBSS())
641 return ".tbss";
642 if (Kind.isData())
643 return IsLarge ? ".ldata" : ".data";
644 if (Kind.isReadOnlyWithRel())
645 return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro";
646 llvm_unreachable("Unknown section kind");
647}
648
649static SmallString<128>
651 Mangler &Mang, const TargetMachine &TM,
652 unsigned EntrySize, bool UniqueSectionName,
653 const MachineJumpTableEntry *JTE) {
655 getSectionPrefixForGlobal(Kind, TM.isLargeGlobalValue(GO));
656 if (Kind.isMergeableCString()) {
657 // We also need alignment here.
658 // FIXME: this is getting the alignment of the character, not the
659 // alignment of the global!
660 Align Alignment = GO->getDataLayout().getPreferredAlign(
661 cast<GlobalVariable>(GO));
662
663 Name += ".str";
664 Name += utostr(EntrySize);
665 Name += ".";
666 Name += utostr(Alignment.value());
667 } else if (Kind.isMergeableConst()) {
668 Name += ".cst";
669 Name += utostr(EntrySize);
670 }
671
672 bool HasPrefix = false;
673 if (const auto *F = dyn_cast<Function>(GO)) {
674 // Jump table hotness takes precedence over its enclosing function's hotness
675 // if it's known. The function's section prefix is used if jump table entry
676 // hotness is unknown.
677 if (JTE && JTE->Hotness != MachineFunctionDataHotness::Unknown) {
679 raw_svector_ostream(Name) << ".hot";
680 } else {
682 "Hotness must be cold");
683 raw_svector_ostream(Name) << ".unlikely";
684 }
685 HasPrefix = true;
686 } else if (std::optional<StringRef> Prefix = F->getSectionPrefix()) {
687 raw_svector_ostream(Name) << '.' << *Prefix;
688 HasPrefix = true;
689 }
690 }
691
692 if (UniqueSectionName) {
693 Name.push_back('.');
694 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
695 } else if (HasPrefix)
696 // For distinguishing between .text.${text-section-prefix}. (with trailing
697 // dot) and .text.${function-name}
698 Name.push_back('.');
699 return Name;
700}
701
702namespace {
703class LoweringDiagnosticInfo : public DiagnosticInfo {
704 const Twine &Msg;
705
706public:
707 LoweringDiagnosticInfo(const Twine &DiagMsg,
708 DiagnosticSeverity Severity = DS_Error)
709 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
710 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
711};
712}
713
714/// Calculate an appropriate unique ID for a section, and update Flags,
715/// EntrySize and NextUniqueID where appropriate.
716static unsigned
718 SectionKind Kind, const TargetMachine &TM,
719 MCContext &Ctx, Mangler &Mang, unsigned &Flags,
720 unsigned &EntrySize, unsigned &NextUniqueID,
721 const bool Retain, const bool ForceUnique) {
722 // Increment uniqueID if we are forced to emit a unique section.
723 // This works perfectly fine with section attribute or pragma section as the
724 // sections with the same name are grouped together by the assembler.
725 if (ForceUnique)
726 return NextUniqueID++;
727
728 // A section can have at most one associated section. Put each global with
729 // MD_associated in a unique section.
730 const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
731 if (Associated) {
732 Flags |= ELF::SHF_LINK_ORDER;
733 return NextUniqueID++;
734 }
735
736 if (Retain) {
737 if (TM.getTargetTriple().isOSSolaris())
739 else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
740 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36))
741 Flags |= ELF::SHF_GNU_RETAIN;
742 return NextUniqueID++;
743 }
744
745 // If two symbols with differing sizes end up in the same mergeable section
746 // that section can be assigned an incorrect entry size. To avoid this we
747 // usually put symbols of the same size into distinct mergeable sections with
748 // the same name. Doing so relies on the ",unique ," assembly feature. This
749 // feature is not available until binutils version 2.35
750 // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
751 const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
752 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
753 if (!SupportsUnique) {
754 Flags &= ~ELF::SHF_MERGE;
755 EntrySize = 0;
757 }
758
759 const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
760 const bool SeenSectionNameBefore =
762 // If this is the first occurrence of this section name, treat it as the
763 // generic section
764 if (!SymbolMergeable && !SeenSectionNameBefore) {
765 if (TM.getSeparateNamedSections())
766 return NextUniqueID++;
767 else
769 }
770
771 // Symbols must be placed into sections with compatible entry sizes. Generate
772 // unique sections for symbols that have not been assigned to compatible
773 // sections.
774 const auto PreviousID =
775 Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
776 if (PreviousID && (!TM.getSeparateNamedSections() ||
777 *PreviousID == MCContext::GenericSectionID))
778 return *PreviousID;
779
780 // If the user has specified the same section name as would be created
781 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
782 // to unique the section as the entry size for this symbol will be
783 // compatible with implicitly created sections.
784 SmallString<128> ImplicitSectionNameStem = getELFSectionNameForGlobal(
785 GO, Kind, Mang, TM, EntrySize, false, /*MJTE=*/nullptr);
786 if (SymbolMergeable &&
788 SectionName.starts_with(ImplicitSectionNameStem))
790
791 // We have seen this section name before, but with different flags or entity
792 // size. Create a new unique ID.
793 return NextUniqueID++;
794}
795
796static std::tuple<StringRef, bool, unsigned>
798 StringRef Group = "";
799 bool IsComdat = false;
800 unsigned Flags = 0;
801 if (const Comdat *C = getELFComdat(GO)) {
802 Flags |= ELF::SHF_GROUP;
803 Group = C->getName();
804 IsComdat = C->getSelectionKind() == Comdat::Any;
805 }
806 if (TM.isLargeGlobalValue(GO))
807 Flags |= ELF::SHF_X86_64_LARGE;
808 return {Group, IsComdat, Flags};
809}
810
812 SectionKind Kind) {
813 // Check if '#pragma clang section' name is applicable.
814 // Note that pragma directive overrides -ffunction-section, -fdata-section
815 // and so section name is exactly as user specified and not uniqued.
816 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
817 if (GV && GV->hasImplicitSection()) {
818 auto Attrs = GV->getAttributes();
819 if (Attrs.hasAttribute("bss-section") && Kind.isBSS())
820 return Attrs.getAttribute("bss-section").getValueAsString();
821 else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())
822 return Attrs.getAttribute("rodata-section").getValueAsString();
823 else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel())
824 return Attrs.getAttribute("relro-section").getValueAsString();
825 else if (Attrs.hasAttribute("data-section") && Kind.isData())
826 return Attrs.getAttribute("data-section").getValueAsString();
827 }
828
829 return GO->getSection();
830}
831
833 SectionKind Kind,
834 const TargetMachine &TM,
835 MCContext &Ctx, Mangler &Mang,
836 unsigned &NextUniqueID,
837 bool Retain, bool ForceUnique) {
839
840 // Infer section flags from the section name if we can.
842
843 unsigned Flags = getELFSectionFlags(Kind);
844 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
845 Flags |= ExtraFlags;
846
847 unsigned EntrySize = getEntrySizeForKind(Kind);
848 const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
849 GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
850 Retain, ForceUnique);
851
852 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
853 MCSectionELF *Section = Ctx.getELFSection(
854 SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
855 Group, IsComdat, UniqueID, LinkedToSym);
856 // Make sure that we did not get some other section with incompatible sh_link.
857 // This should not be possible due to UniqueID code above.
858 assert(Section->getLinkedToSymbol() == LinkedToSym &&
859 "Associated symbol mismatch between sections");
860
861 if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
862 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
863 // If we are using GNU as before 2.35, then this symbol might have
864 // been placed in an incompatible mergeable section. Emit an error if this
865 // is the case to avoid creating broken output.
866 if ((Section->getFlags() & ELF::SHF_MERGE) &&
867 (Section->getEntrySize() != getEntrySizeForKind(Kind)))
868 GO->getContext().diagnose(LoweringDiagnosticInfo(
869 "Symbol '" + GO->getName() + "' from module '" +
870 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
871 "' required a section with entry-size=" +
872 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
873 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
874 ": Explicit assignment by pragma or attribute of an incompatible "
875 "symbol to this section?"));
876 }
877
878 return Section;
879}
880
882 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
884 NextUniqueID, Used.count(GO),
885 /* ForceUnique = */false);
886}
887
889 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
890 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
891 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol,
892 const MachineJumpTableEntry *MJTE = nullptr) {
893
894 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
895 Flags |= ExtraFlags;
896
897 // Get the section entry size based on the kind.
898 unsigned EntrySize = getEntrySizeForKind(Kind);
899
900 bool UniqueSectionName = false;
901 unsigned UniqueID = MCContext::GenericSectionID;
902 if (EmitUniqueSection) {
903 if (TM.getUniqueSectionNames()) {
904 UniqueSectionName = true;
905 } else {
906 UniqueID = *NextUniqueID;
907 (*NextUniqueID)++;
908 }
909 }
911 GO, Kind, Mang, TM, EntrySize, UniqueSectionName, MJTE);
912
913 // Use 0 as the unique ID for execute-only text.
914 if (Kind.isExecuteOnly())
915 UniqueID = 0;
916 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
917 EntrySize, Group, IsComdat, UniqueID,
918 AssociatedSymbol);
919}
920
922 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
923 const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
924 unsigned Flags, unsigned *NextUniqueID) {
925 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
926 if (LinkedToSym) {
927 EmitUniqueSection = true;
928 Flags |= ELF::SHF_LINK_ORDER;
929 }
930 if (Retain) {
931 if (TM.getTargetTriple().isOSSolaris()) {
932 EmitUniqueSection = true;
934 } else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
935 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) {
936 EmitUniqueSection = true;
937 Flags |= ELF::SHF_GNU_RETAIN;
938 }
939 }
940
942 Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
943 NextUniqueID, LinkedToSym);
944 assert(Section->getLinkedToSymbol() == LinkedToSym);
945 return Section;
946}
947
949 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
950 unsigned Flags = getELFSectionFlags(Kind);
951
952 // If we have -ffunction-section or -fdata-section then we should emit the
953 // global value to a uniqued section specifically for it.
954 bool EmitUniqueSection = false;
955 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
956 if (Kind.isText())
957 EmitUniqueSection = TM.getFunctionSections();
958 else
959 EmitUniqueSection = TM.getDataSections();
960 }
961 EmitUniqueSection |= GO->hasComdat();
962 return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
963 Used.count(GO), EmitUniqueSection, Flags,
964 &NextUniqueID);
965}
966
968 const Function &F, const TargetMachine &TM) const {
970 unsigned Flags = getELFSectionFlags(Kind);
971 // If the function's section names is pre-determined via pragma or a
972 // section attribute, call selectExplicitSectionGlobal.
973 if (F.hasSection())
975 &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
976 Used.count(&F), /* ForceUnique = */true);
977 else
979 getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
980 /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
981}
982
984 const Function &F, const TargetMachine &TM) const {
985 return getSectionForJumpTable(F, TM, /*JTE=*/nullptr);
986}
987
989 const Function &F, const TargetMachine &TM,
990 const MachineJumpTableEntry *JTE) const {
991 // If the function can be removed, produce a unique section so that
992 // the table doesn't prevent the removal.
993 const Comdat *C = F.getComdat();
994 bool EmitUniqueSection = TM.getFunctionSections() || C;
995 if (!EmitUniqueSection && !TM.getEnableStaticDataPartitioning())
996 return ReadOnlySection;
997
999 getMangler(), TM, EmitUniqueSection,
1000 ELF::SHF_ALLOC, &NextUniqueID,
1001 /* AssociatedSymbol */ nullptr, JTE);
1002}
1003
1005 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
1006 // If neither COMDAT nor function sections, use the monolithic LSDA section.
1007 // Re-use this path if LSDASection is null as in the Arm EHABI.
1008 if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
1009 return LSDASection;
1010
1011 const auto *LSDA = cast<MCSectionELF>(LSDASection);
1012 unsigned Flags = LSDA->getFlags();
1013 const MCSymbolELF *LinkedToSym = nullptr;
1014 StringRef Group;
1015 bool IsComdat = false;
1016 if (const Comdat *C = getELFComdat(&F)) {
1017 Flags |= ELF::SHF_GROUP;
1018 Group = C->getName();
1019 IsComdat = C->getSelectionKind() == Comdat::Any;
1020 }
1021 // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
1022 // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
1023 if (TM.getFunctionSections() &&
1024 (getContext().getAsmInfo()->useIntegratedAssembler() &&
1025 getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
1026 Flags |= ELF::SHF_LINK_ORDER;
1027 LinkedToSym = cast<MCSymbolELF>(&FnSym);
1028 }
1029
1030 // Append the function name as the suffix like GCC, assuming
1031 // -funique-section-names applies to .gcc_except_table sections.
1032 return getContext().getELFSection(
1033 (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
1034 : LSDA->getName()),
1035 LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
1036 LinkedToSym);
1037}
1038
1040 bool UsesLabelDifference, const Function &F) const {
1041 // We can always create relative relocations, so use another section
1042 // that can be marked non-executable.
1043 return false;
1044}
1045
1046/// Given a mergeable constant with the specified size and relocation
1047/// information, return a section that it should be placed in.
1049 const DataLayout &DL, SectionKind Kind, const Constant *C,
1050 Align &Alignment) const {
1051 if (Kind.isMergeableConst4() && MergeableConst4Section)
1053 if (Kind.isMergeableConst8() && MergeableConst8Section)
1055 if (Kind.isMergeableConst16() && MergeableConst16Section)
1057 if (Kind.isMergeableConst32() && MergeableConst32Section)
1059 if (Kind.isReadOnly())
1060 return ReadOnlySection;
1061
1062 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
1063 return DataRelROSection;
1064}
1065
1066/// Returns a unique section for the given machine basic block.
1068 const Function &F, const MachineBasicBlock &MBB,
1069 const TargetMachine &TM) const {
1070 assert(MBB.isBeginSection() && "Basic block does not start a section!");
1071 unsigned UniqueID = MCContext::GenericSectionID;
1072
1073 // For cold sections use the .text.split. prefix along with the parent
1074 // function name. All cold blocks for the same function go to the same
1075 // section. Similarly all exception blocks are grouped by symbol name
1076 // under the .text.eh prefix. For regular sections, we either use a unique
1077 // name, or a unique ID for the section.
1079 StringRef FunctionSectionName = MBB.getParent()->getSection()->getName();
1080 if (FunctionSectionName == ".text" ||
1081 FunctionSectionName.starts_with(".text.")) {
1082 // Function is in a regular .text section.
1083 StringRef FunctionName = MBB.getParent()->getName();
1086 Name += FunctionName;
1088 Name += ".text.eh.";
1089 Name += FunctionName;
1090 } else {
1091 Name += FunctionSectionName;
1093 if (!Name.ends_with("."))
1094 Name += ".";
1095 Name += MBB.getSymbol()->getName();
1096 } else {
1097 UniqueID = NextUniqueID++;
1098 }
1099 }
1100 } else {
1101 // If the original function has a custom non-dot-text section, then emit
1102 // all basic block sections into that section too, each with a unique id.
1103 Name = FunctionSectionName;
1104 UniqueID = NextUniqueID++;
1105 }
1106
1107 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
1108 std::string GroupName;
1109 if (F.hasComdat()) {
1110 Flags |= ELF::SHF_GROUP;
1111 GroupName = F.getComdat()->getName().str();
1112 }
1114 0 /* Entry Size */, GroupName,
1115 F.hasComdat(), UniqueID, nullptr);
1116}
1117
1118static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1119 bool IsCtor, unsigned Priority,
1120 const MCSymbol *KeySym) {
1121 std::string Name;
1122 unsigned Type;
1123 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1124 StringRef Comdat = KeySym ? KeySym->getName() : "";
1125
1126 if (KeySym)
1127 Flags |= ELF::SHF_GROUP;
1128
1129 if (UseInitArray) {
1130 if (IsCtor) {
1132 Name = ".init_array";
1133 } else {
1135 Name = ".fini_array";
1136 }
1137 if (Priority != 65535) {
1138 Name += '.';
1139 Name += utostr(Priority);
1140 }
1141 } else {
1142 // The default scheme is .ctor / .dtor, so we have to invert the priority
1143 // numbering.
1144 if (IsCtor)
1145 Name = ".ctors";
1146 else
1147 Name = ".dtors";
1148 if (Priority != 65535)
1149 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1151 }
1152
1153 return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1154}
1155
1157 unsigned Priority, const MCSymbol *KeySym) const {
1158 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1159 KeySym);
1160}
1161
1163 unsigned Priority, const MCSymbol *KeySym) const {
1164 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1165 KeySym);
1166}
1167
1169 const GlobalValue *LHS, const GlobalValue *RHS,
1170 const TargetMachine &TM) const {
1171 // We may only use a PLT-relative relocation to refer to unnamed_addr
1172 // functions.
1173 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1174 return nullptr;
1175
1176 // Basic correctness checks.
1177 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1178 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1179 RHS->isThreadLocal())
1180 return nullptr;
1181
1184 getContext()),
1186}
1187
1189 const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1191
1192 const auto *GV = Equiv->getGlobalValue();
1193
1194 // A PLT entry is not needed for dso_local globals.
1195 if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1197
1199 getContext());
1200}
1201
1203 // Use ".GCC.command.line" since this feature is to support clang's
1204 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1205 // same name.
1206 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1208}
1209
1210void
1212 UseInitArray = UseInitArray_;
1213 MCContext &Ctx = getContext();
1214 if (!UseInitArray) {
1217
1220 return;
1221 }
1222
1227}
1228
1229//===----------------------------------------------------------------------===//
1230// MachO
1231//===----------------------------------------------------------------------===//
1232
1235}
1236
1238 const TargetMachine &TM) {
1241 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1243 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1245 } else {
1246 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1249 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1252 }
1253
1259}
1260
1262 unsigned Priority, const MCSymbol *KeySym) const {
1263 return StaticDtorSection;
1264 // In userspace, we lower global destructors via atexit(), but kernel/kext
1265 // environments do not provide this function so we still need to support the
1266 // legacy way here.
1267 // See the -disable-atexit-based-global-dtor-lowering CodeGen flag for more
1268 // context.
1269}
1270
1272 Module &M) const {
1273 // Emit the linker options if present.
1274 emitLinkerDirectives(Streamer, M);
1275
1276 unsigned VersionVal = 0;
1277 unsigned ImageInfoFlags = 0;
1278 StringRef SectionVal;
1279
1280 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1281 emitCGProfileMetadata(Streamer, M);
1282
1283 // The section is mandatory. If we don't have it, then we don't have GC info.
1284 if (SectionVal.empty())
1285 return;
1286
1287 StringRef Segment, Section;
1288 unsigned TAA = 0, StubSize = 0;
1289 bool TAAParsed;
1291 SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1292 // If invalid, report the error with report_fatal_error.
1293 report_fatal_error("Invalid section specifier '" + Section +
1294 "': " + toString(std::move(E)) + ".");
1295 }
1296
1297 // Get the section.
1299 Segment, Section, TAA, StubSize, SectionKind::getData());
1300 Streamer.switchSection(S);
1301 Streamer.emitLabel(getContext().
1302 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1303 Streamer.emitInt32(VersionVal);
1304 Streamer.emitInt32(ImageInfoFlags);
1305 Streamer.addBlankLine();
1306}
1307
1309 Module &M) const {
1310 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1311 for (const auto *Option : LinkerOptions->operands()) {
1312 SmallVector<std::string, 4> StrOptions;
1313 for (const auto &Piece : cast<MDNode>(Option)->operands())
1314 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1315 Streamer.emitLinkerOptions(StrOptions);
1316 }
1317 }
1318}
1319
1320static void checkMachOComdat(const GlobalValue *GV) {
1321 const Comdat *C = GV->getComdat();
1322 if (!C)
1323 return;
1324
1325 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1326 "' cannot be lowered.");
1327}
1328
1330 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1331
1333
1334 // Parse the section specifier and create it if valid.
1335 StringRef Segment, Section;
1336 unsigned TAA = 0, StubSize = 0;
1337 bool TAAParsed;
1338
1339 checkMachOComdat(GO);
1340
1342 SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1343 // If invalid, report the error with report_fatal_error.
1344 report_fatal_error("Global variable '" + GO->getName() +
1345 "' has an invalid section specifier '" +
1346 GO->getSection() + "': " + toString(std::move(E)) + ".");
1347 }
1348
1349 // Get the section.
1350 MCSectionMachO *S =
1351 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1352
1353 // If TAA wasn't set by ParseSectionSpecifier() above,
1354 // use the value returned by getMachOSection() as a default.
1355 if (!TAAParsed)
1356 TAA = S->getTypeAndAttributes();
1357
1358 // Okay, now that we got the section, verify that the TAA & StubSize agree.
1359 // If the user declared multiple globals with different section flags, we need
1360 // to reject it here.
1361 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1362 // If invalid, report the error with report_fatal_error.
1363 report_fatal_error("Global variable '" + GO->getName() +
1364 "' section type or attributes does not match previous"
1365 " section specifier");
1366 }
1367
1368 return S;
1369}
1370
1372 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1373 checkMachOComdat(GO);
1374
1375 // Handle thread local data.
1376 if (Kind.isThreadBSS()) return TLSBSSSection;
1377 if (Kind.isThreadData()) return TLSDataSection;
1378
1379 if (Kind.isText())
1381
1382 // If this is weak/linkonce, put this in a coalescable section, either in text
1383 // or data depending on if it is writable.
1384 if (GO->isWeakForLinker()) {
1385 if (Kind.isReadOnly())
1386 return ConstTextCoalSection;
1387 if (Kind.isReadOnlyWithRel())
1388 return ConstDataCoalSection;
1389 return DataCoalSection;
1390 }
1391
1392 // FIXME: Alignment check should be handled by section classifier.
1393 if (Kind.isMergeable1ByteCString() &&
1395 cast<GlobalVariable>(GO)) < Align(32))
1396 return CStringSection;
1397
1398 // Do not put 16-bit arrays in the UString section if they have an
1399 // externally visible label, this runs into issues with certain linker
1400 // versions.
1401 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1403 cast<GlobalVariable>(GO)) < Align(32))
1404 return UStringSection;
1405
1406 // With MachO only variables whose corresponding symbol starts with 'l' or
1407 // 'L' can be merged, so we only try merging GVs with private linkage.
1408 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1409 if (Kind.isMergeableConst4())
1411 if (Kind.isMergeableConst8())
1413 if (Kind.isMergeableConst16())
1415 }
1416
1417 // Otherwise, if it is readonly, but not something we can specially optimize,
1418 // just drop it in .const.
1419 if (Kind.isReadOnly())
1420 return ReadOnlySection;
1421
1422 // If this is marked const, put it into a const section. But if the dynamic
1423 // linker needs to write to it, put it in the data segment.
1424 if (Kind.isReadOnlyWithRel())
1425 return ConstDataSection;
1426
1427 // Put zero initialized globals with strong external linkage in the
1428 // DATA, __common section with the .zerofill directive.
1429 if (Kind.isBSSExtern())
1430 return DataCommonSection;
1431
1432 // Put zero initialized globals with local linkage in __DATA,__bss directive
1433 // with the .zerofill directive (aka .lcomm).
1434 if (Kind.isBSSLocal())
1435 return DataBSSSection;
1436
1437 // Otherwise, just drop the variable in the normal data section.
1438 return DataSection;
1439}
1440
1442 const DataLayout &DL, SectionKind Kind, const Constant *C,
1443 Align &Alignment) const {
1444 // If this constant requires a relocation, we have to put it in the data
1445 // segment, not in the text segment.
1446 if (Kind.isData() || Kind.isReadOnlyWithRel())
1447 return ConstDataSection;
1448
1449 if (Kind.isMergeableConst4())
1451 if (Kind.isMergeableConst8())
1453 if (Kind.isMergeableConst16())
1455 return ReadOnlySection; // .const
1456}
1457
1459 return getContext().getMachOSection("__TEXT", "__command_line", 0,
1461}
1462
1464 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1465 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1466 // The mach-o version of this method defaults to returning a stub reference.
1467
1468 if (Encoding & DW_EH_PE_indirect) {
1469 MachineModuleInfoMachO &MachOMMI =
1471
1472 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1473
1474 // Add information about the stub reference to MachOMMI so that the stub
1475 // gets emitted by the asmprinter.
1476 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1477 if (!StubSym.getPointer()) {
1478 MCSymbol *Sym = TM.getSymbol(GV);
1480 }
1481
1484 Encoding & ~DW_EH_PE_indirect, Streamer);
1485 }
1486
1488 MMI, Streamer);
1489}
1490
1492 const GlobalValue *GV, const TargetMachine &TM,
1493 MachineModuleInfo *MMI) const {
1494 // The mach-o version of this method defaults to returning a stub reference.
1495 MachineModuleInfoMachO &MachOMMI =
1497
1498 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1499
1500 // Add information about the stub reference to MachOMMI so that the stub
1501 // gets emitted by the asmprinter.
1502 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1503 if (!StubSym.getPointer()) {
1504 MCSymbol *Sym = TM.getSymbol(GV);
1506 }
1507
1508 return SSym;
1509}
1510
1512 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1513 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1514 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1515 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1516 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1517 // computation of deltas to final external symbols. Example:
1518 //
1519 // _extgotequiv:
1520 // .long _extfoo
1521 //
1522 // _delta:
1523 // .long _extgotequiv-_delta
1524 //
1525 // is transformed to:
1526 //
1527 // _delta:
1528 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1529 //
1530 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1531 // L_extfoo$non_lazy_ptr:
1532 // .indirect_symbol _extfoo
1533 // .long 0
1534 //
1535 // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1536 // may point to both local (same translation unit) and global (other
1537 // translation units) symbols. Example:
1538 //
1539 // .section __DATA,__pointers,non_lazy_symbol_pointers
1540 // L1:
1541 // .indirect_symbol _myGlobal
1542 // .long 0
1543 // L2:
1544 // .indirect_symbol _myLocal
1545 // .long _myLocal
1546 //
1547 // If the symbol is local, instead of the symbol's index, the assembler
1548 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1549 // Then the linker will notice the constant in the table and will look at the
1550 // content of the symbol.
1551 MachineModuleInfoMachO &MachOMMI =
1553 MCContext &Ctx = getContext();
1554
1555 // The offset must consider the original displacement from the base symbol
1556 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1557 Offset = -MV.getConstant();
1558 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1559
1560 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1561 // non_lazy_ptr stubs.
1563 StringRef Suffix = "$non_lazy_ptr";
1565 Name += Sym->getName();
1566 Name += Suffix;
1567 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1568
1569 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1570
1571 if (!StubSym.getPointer())
1572 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1573 !GV->hasLocalLinkage());
1574
1575 const MCExpr *BSymExpr =
1577 const MCExpr *LHS =
1579
1580 if (!Offset)
1581 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1582
1583 const MCExpr *RHS =
1585 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1586}
1587
1588static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1589 const MCSection &Section) {
1591 return true;
1592
1593 // FIXME: we should be able to use private labels for sections that can't be
1594 // dead-stripped (there's no issue with blocking atomization there), but `ld
1595 // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1596 // we don't allow it.
1597 return false;
1598}
1599
1601 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1602 const TargetMachine &TM) const {
1603 bool CannotUsePrivateLabel = true;
1604 if (auto *GO = GV->getAliaseeObject()) {
1606 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1607 CannotUsePrivateLabel =
1608 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1609 }
1610 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1611}
1612
1613//===----------------------------------------------------------------------===//
1614// COFF
1615//===----------------------------------------------------------------------===//
1616
1617static unsigned
1619 unsigned Flags = 0;
1620 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1621
1622 if (K.isMetadata())
1623 Flags |=
1625 else if (K.isExclude())
1626 Flags |=
1628 else if (K.isText())
1629 Flags |=
1634 else if (K.isBSS())
1635 Flags |=
1639 else if (K.isThreadLocal())
1640 Flags |=
1644 else if (K.isReadOnly() || K.isReadOnlyWithRel())
1645 Flags |=
1648 else if (K.isWriteable())
1649 Flags |=
1653
1654 return Flags;
1655}
1656
1658 const Comdat *C = GV->getComdat();
1659 assert(C && "expected GV to have a Comdat!");
1660
1661 StringRef ComdatGVName = C->getName();
1662 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1663 if (!ComdatGV)
1664 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1665 "' does not exist.");
1666
1667 if (ComdatGV->getComdat() != C)
1668 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1669 "' is not a key for its COMDAT.");
1670
1671 return ComdatGV;
1672}
1673
1674static int getSelectionForCOFF(const GlobalValue *GV) {
1675 if (const Comdat *C = GV->getComdat()) {
1676 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1677 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1678 ComdatKey = GA->getAliaseeObject();
1679 if (ComdatKey == GV) {
1680 switch (C->getSelectionKind()) {
1681 case Comdat::Any:
1683 case Comdat::ExactMatch:
1685 case Comdat::Largest:
1689 case Comdat::SameSize:
1691 }
1692 } else {
1694 }
1695 }
1696 return 0;
1697}
1698
1700 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1702 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::COFF,
1703 /*AddSegmentInfo=*/false) ||
1705 /*AddSegmentInfo=*/false) ||
1706 Name == getInstrProfSectionName(IPSK_covdata, Triple::COFF,
1707 /*AddSegmentInfo=*/false) ||
1708 Name == getInstrProfSectionName(IPSK_covname, Triple::COFF,
1709 /*AddSegmentInfo=*/false))
1710 Kind = SectionKind::getMetadata();
1711 int Selection = 0;
1712 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1713 StringRef COMDATSymName = "";
1714 if (GO->hasComdat()) {
1716 const GlobalValue *ComdatGV;
1718 ComdatGV = getComdatGVForCOFF(GO);
1719 else
1720 ComdatGV = GO;
1721
1722 if (!ComdatGV->hasPrivateLinkage()) {
1723 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1724 COMDATSymName = Sym->getName();
1726 } else {
1727 Selection = 0;
1728 }
1729 }
1730
1731 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1732 Selection);
1733}
1734
1736 if (Kind.isText())
1737 return ".text";
1738 if (Kind.isBSS())
1739 return ".bss";
1740 if (Kind.isThreadLocal())
1741 return ".tls$";
1742 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1743 return ".rdata";
1744 return ".data";
1745}
1746
1748 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1749 // If we have -ffunction-sections then we should emit the global value to a
1750 // uniqued section specifically for it.
1751 bool EmitUniquedSection;
1752 if (Kind.isText())
1753 EmitUniquedSection = TM.getFunctionSections();
1754 else
1755 EmitUniquedSection = TM.getDataSections();
1756
1757 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1759
1760 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1761
1764 if (!Selection)
1766 const GlobalValue *ComdatGV;
1767 if (GO->hasComdat())
1768 ComdatGV = getComdatGVForCOFF(GO);
1769 else
1770 ComdatGV = GO;
1771
1772 unsigned UniqueID = MCContext::GenericSectionID;
1773 if (EmitUniquedSection)
1774 UniqueID = NextUniqueID++;
1775
1776 if (!ComdatGV->hasPrivateLinkage()) {
1777 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1778 StringRef COMDATSymName = Sym->getName();
1779
1780 if (const auto *F = dyn_cast<Function>(GO))
1781 if (std::optional<StringRef> Prefix = F->getSectionPrefix())
1782 raw_svector_ostream(Name) << '$' << *Prefix;
1783
1784 // Append "$symbol" to the section name *before* IR-level mangling is
1785 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1786 // COFF linker will not properly handle comdats otherwise.
1787 if (getContext().getTargetTriple().isWindowsGNUEnvironment())
1788 raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1789
1790 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1791 Selection, UniqueID);
1792 } else {
1793 SmallString<256> TmpData;
1794 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1795 return getContext().getCOFFSection(Name, Characteristics, TmpData,
1796 Selection, UniqueID);
1797 }
1798 }
1799
1800 if (Kind.isText())
1801 return TextSection;
1802
1803 if (Kind.isThreadLocal())
1804 return TLSDataSection;
1805
1806 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1807 return ReadOnlySection;
1808
1809 // Note: we claim that common symbols are put in BSSSection, but they are
1810 // really emitted with the magic .comm directive, which creates a symbol table
1811 // entry but not a section.
1812 if (Kind.isBSS() || Kind.isCommon())
1813 return BSSSection;
1814
1815 return DataSection;
1816}
1817
1819 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1820 const TargetMachine &TM) const {
1821 bool CannotUsePrivateLabel = false;
1822 if (GV->hasPrivateLinkage() &&
1823 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1824 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1825 CannotUsePrivateLabel = true;
1826
1827 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1828}
1829
1831 const Function &F, const TargetMachine &TM) const {
1832 // If the function can be removed, produce a unique section so that
1833 // the table doesn't prevent the removal.
1834 const Comdat *C = F.getComdat();
1835 bool EmitUniqueSection = TM.getFunctionSections() || C;
1836 if (!EmitUniqueSection)
1837 return ReadOnlySection;
1838
1839 // FIXME: we should produce a symbol for F instead.
1840 if (F.hasPrivateLinkage())
1841 return ReadOnlySection;
1842
1843 MCSymbol *Sym = TM.getSymbol(&F);
1844 StringRef COMDATSymName = Sym->getName();
1845
1848 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1850 unsigned UniqueID = NextUniqueID++;
1851
1852 return getContext().getCOFFSection(SecName, Characteristics, COMDATSymName,
1854 UniqueID);
1855}
1856
1858 bool UsesLabelDifference, const Function &F) const {
1859 if (TM->getTargetTriple().getArch() == Triple::x86_64) {
1861 // We can always create relative relocations, so use another section
1862 // that can be marked non-executable.
1863 return false;
1864 }
1865 }
1867 UsesLabelDifference, F);
1868}
1869
1871 Module &M) const {
1872 emitLinkerDirectives(Streamer, M);
1873
1874 unsigned Version = 0;
1875 unsigned Flags = 0;
1876 StringRef Section;
1877
1878 GetObjCImageInfo(M, Version, Flags, Section);
1879 if (!Section.empty()) {
1880 auto &C = getContext();
1881 auto *S = C.getCOFFSection(Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1883 Streamer.switchSection(S);
1884 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1885 Streamer.emitInt32(Version);
1886 Streamer.emitInt32(Flags);
1887 Streamer.addBlankLine();
1888 }
1889
1890 emitCGProfileMetadata(Streamer, M);
1891}
1892
1894 MCStreamer &Streamer, Module &M) const {
1895 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1896 // Emit the linker options to the linker .drectve section. According to the
1897 // spec, this section is a space-separated string containing flags for
1898 // linker.
1900 Streamer.switchSection(Sec);
1901 for (const auto *Option : LinkerOptions->operands()) {
1902 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1903 // Lead with a space for consistency with our dllexport implementation.
1904 std::string Directive(" ");
1905 Directive.append(std::string(cast<MDString>(Piece)->getString()));
1906 Streamer.emitBytes(Directive);
1907 }
1908 }
1909 }
1910
1911 // Emit /EXPORT: flags for each exported global as necessary.
1912 std::string Flags;
1913 for (const GlobalValue &GV : M.global_values()) {
1914 raw_string_ostream OS(Flags);
1915 emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
1916 getMangler());
1917 OS.flush();
1918 if (!Flags.empty()) {
1919 Streamer.switchSection(getDrectveSection());
1920 Streamer.emitBytes(Flags);
1921 }
1922 Flags.clear();
1923 }
1924
1925 // Emit /INCLUDE: flags for each used global as necessary.
1926 if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1927 assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1928 assert(isa<ArrayType>(LU->getValueType()) &&
1929 "expected llvm.used to be an array type");
1930 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1931 for (const Value *Op : A->operands()) {
1932 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1933 // Global symbols with internal or private linkage are not visible to
1934 // the linker, and thus would cause an error when the linker tried to
1935 // preserve the symbol due to the `/include:` directive.
1936 if (GV->hasLocalLinkage())
1937 continue;
1938
1939 raw_string_ostream OS(Flags);
1940 emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
1941 getMangler());
1942 OS.flush();
1943
1944 if (!Flags.empty()) {
1945 Streamer.switchSection(getDrectveSection());
1946 Streamer.emitBytes(Flags);
1947 }
1948 Flags.clear();
1949 }
1950 }
1951 }
1952}
1953
1955 const TargetMachine &TM) {
1957 this->TM = &TM;
1958 const Triple &T = TM.getTargetTriple();
1959 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1966 } else {
1973 }
1974}
1975
1977 const Triple &T, bool IsCtor,
1978 unsigned Priority,
1979 const MCSymbol *KeySym,
1981 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1982 // If the priority is the default, use .CRT$XCU, possibly associative.
1983 if (Priority == 65535)
1984 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1985
1986 // Otherwise, we need to compute a new section name. Low priorities should
1987 // run earlier. The linker will sort sections ASCII-betically, and we need a
1988 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1989 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1990 // low priorities need to sort before 'L', since the CRT uses that
1991 // internally, so we use ".CRT$XCA00001" for them. We have a contract with
1992 // the frontend that "init_seg(compiler)" corresponds to priority 200 and
1993 // "init_seg(lib)" corresponds to priority 400, and those respectively use
1994 // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
1995 // use 'C' with the priority as a suffix.
1997 char LastLetter = 'T';
1998 bool AddPrioritySuffix = Priority != 200 && Priority != 400;
1999 if (Priority < 200)
2000 LastLetter = 'A';
2001 else if (Priority < 400)
2002 LastLetter = 'C';
2003 else if (Priority == 400)
2004 LastLetter = 'L';
2006 OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
2007 if (AddPrioritySuffix)
2008 OS << format("%05u", Priority);
2009 MCSectionCOFF *Sec = Ctx.getCOFFSection(
2011 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
2012 }
2013
2014 std::string Name = IsCtor ? ".ctors" : ".dtors";
2015 if (Priority != 65535)
2016 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
2017
2018 return Ctx.getAssociativeCOFFSection(
2022 KeySym, 0);
2023}
2024
2026 unsigned Priority, const MCSymbol *KeySym) const {
2028 getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
2029 cast<MCSectionCOFF>(StaticCtorSection));
2030}
2031
2033 unsigned Priority, const MCSymbol *KeySym) const {
2035 getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
2036 cast<MCSectionCOFF>(StaticDtorSection));
2037}
2038
2040 const GlobalValue *LHS, const GlobalValue *RHS,
2041 const TargetMachine &TM) const {
2042 const Triple &T = TM.getTargetTriple();
2043 if (T.isOSCygMing())
2044 return nullptr;
2045
2046 // Our symbols should exist in address space zero, cowardly no-op if
2047 // otherwise.
2048 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2050 return nullptr;
2051
2052 // Both ptrtoint instructions must wrap global objects:
2053 // - Only global variables are eligible for image relative relocations.
2054 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
2055 // We expect __ImageBase to be a global variable without a section, externally
2056 // defined.
2057 //
2058 // It should look something like this: @__ImageBase = external constant i8
2059 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
2060 LHS->isThreadLocal() || RHS->isThreadLocal() ||
2061 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
2062 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
2063 return nullptr;
2064
2065 return MCSymbolRefExpr::create(TM.getSymbol(LHS),
2067 getContext());
2068}
2069
2070static std::string APIntToHexString(const APInt &AI) {
2071 unsigned Width = (AI.getBitWidth() / 8) * 2;
2072 std::string HexString = toString(AI, 16, /*Signed=*/false);
2073 llvm::transform(HexString, HexString.begin(), tolower);
2074 unsigned Size = HexString.size();
2075 assert(Width >= Size && "hex string is too large!");
2076 HexString.insert(HexString.begin(), Width - Size, '0');
2077
2078 return HexString;
2079}
2080
2081static std::string scalarConstantToHexString(const Constant *C) {
2082 Type *Ty = C->getType();
2083 if (isa<UndefValue>(C)) {
2085 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
2086 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2087 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
2088 return APIntToHexString(CI->getValue());
2089 } else {
2090 unsigned NumElements;
2091 if (auto *VTy = dyn_cast<VectorType>(Ty))
2092 NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2093 else
2094 NumElements = Ty->getArrayNumElements();
2095 std::string HexString;
2096 for (int I = NumElements - 1, E = -1; I != E; --I)
2097 HexString += scalarConstantToHexString(C->getAggregateElement(I));
2098 return HexString;
2099 }
2100}
2101
2103 const DataLayout &DL, SectionKind Kind, const Constant *C,
2104 Align &Alignment) const {
2105 if (Kind.isMergeableConst() && C &&
2106 getContext().getAsmInfo()->hasCOFFComdatConstants()) {
2107 // This creates comdat sections with the given symbol name, but unless
2108 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
2109 // will be created with a null storage class, which makes GNU binutils
2110 // error out.
2114 std::string COMDATSymName;
2115 if (Kind.isMergeableConst4()) {
2116 if (Alignment <= 4) {
2117 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2118 Alignment = Align(4);
2119 }
2120 } else if (Kind.isMergeableConst8()) {
2121 if (Alignment <= 8) {
2122 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2123 Alignment = Align(8);
2124 }
2125 } else if (Kind.isMergeableConst16()) {
2126 // FIXME: These may not be appropriate for non-x86 architectures.
2127 if (Alignment <= 16) {
2128 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
2129 Alignment = Align(16);
2130 }
2131 } else if (Kind.isMergeableConst32()) {
2132 if (Alignment <= 32) {
2133 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
2134 Alignment = Align(32);
2135 }
2136 }
2137
2138 if (!COMDATSymName.empty())
2139 return getContext().getCOFFSection(".rdata", Characteristics,
2140 COMDATSymName,
2142 }
2143
2145 Alignment);
2146}
2147
2148//===----------------------------------------------------------------------===//
2149// Wasm
2150//===----------------------------------------------------------------------===//
2151
2152static const Comdat *getWasmComdat(const GlobalValue *GV) {
2153 const Comdat *C = GV->getComdat();
2154 if (!C)
2155 return nullptr;
2156
2157 if (C->getSelectionKind() != Comdat::Any)
2158 report_fatal_error("WebAssembly COMDATs only support "
2159 "SelectionKind::Any, '" + C->getName() + "' cannot be "
2160 "lowered.");
2161
2162 return C;
2163}
2164
2165static unsigned getWasmSectionFlags(SectionKind K, bool Retain) {
2166 unsigned Flags = 0;
2167
2168 if (K.isThreadLocal())
2169 Flags |= wasm::WASM_SEG_FLAG_TLS;
2170
2171 if (K.isMergeableCString())
2173
2174 if (Retain)
2176
2177 // TODO(sbc): Add suport for K.isMergeableConst()
2178
2179 return Flags;
2180}
2181
2184 collectUsedGlobalVariables(M, Vec, false);
2185 for (GlobalValue *GV : Vec)
2186 if (auto *GO = dyn_cast<GlobalObject>(GV))
2187 Used.insert(GO);
2188}
2189
2191 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2192 // We don't support explict section names for functions in the wasm object
2193 // format. Each function has to be in its own unique section.
2194 if (isa<Function>(GO)) {
2195 return SelectSectionForGlobal(GO, Kind, TM);
2196 }
2197
2198 StringRef Name = GO->getSection();
2199
2200 // Certain data sections we treat as named custom sections rather than
2201 // segments within the data section.
2202 // This could be avoided if all data segements (the wasm sense) were
2203 // represented as their own sections (in the llvm sense).
2204 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
2205 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::Wasm,
2206 /*AddSegmentInfo=*/false) ||
2208 /*AddSegmentInfo=*/false) ||
2209 Name == ".llvmbc" || Name == ".llvmcmd")
2210 Kind = SectionKind::getMetadata();
2211
2212 StringRef Group = "";
2213 if (const Comdat *C = getWasmComdat(GO)) {
2214 Group = C->getName();
2215 }
2216
2217 unsigned Flags = getWasmSectionFlags(Kind, Used.count(GO));
2219 Name, Kind, Flags, Group, MCContext::GenericSectionID);
2220
2221 return Section;
2222}
2223
2224static MCSectionWasm *
2226 SectionKind Kind, Mangler &Mang,
2227 const TargetMachine &TM, bool EmitUniqueSection,
2228 unsigned *NextUniqueID, bool Retain) {
2229 StringRef Group = "";
2230 if (const Comdat *C = getWasmComdat(GO)) {
2231 Group = C->getName();
2232 }
2233
2234 bool UniqueSectionNames = TM.getUniqueSectionNames();
2235 SmallString<128> Name = getSectionPrefixForGlobal(Kind, /*IsLarge=*/false);
2236
2237 if (const auto *F = dyn_cast<Function>(GO)) {
2238 const auto &OptionalPrefix = F->getSectionPrefix();
2239 if (OptionalPrefix)
2240 raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2241 }
2242
2243 if (EmitUniqueSection && UniqueSectionNames) {
2244 Name.push_back('.');
2245 TM.getNameWithPrefix(Name, GO, Mang, true);
2246 }
2247 unsigned UniqueID = MCContext::GenericSectionID;
2248 if (EmitUniqueSection && !UniqueSectionNames) {
2249 UniqueID = *NextUniqueID;
2250 (*NextUniqueID)++;
2251 }
2252
2253 unsigned Flags = getWasmSectionFlags(Kind, Retain);
2254 return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2255}
2256
2258 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2259
2260 if (Kind.isCommon())
2261 report_fatal_error("mergable sections not supported yet on wasm");
2262
2263 // If we have -ffunction-section or -fdata-section then we should emit the
2264 // global value to a uniqued section specifically for it.
2265 bool EmitUniqueSection = false;
2266 if (Kind.isText())
2267 EmitUniqueSection = TM.getFunctionSections();
2268 else
2269 EmitUniqueSection = TM.getDataSections();
2270 EmitUniqueSection |= GO->hasComdat();
2271 bool Retain = Used.count(GO);
2272 EmitUniqueSection |= Retain;
2273
2274 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2275 EmitUniqueSection, &NextUniqueID, Retain);
2276}
2277
2279 bool UsesLabelDifference, const Function &F) const {
2280 // We can always create relative relocations, so use another section
2281 // that can be marked non-executable.
2282 return false;
2283}
2284
2286 const GlobalValue *LHS, const GlobalValue *RHS,
2287 const TargetMachine &TM) const {
2288 // We may only use a PLT-relative relocation to refer to unnamed_addr
2289 // functions.
2290 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2291 return nullptr;
2292
2293 // Basic correctness checks.
2294 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2295 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2296 RHS->isThreadLocal())
2297 return nullptr;
2298
2301 getContext()),
2303}
2304
2308
2309 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2310 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2312}
2313
2315 unsigned Priority, const MCSymbol *KeySym) const {
2316 return Priority == UINT16_MAX ?
2318 getContext().getWasmSection(".init_array." + utostr(Priority),
2320}
2321
2323 unsigned Priority, const MCSymbol *KeySym) const {
2324 report_fatal_error("@llvm.global_dtors should have been lowered already");
2325}
2326
2327//===----------------------------------------------------------------------===//
2328// XCOFF
2329//===----------------------------------------------------------------------===//
2331 const MachineFunction *MF) {
2332 if (!MF->getLandingPads().empty())
2333 return true;
2334
2335 const Function &F = MF->getFunction();
2336 if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2337 return false;
2338
2339 const GlobalValue *Per =
2340 dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2341 assert(Per && "Personality routine is not a GlobalValue type.");
2343 return false;
2344
2345 return true;
2346}
2347
2349 const MachineFunction *MF) {
2350 const Function &F = MF->getFunction();
2351 if (!F.hasStackProtectorFnAttr())
2352 return false;
2353 // FIXME: check presence of canary word
2354 // There are cases that the stack protectors are not really inserted even if
2355 // the attributes are on.
2356 return true;
2357}
2358
2359MCSymbol *
2361 MCSymbol *EHInfoSym = MF->getContext().getOrCreateSymbol(
2362 "__ehinfo." + Twine(MF->getFunctionNumber()));
2363 cast<MCSymbolXCOFF>(EHInfoSym)->setEHInfo();
2364 return EHInfoSym;
2365}
2366
2367MCSymbol *
2369 const TargetMachine &TM) const {
2370 // We always use a qualname symbol for a GV that represents
2371 // a declaration, a function descriptor, or a common symbol.
2372 // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2373 // also return a qualname so that a label symbol could be avoided.
2374 // It is inherently ambiguous when the GO represents the address of a
2375 // function, as the GO could either represent a function descriptor or a
2376 // function entry point. We choose to always return a function descriptor
2377 // here.
2378 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2379 if (GO->isDeclarationForLinker())
2380 return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
2381 ->getQualNameSymbol();
2382
2383 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2384 if (GVar->hasAttribute("toc-data"))
2385 return cast<MCSectionXCOFF>(
2387 ->getQualNameSymbol();
2388
2389 SectionKind GOKind = getKindForGlobal(GO, TM);
2390 if (GOKind.isText())
2391 return cast<MCSectionXCOFF>(
2392 getSectionForFunctionDescriptor(cast<Function>(GO), TM))
2393 ->getQualNameSymbol();
2394 if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2395 GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
2396 return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
2397 ->getQualNameSymbol();
2398 }
2399
2400 // For all other cases, fall back to getSymbol to return the unqualified name.
2401 return nullptr;
2402}
2403
2405 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2406 if (!GO->hasSection())
2407 report_fatal_error("#pragma clang section is not yet supported");
2408
2410
2411 // Handle the XCOFF::TD case first, then deal with the rest.
2412 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2413 if (GVar->hasAttribute("toc-data"))
2414 return getContext().getXCOFFSection(
2415 SectionName, Kind,
2417 /* MultiSymbolsAllowed*/ true);
2418
2419 XCOFF::StorageMappingClass MappingClass;
2420 if (Kind.isText())
2421 MappingClass = XCOFF::XMC_PR;
2422 else if (Kind.isData() || Kind.isBSS())
2423 MappingClass = XCOFF::XMC_RW;
2424 else if (Kind.isReadOnlyWithRel())
2425 MappingClass =
2427 else if (Kind.isReadOnly())
2428 MappingClass = XCOFF::XMC_RO;
2429 else
2430 report_fatal_error("XCOFF other section types not yet implemented.");
2431
2432 return getContext().getXCOFFSection(
2433 SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2434 /* MultiSymbolsAllowed*/ true);
2435}
2436
2438 const GlobalObject *GO, const TargetMachine &TM) const {
2440 "Tried to get ER section for a defined global.");
2441
2444
2445 // AIX TLS local-dynamic does not need the external reference for the
2446 // "_$TLSML" symbol.
2448 GO->hasName() && GO->getName() == "_$TLSML") {
2449 return getContext().getXCOFFSection(
2452 }
2453
2455 isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
2456 if (GO->isThreadLocal())
2457 SMC = XCOFF::XMC_UL;
2458
2459 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2460 if (GVar->hasAttribute("toc-data"))
2461 SMC = XCOFF::XMC_TD;
2462
2463 // Externals go into a csect of type ER.
2464 return getContext().getXCOFFSection(
2467}
2468
2470 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2471 // Handle the XCOFF::TD case first, then deal with the rest.
2472 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2473 if (GVar->hasAttribute("toc-data")) {
2476 XCOFF::SymbolType symType =
2478 return getContext().getXCOFFSection(
2479 Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, symType),
2480 /* MultiSymbolsAllowed*/ true);
2481 }
2482
2483 // Common symbols go into a csect with matching name which will get mapped
2484 // into the .bss section.
2485 // Zero-initialized local TLS symbols go into a csect with matching name which
2486 // will get mapped into the .tbss section.
2487 if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2490 XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2491 : Kind.isCommon() ? XCOFF::XMC_RW
2492 : XCOFF::XMC_UL;
2493 return getContext().getXCOFFSection(
2495 }
2496
2497 if (Kind.isText()) {
2498 if (TM.getFunctionSections()) {
2499 return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2500 ->getRepresentedCsect();
2501 }
2502 return TextSection;
2503 }
2504
2505 if (TM.Options.XCOFFReadOnlyPointers && Kind.isReadOnlyWithRel()) {
2506 if (!TM.getDataSections())
2508 "ReadOnlyPointers is supported only if data sections is turned on");
2509
2512 return getContext().getXCOFFSection(
2515 }
2516
2517 // For BSS kind, zero initialized data must be emitted to the .data section
2518 // because external linkage control sections that get mapped to the .bss
2519 // section will be linked as tentative defintions, which is only appropriate
2520 // for SectionKind::Common.
2521 if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2522 if (TM.getDataSections()) {
2525 return getContext().getXCOFFSection(
2528 }
2529 return DataSection;
2530 }
2531
2532 if (Kind.isReadOnly()) {
2533 if (TM.getDataSections()) {
2536 return getContext().getXCOFFSection(
2539 }
2540 return ReadOnlySection;
2541 }
2542
2543 // External/weak TLS data and initialized local TLS data are not eligible
2544 // to be put into common csect. If data sections are enabled, thread
2545 // data are emitted into separate sections. Otherwise, thread data
2546 // are emitted into the .tdata section.
2547 if (Kind.isThreadLocal()) {
2548 if (TM.getDataSections()) {
2551 return getContext().getXCOFFSection(
2553 }
2554 return TLSDataSection;
2555 }
2556
2557 report_fatal_error("XCOFF other section types not yet implemented.");
2558}
2559
2561 const Function &F, const TargetMachine &TM) const {
2562 assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2563
2564 if (!TM.getFunctionSections())
2565 return ReadOnlySection;
2566
2567 // If the function can be removed, produce a unique section so that
2568 // the table doesn't prevent the removal.
2569 SmallString<128> NameStr(".rodata.jmp..");
2570 getNameWithPrefix(NameStr, &F, TM);
2571 return getContext().getXCOFFSection(
2572 NameStr, SectionKind::getReadOnly(),
2574}
2575
2577 bool UsesLabelDifference, const Function &F) const {
2578 return false;
2579}
2580
2581/// Given a mergeable constant with the specified size and relocation
2582/// information, return a section that it should be placed in.
2584 const DataLayout &DL, SectionKind Kind, const Constant *C,
2585 Align &Alignment) const {
2586 // TODO: Enable emiting constant pool to unique sections when we support it.
2587 if (Alignment > Align(16))
2588 report_fatal_error("Alignments greater than 16 not yet supported.");
2589
2590 if (Alignment == Align(8)) {
2591 assert(ReadOnly8Section && "Section should always be initialized.");
2592 return ReadOnly8Section;
2593 }
2594
2595 if (Alignment == Align(16)) {
2596 assert(ReadOnly16Section && "Section should always be initialized.");
2597 return ReadOnly16Section;
2598 }
2599
2600 return ReadOnlySection;
2601}
2602
2604 const TargetMachine &TgtM) {
2611 LSDAEncoding = 0;
2613
2614 // AIX debug for thread local location is not ready. And for integrated as
2615 // mode, the relocatable address for the thread local variable will cause
2616 // linker error. So disable the location attribute generation for thread local
2617 // variables for now.
2618 // FIXME: when TLS debug on AIX is ready, remove this setting.
2620}
2621
2623 unsigned Priority, const MCSymbol *KeySym) const {
2624 report_fatal_error("no static constructor section on AIX");
2625}
2626
2628 unsigned Priority, const MCSymbol *KeySym) const {
2629 report_fatal_error("no static destructor section on AIX");
2630}
2631
2633 const GlobalValue *LHS, const GlobalValue *RHS,
2634 const TargetMachine &TM) const {
2635 /* Not implemented yet, but don't crash, return nullptr. */
2636 return nullptr;
2637}
2638
2641 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2642
2643 switch (GV->getLinkage()) {
2646 return XCOFF::C_HIDEXT;
2650 return XCOFF::C_EXT;
2656 return XCOFF::C_WEAKEXT;
2659 "There is no mapping that implements AppendingLinkage for XCOFF.");
2660 }
2661 llvm_unreachable("Unknown linkage type!");
2662}
2663
2665 const GlobalValue *Func, const TargetMachine &TM) const {
2666 assert((isa<Function>(Func) ||
2667 (isa<GlobalAlias>(Func) &&
2668 isa_and_nonnull<Function>(
2669 cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2670 "Func must be a function or an alias which has a function as base "
2671 "object.");
2672
2673 SmallString<128> NameStr;
2674 NameStr.push_back('.');
2675 getNameWithPrefix(NameStr, Func, TM);
2676
2677 // When -function-sections is enabled and explicit section is not specified,
2678 // it's not necessary to emit function entry point label any more. We will use
2679 // function entry point csect instead. And for function delcarations, the
2680 // undefined symbols gets treated as csect with XTY_ER property.
2681 if (((TM.getFunctionSections() && !Func->hasSection()) ||
2682 Func->isDeclarationForLinker()) &&
2683 isa<Function>(Func)) {
2684 return getContext()
2686 NameStr, SectionKind::getText(),
2687 XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclarationForLinker()
2689 : XCOFF::XTY_SD))
2691 }
2692
2693 return getContext().getOrCreateSymbol(NameStr);
2694}
2695
2697 const Function *F, const TargetMachine &TM) const {
2698 SmallString<128> NameStr;
2699 getNameWithPrefix(NameStr, F, TM);
2700 return getContext().getXCOFFSection(
2701 NameStr, SectionKind::getData(),
2703}
2704
2706 const MCSymbol *Sym, const TargetMachine &TM) const {
2707 const XCOFF::StorageMappingClass SMC = [](const MCSymbol *Sym,
2708 const TargetMachine &TM) {
2709 const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(Sym);
2710
2711 // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC,
2712 // otherwise the AIX assembler will complain.
2713 if (XSym->getSymbolTableName() == "_$TLSML")
2714 return XCOFF::XMC_TC;
2715
2716 // Use large code model toc entries for ehinfo symbols as they are
2717 // never referenced directly. The runtime loads their TOC entry
2718 // addresses from the trace-back table.
2719 if (XSym->isEHInfo())
2720 return XCOFF::XMC_TE;
2721
2722 // If the symbol does not have a code model specified use the module value.
2723 if (!XSym->hasPerSymbolCodeModel())
2725 : XCOFF::XMC_TC;
2726
2729 : XCOFF::XMC_TC;
2730 }(Sym, TM);
2731
2732 return getContext().getXCOFFSection(
2733 cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
2735}
2736
2738 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2739 auto *LSDA = cast<MCSectionXCOFF>(LSDASection);
2740 if (TM.getFunctionSections()) {
2741 // If option -ffunction-sections is on, append the function name to the
2742 // name of the LSDA csect so that each function has its own LSDA csect.
2743 // This helps the linker to garbage-collect EH info of unused functions.
2744 SmallString<128> NameStr = LSDA->getName();
2745 raw_svector_ostream(NameStr) << '.' << F.getName();
2746 LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
2747 LSDA->getCsectProp());
2748 }
2749 return LSDA;
2750}
2751//===----------------------------------------------------------------------===//
2752// GOFF
2753//===----------------------------------------------------------------------===//
2755
2757 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2758 return SelectSectionForGlobal(GO, Kind, TM);
2759}
2760
2762 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2763 std::string Name = ".gcc_exception_table." + F.getName().str();
2764 return getContext().getGOFFSection(Name, SectionKind::getData(), nullptr, 0);
2765}
2766
2768 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2769 auto *Symbol = TM.getSymbol(GO);
2770 if (Kind.isBSS())
2771 return getContext().getGOFFSection(Symbol->getName(), SectionKind::getBSS(),
2772 nullptr, 0);
2773
2775}
amdgpu AMDGPU DAG DAG Pattern Instruction Selection
static bool isThumb(const MCSubtargetInfo &STI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
COFFYAML::WeakExternalCharacteristics Characteristics
Definition: COFFYAML.cpp:350
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
Module.h This file contains the declarations for the Module class.
This file declares the MCSectionGOFF class, which contains all of the necessary machine code sections...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, const MCSection &Section)
static MCSection * selectExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM, MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID, bool Retain, bool ForceUnique)
static int getSelectionForCOFF(const GlobalValue *GV)
static MCSectionCOFF * getCOFFStaticStructorSection(MCContext &Ctx, const Triple &T, bool IsCtor, unsigned Priority, const MCSymbol *KeySym, MCSectionCOFF *Default)
static unsigned getEntrySizeForKind(SectionKind Kind)
static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, StringRef &Section)
static const GlobalValue * getComdatGVForCOFF(const GlobalValue *GV)
static unsigned getCOFFSectionFlags(SectionKind K, const TargetMachine &TM)
static StringRef handlePragmaClangSection(const GlobalObject *GO, SectionKind Kind)
static unsigned getELFSectionType(StringRef Name, SectionKind K)
static bool hasPrefix(StringRef SectionName, StringRef Prefix)
static MCSectionWasm * selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID, bool Retain)
static const MCSymbolELF * getLinkedToSymbol(const GlobalObject *GO, const TargetMachine &TM)
static unsigned calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName, SectionKind Kind, const TargetMachine &TM, MCContext &Ctx, Mangler &Mang, unsigned &Flags, unsigned &EntrySize, unsigned &NextUniqueID, const bool Retain, const bool ForceUnique)
Calculate an appropriate unique ID for a section, and update Flags, EntrySize and NextUniqueID where ...
static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K)
static const Comdat * getWasmComdat(const GlobalValue *GV)
static MCSectionELF * getStaticStructorSection(MCContext &Ctx, bool UseInitArray, bool IsCtor, unsigned Priority, const MCSymbol *KeySym)
static SmallString< 128 > getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, unsigned EntrySize, bool UniqueSectionName, const MachineJumpTableEntry *JTE)
static unsigned getWasmSectionFlags(SectionKind K, bool Retain)
static void checkMachOComdat(const GlobalValue *GV)
static std::string APIntToHexString(const APInt &AI)
static cl::opt< bool > JumpTableInFunctionSection("jumptable-in-function-section", cl::Hidden, cl::init(false), cl::desc("Putting Jump Table in function section"))
static StringRef getSectionPrefixForGlobal(SectionKind Kind, bool IsLarge)
Return the section prefix name used by options FunctionsSections and DataSections.
static std::string scalarConstantToHexString(const Constant *C)
static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind)
static const Comdat * getELFComdat(const GlobalValue *GV)
static MCSectionELF * selectELFSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol, const MachineJumpTableEntry *MJTE=nullptr)
static std::tuple< StringRef, bool, unsigned > getGlobalObjectInfo(const GlobalObject *GO, const TargetMachine &TM)
static unsigned getELFSectionFlags(SectionKind K)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1468
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:200
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
This is an important base class in LLVM.
Definition: Constant.h:42
Wrapper for a function that represents a value that functionally represents the original function.
Definition: Constants.h:941
GlobalValue * getGlobalValue() const
Definition: Constants.h:962
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:988
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:285
This is the base abstract class for diagnostic reporting in the backend.
Interface for custom diagnostic printing.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:117
bool hasComdat() const
Definition: GlobalObject.h:127
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:109
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:565
bool hasExternalLinkage() const
Definition: GlobalValue.h:512
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:264
LinkageTypes getLinkage() const
Definition: GlobalValue.h:547
bool hasLocalLinkage() const
Definition: GlobalValue.h:529
bool hasPrivateLinkage() const
Definition: GlobalValue.h:528
const Comdat * getComdat() const
Definition: Globals.cpp:199
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:272
bool isDeclarationForLinker() const
Definition: GlobalValue.h:619
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:657
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:400
const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition: Globals.cpp:130
bool hasCommonLinkage() const
Definition: GlobalValue.h:533
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:459
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
AttributeSet getAttributes() const
Return the attribute set for this global.
bool hasImplicitSection() const
Check if section name is present.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static bool isSectionAtomizableBySymbols(const MCSection &Section)
True if the section is atomized using the symbols in it.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
bool useIntegratedAssembler() const
Return true if assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:698
bool binutilsIsAtLeast(int Major, int Minor) const
Definition: MCAsmInfo.h:705
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:642
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:537
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:622
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:222
Context object for machine code objects.
Definition: MCContext.h:83
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:416
MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Definition: MCContext.cpp:488
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K, unsigned Flags=0)
Definition: MCContext.h:628
MCSectionELF * getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize=0)
Get a section with the provided group identifier.
Definition: MCContext.cpp:551
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:551
MCSectionXCOFF * getXCOFFSection(StringRef Section, SectionKind K, std::optional< XCOFF::CsectProperties > CsectProp=std::nullopt, bool MultiSymbolsAllowed=false, std::optional< XCOFF::DwarfSectionSubtypeFlags > DwarfSubtypeFlags=std::nullopt)
Definition: MCContext.cpp:805
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID)
Definition: MCContext.cpp:692
MCSectionGOFF * getGOFFSection(StringRef Section, SectionKind Kind, MCSection *Parent, uint32_t Subsection=0)
Definition: MCContext.cpp:674
bool isELFGenericMergeableSection(StringRef Name)
Definition: MCContext.cpp:661
std::optional< unsigned > getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags, unsigned EntrySize)
Return the unique ID of the section with the given name, flags and entry size, if it exists.
Definition: MCContext.cpp:667
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:412
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:212
bool isELFImplicitMergeableSectionNamePrefix(StringRef Name)
Definition: MCContext.cpp:656
MCSectionCOFF * getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID=GenericSectionID)
Gets or creates a section equivalent to Sec that is associated with the section containing KeySym.
Definition: MCContext.cpp:733
@ GenericSectionID
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:534
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
MCSection * TLSBSSSection
Section directive for Thread Local uninitialized data.
MCSection * MergeableConst16Section
MCSection * MergeableConst4Section
MCSection * TextSection
Section directive for standard text.
MCSection * ConstDataCoalSection
MCSection * ConstTextCoalSection
MCSection * TLSDataSection
Section directive for Thread Local data. ELF, MachO, COFF, and Wasm.
MCSection * MergeableConst8Section
MCSection * LSDASection
If exception handling is supported by the target, this is the section the Language Specific Data Area...
MCSection * FourByteConstantSection
MCSection * getDrectveSection() const
bool isPositionIndependent() const
MCSection * MergeableConst32Section
MCSection * SixteenByteConstantSection
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
MCSection * BSSSection
Section that is default initialized to zero.
MCSection * EightByteConstantSection
MCSection * getTextSection() const
MCContext & getContext() const
MCSection * DataSection
Section directive for standard data.
This represents a section on Windows.
Definition: MCSectionCOFF.h:27
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
This represents a section on a Mach-O system (used by Mac OS X).
static Error ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
unsigned getTypeAndAttributes() const
unsigned getStubSize() const
This represents a section on wasm.
Definition: MCSectionWasm.h:26
MCSymbolXCOFF * getQualNameSymbol() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
static constexpr unsigned NonUniqueID
Definition: MCSection.h:40
StringRef getName() const
Definition: MCSection.h:130
Streaming machine code generation interface.
Definition: MCStreamer.h:213
virtual void addBlankLine()
Emit a blank line to a .s file to pretty it up.
Definition: MCStreamer.h:397
virtual bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute)=0
Add the given Attribute to Symbol.
virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value)
Emit an ELF .size directive.
void emitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative=false)
Special case of EmitValue that avoids the client having to pass in a MCExpr for MCSymbols.
Definition: MCStreamer.cpp:183
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:420
virtual void emitValueToAlignment(Align Alignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
unsigned emitULEB128IntValue(uint64_t Value, unsigned PadTo=0)
Special case of EmitULEB128Value that avoids the client having to pass in a MCExpr for constant integ...
Definition: MCStreamer.cpp:161
virtual void emitLinkerOptions(ArrayRef< std::string > Kind)
Emit the given list Options of strings as linker options into the output.
Definition: MCStreamer.h:477
void emitInt64(uint64_t Value)
Definition: MCStreamer.h:740
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
void emitInt32(uint64_t Value)
Definition: MCStreamer.h:739
void emitInt8(uint64_t Value)
Definition: MCStreamer.h:737
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
const MCSymbol & getSymbol() const
Definition: MCExpr.h:411
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:398
StringRef getSymbolTableName() const
Definition: MCSymbolXCOFF.h:68
bool hasPerSymbolCodeModel() const
Definition: MCSymbolXCOFF.h:78
CodeModel getPerSymbolCodeModel() const
Definition: MCSymbolXCOFF.h:80
bool isEHInfo() const
Definition: MCSymbolXCOFF.h:74
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
This represents an "assembler immediate".
Definition: MCValue.h:36
int64_t getConstant() const
Definition: MCValue.h:43
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:45
Metadata node.
Definition: Metadata.h:1073
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1434
Metadata * get() const
Definition: Metadata.h:924
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isBeginSection() const
Returns true if this block begins any section.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MCContext & getContext() const
Function & getFunction()
Return the LLVM function that this machine code represents.
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
MCSection * getSection() const
Returns the Section this function belongs to.
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
StubValueTy & getGVStubEntry(MCSymbol *Sym)
PointerIntPair< MCSymbol *, 1, bool > StubValueTy
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets.
StubValueTy & getGVStubEntry(MCSymbol *Sym)
This class contains meta information specific to a module.
const Module * getModule() const
Ty & getObjFileInfo()
Keep track of various per-module pieces of information for backends that would like to do so.
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:121
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
@ Require
Adds a requirement that another module flag be present and have a specified value after linking is pe...
Definition: Module.h:131
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition: Module.h:279
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition: Module.cpp:170
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:294
A tuple of MDNodes.
Definition: Metadata.h:1737
PointerIntPair - This class implements a pair of a pointer and small integer.
PointerTy getPointer() const
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
static SectionKind getThreadData()
Definition: SectionKind.h:207
static SectionKind getMetadata()
Definition: SectionKind.h:188
bool isThreadBSSLocal() const
Definition: SectionKind.h:163
static SectionKind getText()
Definition: SectionKind.h:190
bool isBSSLocal() const
Definition: SectionKind.h:170
static SectionKind getData()
Definition: SectionKind.h:213
bool isText() const
Definition: SectionKind.h:127
static SectionKind getBSS()
Definition: SectionKind.h:209
static SectionKind getThreadBSS()
Definition: SectionKind.h:206
static SectionKind getReadOnly()
Definition: SectionKind.h:192
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:265
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a mergeable constant with the specified size and relocation information, return a section that ...
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit Obj-C garbage collection and linker options.
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
void emitLinkerDirectives(MCStreamer &Streamer, Module &M) const override
Process linker options metadata and emit platform-specific bits.
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
MCSection * getUniqueSectionForFunction(const Function &F, const TargetMachine &TM) const override
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit Obj-C garbage collection and linker options.
void emitLinkerDirectives(MCStreamer &Streamer, Module &M) const override
Process linker options metadata and emit platform-specific bits.
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, const MachineModuleInfo *MMI) const override
const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Return an MCExpr to use for a reference to the specified type info global variable from exception han...
void getModuleMetadata(Module &M) override
Get the module-level metadata that the platform cares about.
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
const MCExpr * lowerDSOLocalEquivalent(const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const override
MCSection * getSectionForCommandLines() const override
If supported, return the section to use for the llvm.commandline metadata.
MCSection * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
virtual void emitPersonalityValueImpl(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, const MachineModuleInfo *MMI) const
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
MCSection * getSectionForMachineBasicBlock(const Function &F, const MachineBasicBlock &MBB, const TargetMachine &TM) const override
Returns a unique section for the given machine basic block.
MCSymbolRefExpr::VariantKind PLTRelativeVariantKind
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
void emitLinkerDirectives(MCStreamer &Streamer, Module &M) const override
Process linker options metadata and emit platform-specific bits.
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Get MachO PC relative GOT entry relocation.
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit the module flags that specify the garbage collection information.
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForCommandLines() const override
If supported, return the section to use for the llvm.commandline metadata.
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
The mach-o version of this method defaults to returning a stub reference.
void getModuleMetadata(Module &M) override
Get the module-level metadata that the platform cares about.
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
static bool ShouldSetSSPCanaryBitInTB(const MachineFunction *MF)
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForTOCEntry(const MCSymbol *Sym, const TargetMachine &TM) const override
On targets that support TOC entries, return a section for the entry given the symbol it refers to.
MCSection * getSectionForExternalReference(const GlobalObject *GO, const TargetMachine &TM) const override
For external functions, this will always return a function descriptor csect.
MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const override
If supported, return the function entry point symbol.
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
static MCSymbol * getEHInfoTableSymbol(const MachineFunction *MF)
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
static XCOFF::StorageClass getStorageClassForGlobal(const GlobalValue *GV)
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getTargetSymbol(const GlobalValue *GV, const TargetMachine &TM) const override
For functions, this will always return a function descriptor symbol.
MCSection * getSectionForFunctionDescriptor(const Function *F, const TargetMachine &TM) const override
On targets that use separate function descriptor symbols, return a section for the descriptor given i...
static bool ShouldEmitEHBlock(const MachineFunction *MF)
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
For functions, this will return the LSDA section.
void emitCGProfileMetadata(MCStreamer &Streamer, Module &M) const
Emit Call Graph Profile metadata.
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
MCSection * StaticDtorSection
This section contains the static destructor pointer list.
unsigned PersonalityEncoding
PersonalityEncoding, LSDAEncoding, TTypeEncoding - Some encoding values for EH.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
bool supportDSOLocalEquivalentLowering() const
Target supports a native lowering of a dso_local_equivalent constant without needing to replace it wi...
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
This method must be called before any actual lowering is done.
MCSection * StaticCtorSection
This section contains the static constructor pointer list.
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Return an MCExpr to use for a reference to the specified global variable from exception handling info...
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:80
const Triple & getTargetTriple() const
bool getUniqueBasicBlockSectionNames() const
Return true if unique basic block section names must be generated.
bool getUniqueSectionNames() const
bool getEnableStaticDataPartitioning() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
TargetOptions Options
MCSymbol * getSymbol(const GlobalValue *GV) const
bool getDataSections() const
Return true if data objects should be emitted into their own section, corresponds to -fdata-sections.
CodeModel::Model getCodeModel() const
Returns the code model.
bool getFunctionSections() const
Return true if functions should be emitted into their own section, corresponding to -ffunction-sectio...
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
unsigned XCOFFReadOnlyPointers
When set to true, const objects with relocatable address values are put into the RO data section.
unsigned UseInitArray
UseInitArray - Use .init_array instead of .ctors for static constructors.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ loongarch32
Definition: Triple.h:61
@ aarch64_be
Definition: Triple.h:52
@ loongarch64
Definition: Triple.h:62
@ mips64el
Definition: Triple.h:67
@ aarch64_32
Definition: Triple.h:53
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:395
EnvironmentType getEnvironment() const
Get the parsed environment type of this triple.
Definition: Triple.h:412
bool isOSFreeBSD() const
Definition: Triple.h:614
bool isArch32Bit() const
Test whether the architecture is 32-bit.
Definition: Triple.cpp:1738
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
uint64_t getArrayNumElements() const
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1094
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SectionCharacteristics
Definition: COFF.h:297
@ IMAGE_SCN_LNK_REMOVE
Definition: COFF.h:307
@ IMAGE_SCN_CNT_CODE
Definition: COFF.h:302
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:335
@ IMAGE_SCN_MEM_EXECUTE
Definition: COFF.h:334
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:304
@ IMAGE_SCN_MEM_DISCARDABLE
Definition: COFF.h:330
@ IMAGE_SCN_MEM_16BIT
Definition: COFF.h:311
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:303
@ IMAGE_SCN_LNK_COMDAT
Definition: COFF.h:308
@ IMAGE_SCN_MEM_WRITE
Definition: COFF.h:336
@ IMAGE_COMDAT_SELECT_NODUPLICATES
Definition: COFF.h:454
@ IMAGE_COMDAT_SELECT_LARGEST
Definition: COFF.h:459
@ IMAGE_COMDAT_SELECT_SAME_SIZE
Definition: COFF.h:456
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition: COFF.h:458
@ IMAGE_COMDAT_SELECT_EXACT_MATCH
Definition: COFF.h:457
@ IMAGE_COMDAT_SELECT_ANY
Definition: COFF.h:455
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SHT_LLVM_DEPENDENT_LIBRARIES
Definition: ELF.h:1139
@ SHT_PROGBITS
Definition: ELF.h:1108
@ SHT_LLVM_LINKER_OPTIONS
Definition: ELF.h:1136
@ SHT_NOBITS
Definition: ELF.h:1115
@ SHT_LLVM_OFFLOADING
Definition: ELF.h:1149
@ SHT_LLVM_LTO
Definition: ELF.h:1150
@ SHT_PREINIT_ARRAY
Definition: ELF.h:1121
@ SHT_INIT_ARRAY
Definition: ELF.h:1119
@ SHT_NOTE
Definition: ELF.h:1114
@ SHT_FINI_ARRAY
Definition: ELF.h:1120
@ SHF_MERGE
Definition: ELF.h:1214
@ SHF_STRINGS
Definition: ELF.h:1217
@ SHF_EXCLUDE
Definition: ELF.h:1242
@ SHF_ALLOC
Definition: ELF.h:1208
@ SHF_LINK_ORDER
Definition: ELF.h:1223
@ SHF_GROUP
Definition: ELF.h:1230
@ SHF_SUNW_NODISCARD
Definition: ELF.h:1249
@ SHF_X86_64_LARGE
Definition: ELF.h:1271
@ SHF_GNU_RETAIN
Definition: ELF.h:1239
@ SHF_WRITE
Definition: ELF.h:1205
@ SHF_TLS
Definition: ELF.h:1233
@ SHF_ARM_PURECODE
Definition: ELF.h:1303
@ SHF_EXECINSTR
Definition: ELF.h:1211
@ S_MOD_TERM_FUNC_POINTERS
S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for termination.
Definition: MachO.h:150
@ S_MOD_INIT_FUNC_POINTERS
S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for initialization.
Definition: MachO.h:147
StorageClass
Definition: XCOFF.h:170
@ C_WEAKEXT
Definition: XCOFF.h:199
@ C_HIDEXT
Definition: XCOFF.h:206
StorageMappingClass
Storage Mapping Class definitions.
Definition: XCOFF.h:103
@ XMC_TE
Symbol mapped at the end of TOC.
Definition: XCOFF.h:128
@ XMC_DS
Descriptor csect.
Definition: XCOFF.h:121
@ XMC_RW
Read Write Data.
Definition: XCOFF.h:117
@ XMC_TL
Initialized thread-local variable.
Definition: XCOFF.h:126
@ XMC_RO
Read Only Constant.
Definition: XCOFF.h:106
@ XMC_UA
Unclassified - Treated as Read Write.
Definition: XCOFF.h:122
@ XMC_TD
Scalar data item in the TOC.
Definition: XCOFF.h:120
@ XMC_UL
Uninitialized thread-local variable.
Definition: XCOFF.h:127
@ XMC_PR
Program Code.
Definition: XCOFF.h:105
@ XMC_BS
BSS class (uninitialized static internal)
Definition: XCOFF.h:123
@ XMC_TC
General TOC item.
Definition: XCOFF.h:119
@ XTY_CM
Common csect definition. For uninitialized storage.
Definition: XCOFF.h:245
@ XTY_SD
Csect definition for initialized storage.
Definition: XCOFF.h:242
@ XTY_ER
External reference.
Definition: XCOFF.h:241
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ DW_EH_PE_datarel
Definition: Dwarf.h:860
@ DW_EH_PE_pcrel
Definition: Dwarf.h:858
@ DW_EH_PE_sdata4
Definition: Dwarf.h:855
@ DW_EH_PE_sdata8
Definition: Dwarf.h:856
@ DW_EH_PE_absptr
Definition: Dwarf.h:847
@ DW_EH_PE_udata4
Definition: Dwarf.h:851
@ DW_EH_PE_udata8
Definition: Dwarf.h:852
@ DW_EH_PE_indirect
Definition: Dwarf.h:863
@ WASM_SEG_FLAG_RETAIN
Definition: Wasm.h:227
@ WASM_SEG_FLAG_TLS
Definition: Wasm.h:226
@ WASM_SEG_FLAG_STRINGS
Definition: Wasm.h:225
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:236
@ DK_Lowering
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition: STLExtras.h:1952
std::string encodeBase64(InputBytes const &Bytes)
Definition: Base64.h:23
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
void emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &T, Mangler &M)
Definition: Mangler.cpp:280
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Error
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:214
const char * toString(DWARFSectionKind Kind)
cl::opt< std::string > BBSectionsColdTextPrefix
@ Default
The result values are uniform if and only if all operands are uniform.
@ MCSA_Weak
.weak
Definition: MCDirectives.h:45
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
Definition: MCDirectives.h:25
@ MCSA_Hidden
.hidden (ELF)
Definition: MCDirectives.h:33
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition: Module.cpp:865
constexpr const char * PseudoProbeDescMetadataName
Definition: PseudoProbe.h:25
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
static const MBBSectionID ExceptionSectionID
static const MBBSectionID ColdSectionID
MachineJumpTableEntry - One jump table in the jump table info.
MachineFunctionDataHotness Hotness
The hotness of MJTE is inferred from the hotness of the source basic block(s) that reference it.