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