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