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