LLVM 19.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
216 // FreeBSD must be explicit about the data size and using pcrel since it's
217 // assembler/linker won't do the automatic conversion that the Linux tools
218 // do.
222 }
223 break;
224 case Triple::ppc64:
225 case Triple::ppc64le:
231 break;
232 case Triple::sparcel:
233 case Triple::sparc:
234 if (isPositionIndependent()) {
240 } else {
244 }
246 break;
247 case Triple::riscv32:
248 case Triple::riscv64:
255 break;
256 case Triple::sparcv9:
258 if (isPositionIndependent()) {
263 } else {
266 }
267 break;
268 case Triple::systemz:
269 // All currently-defined code models guarantee that 4-byte PC-relative
270 // values will be in range.
271 if (isPositionIndependent()) {
277 } else {
281 }
282 break;
290 break;
291 default:
292 break;
293 }
294}
295
298 collectUsedGlobalVariables(M, Vec, false);
299 for (GlobalValue *GV : Vec)
300 if (auto *GO = dyn_cast<GlobalObject>(GV))
301 Used.insert(GO);
302}
303
305 Module &M) const {
306 auto &C = getContext();
307
308 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
309 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
311
312 Streamer.switchSection(S);
313
314 for (const auto *Operand : LinkerOptions->operands()) {
315 if (cast<MDNode>(Operand)->getNumOperands() != 2)
316 report_fatal_error("invalid llvm.linker.options");
317 for (const auto &Option : cast<MDNode>(Operand)->operands()) {
318 Streamer.emitBytes(cast<MDString>(Option)->getString());
319 Streamer.emitInt8(0);
320 }
321 }
322 }
323
324 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
325 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
327
328 Streamer.switchSection(S);
329
330 for (const auto *Operand : DependentLibraries->operands()) {
331 Streamer.emitBytes(
332 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
333 Streamer.emitInt8(0);
334 }
335 }
336
337 if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
338 // Emit a descriptor for every function including functions that have an
339 // available external linkage. We may not want this for imported functions
340 // that has code in another thinLTO module but we don't have a good way to
341 // tell them apart from inline functions defined in header files. Therefore
342 // we put each descriptor in a separate comdat section and rely on the
343 // linker to deduplicate.
344 for (const auto *Operand : FuncInfo->operands()) {
345 const auto *MD = cast<MDNode>(Operand);
346 auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
347 auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
348 auto *Name = cast<MDString>(MD->getOperand(2));
349 auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
350 TM->getFunctionSections() ? Name->getString() : StringRef());
351
352 Streamer.switchSection(S);
353 Streamer.emitInt64(GUID->getZExtValue());
354 Streamer.emitInt64(Hash->getZExtValue());
355 Streamer.emitULEB128IntValue(Name->getString().size());
356 Streamer.emitBytes(Name->getString());
357 }
358 }
359
360 if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
361 // Emit the metadata for llvm statistics into .llvm_stats section, which is
362 // formatted as a list of key/value pair, the value is base64 encoded.
363 auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
364 Streamer.switchSection(S);
365 for (const auto *Operand : LLVMStats->operands()) {
366 const auto *MD = cast<MDNode>(Operand);
367 assert(MD->getNumOperands() % 2 == 0 &&
368 ("Operand num should be even for a list of key/value pair"));
369 for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
370 // Encode the key string size.
371 auto *Key = cast<MDString>(MD->getOperand(I));
372 Streamer.emitULEB128IntValue(Key->getString().size());
373 Streamer.emitBytes(Key->getString());
374 // Encode the value into a Base64 string.
375 std::string Value = encodeBase64(
376 Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
377 ->getZExtValue())
378 .str());
379 Streamer.emitULEB128IntValue(Value.size());
380 Streamer.emitBytes(Value);
381 }
382 }
383 }
384
385 unsigned Version = 0;
386 unsigned Flags = 0;
387 StringRef Section;
388
389 GetObjCImageInfo(M, Version, Flags, Section);
390 if (!Section.empty()) {
391 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
392 Streamer.switchSection(S);
393 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
394 Streamer.emitInt32(Version);
395 Streamer.emitInt32(Flags);
396 Streamer.addBlankLine();
397 }
398
399 emitCGProfileMetadata(Streamer, M);
400}
401
403 const GlobalValue *GV, const TargetMachine &TM,
404 MachineModuleInfo *MMI) const {
405 unsigned Encoding = getPersonalityEncoding();
406 if ((Encoding & 0x80) == DW_EH_PE_indirect)
407 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
408 TM.getSymbol(GV)->getName());
409 if ((Encoding & 0x70) == DW_EH_PE_absptr)
410 return TM.getSymbol(GV);
411 report_fatal_error("We do not support this DWARF encoding yet!");
412}
413
415 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
416 SmallString<64> NameData("DW.ref.");
417 NameData += Sym->getName();
418 MCSymbolELF *Label =
419 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
420 Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
421 Streamer.emitSymbolAttribute(Label, MCSA_Weak);
422 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
423 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
424 ELF::SHT_PROGBITS, Flags, 0);
425 unsigned Size = DL.getPointerSize();
426 Streamer.switchSection(Sec);
427 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
430 Streamer.emitELFSize(Label, E);
431 Streamer.emitLabel(Label);
432
433 Streamer.emitSymbolValue(Sym, Size);
434}
435
437 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
438 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
439 if (Encoding & DW_EH_PE_indirect) {
441
442 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
443
444 // Add information about the stub reference to ELFMMI so that the stub
445 // gets emitted by the asmprinter.
447 if (!StubSym.getPointer()) {
448 MCSymbol *Sym = TM.getSymbol(GV);
450 }
451
454 Encoding & ~DW_EH_PE_indirect, Streamer);
455 }
456
458 MMI, Streamer);
459}
460
462 // N.B.: The defaults used in here are not the same ones used in MC.
463 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
464 // both gas and MC will produce a section with no flags. Given
465 // section(".eh_frame") gcc will produce:
466 //
467 // .section .eh_frame,"a",@progbits
468
469 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
470 /*AddSegmentInfo=*/false) ||
472 /*AddSegmentInfo=*/false) ||
474 /*AddSegmentInfo=*/false) ||
476 /*AddSegmentInfo=*/false) ||
477 Name == ".llvmbc" || Name == ".llvmcmd")
479
480 if (!Name.starts_with(".")) return K;
481
482 // Default implementation based on some magic section names.
483 if (Name == ".bss" || Name.starts_with(".bss.") ||
484 Name.starts_with(".gnu.linkonce.b.") ||
485 Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" ||
486 Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") ||
487 Name.starts_with(".llvm.linkonce.sb."))
488 return SectionKind::getBSS();
489
490 if (Name == ".tdata" || Name.starts_with(".tdata.") ||
491 Name.starts_with(".gnu.linkonce.td.") ||
492 Name.starts_with(".llvm.linkonce.td."))
494
495 if (Name == ".tbss" || Name.starts_with(".tbss.") ||
496 Name.starts_with(".gnu.linkonce.tb.") ||
497 Name.starts_with(".llvm.linkonce.tb."))
499
500 return K;
501}
502
504 return SectionName.consume_front(Prefix) &&
505 (SectionName.empty() || SectionName[0] == '.');
506}
507
509 // Use SHT_NOTE for section whose name starts with ".note" to allow
510 // emitting ELF notes from C variable declaration.
511 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
512 if (Name.starts_with(".note"))
513 return ELF::SHT_NOTE;
514
515 if (hasPrefix(Name, ".init_array"))
516 return ELF::SHT_INIT_ARRAY;
517
518 if (hasPrefix(Name, ".fini_array"))
519 return ELF::SHT_FINI_ARRAY;
520
521 if (hasPrefix(Name, ".preinit_array"))
523
524 if (hasPrefix(Name, ".llvm.offloading"))
526
527 if (K.isBSS() || K.isThreadBSS())
528 return ELF::SHT_NOBITS;
529
530 return ELF::SHT_PROGBITS;
531}
532
533static unsigned getELFSectionFlags(SectionKind K) {
534 unsigned Flags = 0;
535
536 if (!K.isMetadata() && !K.isExclude())
537 Flags |= ELF::SHF_ALLOC;
538
539 if (K.isExclude())
540 Flags |= ELF::SHF_EXCLUDE;
541
542 if (K.isText())
543 Flags |= ELF::SHF_EXECINSTR;
544
545 if (K.isExecuteOnly())
546 Flags |= ELF::SHF_ARM_PURECODE;
547
548 if (K.isWriteable())
549 Flags |= ELF::SHF_WRITE;
550
551 if (K.isThreadLocal())
552 Flags |= ELF::SHF_TLS;
553
554 if (K.isMergeableCString() || K.isMergeableConst())
555 Flags |= ELF::SHF_MERGE;
556
557 if (K.isMergeableCString())
558 Flags |= ELF::SHF_STRINGS;
559
560 return Flags;
561}
562
563static const Comdat *getELFComdat(const GlobalValue *GV) {
564 const Comdat *C = GV->getComdat();
565 if (!C)
566 return nullptr;
567
568 if (C->getSelectionKind() != Comdat::Any &&
569 C->getSelectionKind() != Comdat::NoDeduplicate)
570 report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
571 "SelectionKind::NoDeduplicate, '" +
572 C->getName() + "' cannot be lowered.");
573
574 return C;
575}
576
578 const TargetMachine &TM) {
579 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
580 if (!MD)
581 return nullptr;
582
583 auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get());
584 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
585 return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
586}
587
588static unsigned getEntrySizeForKind(SectionKind Kind) {
589 if (Kind.isMergeable1ByteCString())
590 return 1;
591 else if (Kind.isMergeable2ByteCString())
592 return 2;
593 else if (Kind.isMergeable4ByteCString())
594 return 4;
595 else if (Kind.isMergeableConst4())
596 return 4;
597 else if (Kind.isMergeableConst8())
598 return 8;
599 else if (Kind.isMergeableConst16())
600 return 16;
601 else if (Kind.isMergeableConst32())
602 return 32;
603 else {
604 // We shouldn't have mergeable C strings or mergeable constants that we
605 // didn't handle above.
606 assert(!Kind.isMergeableCString() && "unknown string width");
607 assert(!Kind.isMergeableConst() && "unknown data width");
608 return 0;
609 }
610}
611
612/// Return the section prefix name used by options FunctionsSections and
613/// DataSections.
615 if (Kind.isText())
616 return IsLarge ? ".ltext" : ".text";
617 if (Kind.isReadOnly())
618 return IsLarge ? ".lrodata" : ".rodata";
619 if (Kind.isBSS())
620 return IsLarge ? ".lbss" : ".bss";
621 if (Kind.isThreadData())
622 return ".tdata";
623 if (Kind.isThreadBSS())
624 return ".tbss";
625 if (Kind.isData())
626 return IsLarge ? ".ldata" : ".data";
627 if (Kind.isReadOnlyWithRel())
628 return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro";
629 llvm_unreachable("Unknown section kind");
630}
631
632static SmallString<128>
634 Mangler &Mang, const TargetMachine &TM,
635 unsigned EntrySize, bool UniqueSectionName) {
637 getSectionPrefixForGlobal(Kind, TM.isLargeGlobalValue(GO));
638 if (Kind.isMergeableCString()) {
639 // We also need alignment here.
640 // FIXME: this is getting the alignment of the character, not the
641 // alignment of the global!
642 Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
643 cast<GlobalVariable>(GO));
644
645 Name += ".str";
646 Name += utostr(EntrySize);
647 Name += ".";
648 Name += utostr(Alignment.value());
649 } else if (Kind.isMergeableConst()) {
650 Name += ".cst";
651 Name += utostr(EntrySize);
652 }
653
654 bool HasPrefix = false;
655 if (const auto *F = dyn_cast<Function>(GO)) {
656 if (std::optional<StringRef> Prefix = F->getSectionPrefix()) {
657 raw_svector_ostream(Name) << '.' << *Prefix;
658 HasPrefix = true;
659 }
660 }
661
662 if (UniqueSectionName) {
663 Name.push_back('.');
664 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
665 } else if (HasPrefix)
666 // For distinguishing between .text.${text-section-prefix}. (with trailing
667 // dot) and .text.${function-name}
668 Name.push_back('.');
669 return Name;
670}
671
672namespace {
673class LoweringDiagnosticInfo : public DiagnosticInfo {
674 const Twine &Msg;
675
676public:
677 LoweringDiagnosticInfo(const Twine &DiagMsg,
678 DiagnosticSeverity Severity = DS_Error)
679 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
680 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
681};
682}
683
684/// Calculate an appropriate unique ID for a section, and update Flags,
685/// EntrySize and NextUniqueID where appropriate.
686static unsigned
688 SectionKind Kind, const TargetMachine &TM,
689 MCContext &Ctx, Mangler &Mang, unsigned &Flags,
690 unsigned &EntrySize, unsigned &NextUniqueID,
691 const bool Retain, const bool ForceUnique) {
692 // Increment uniqueID if we are forced to emit a unique section.
693 // This works perfectly fine with section attribute or pragma section as the
694 // sections with the same name are grouped together by the assembler.
695 if (ForceUnique)
696 return NextUniqueID++;
697
698 // A section can have at most one associated section. Put each global with
699 // MD_associated in a unique section.
700 const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
701 if (Associated) {
702 Flags |= ELF::SHF_LINK_ORDER;
703 return NextUniqueID++;
704 }
705
706 if (Retain) {
707 if (TM.getTargetTriple().isOSSolaris())
709 else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
710 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36))
711 Flags |= ELF::SHF_GNU_RETAIN;
712 return NextUniqueID++;
713 }
714
715 // If two symbols with differing sizes end up in the same mergeable section
716 // that section can be assigned an incorrect entry size. To avoid this we
717 // usually put symbols of the same size into distinct mergeable sections with
718 // the same name. Doing so relies on the ",unique ," assembly feature. This
719 // feature is not avalible until bintuils version 2.35
720 // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
721 const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
722 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
723 if (!SupportsUnique) {
724 Flags &= ~ELF::SHF_MERGE;
725 EntrySize = 0;
727 }
728
729 const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
730 const bool SeenSectionNameBefore =
732 // If this is the first ocurrence of this section name, treat it as the
733 // generic section
734 if (!SymbolMergeable && !SeenSectionNameBefore) {
735 if (TM.getSeparateNamedSections())
736 return NextUniqueID++;
737 else
739 }
740
741 // Symbols must be placed into sections with compatible entry sizes. Generate
742 // unique sections for symbols that have not been assigned to compatible
743 // sections.
744 const auto PreviousID =
745 Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
746 if (PreviousID && (!TM.getSeparateNamedSections() ||
747 *PreviousID == MCContext::GenericSectionID))
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.starts_with(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
766static std::tuple<StringRef, bool, unsigned>
768 StringRef Group = "";
769 bool IsComdat = false;
770 unsigned Flags = 0;
771 if (const Comdat *C = getELFComdat(GO)) {
772 Flags |= ELF::SHF_GROUP;
773 Group = C->getName();
774 IsComdat = C->getSelectionKind() == Comdat::Any;
775 }
776 if (TM.isLargeGlobalValue(GO))
777 Flags |= ELF::SHF_X86_64_LARGE;
778 return {Group, IsComdat, Flags};
779}
780
782 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
783 MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
784 bool Retain, bool ForceUnique) {
786
787 // Check if '#pragma clang section' name is applicable.
788 // Note that pragma directive overrides -ffunction-section, -fdata-section
789 // and so section name is exactly as user specified and not uniqued.
790 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
791 if (GV && GV->hasImplicitSection()) {
792 auto Attrs = GV->getAttributes();
793 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
794 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
795 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
796 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
797 } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
798 SectionName = Attrs.getAttribute("relro-section").getValueAsString();
799 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
800 SectionName = Attrs.getAttribute("data-section").getValueAsString();
801 }
802 }
803
804 // Infer section flags from the section name if we can.
806
807 unsigned Flags = getELFSectionFlags(Kind);
808 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
809 Flags |= ExtraFlags;
810
811 unsigned EntrySize = getEntrySizeForKind(Kind);
812 const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
813 GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
814 Retain, ForceUnique);
815
816 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
817 MCSectionELF *Section = Ctx.getELFSection(
818 SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
819 Group, IsComdat, UniqueID, LinkedToSym);
820 // Make sure that we did not get some other section with incompatible sh_link.
821 // This should not be possible due to UniqueID code above.
822 assert(Section->getLinkedToSymbol() == LinkedToSym &&
823 "Associated symbol mismatch between sections");
824
825 if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
826 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
827 // If we are using GNU as before 2.35, then this symbol might have
828 // been placed in an incompatible mergeable section. Emit an error if this
829 // is the case to avoid creating broken output.
830 if ((Section->getFlags() & ELF::SHF_MERGE) &&
831 (Section->getEntrySize() != getEntrySizeForKind(Kind)))
832 GO->getContext().diagnose(LoweringDiagnosticInfo(
833 "Symbol '" + GO->getName() + "' from module '" +
834 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
835 "' required a section with entry-size=" +
836 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
837 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
838 ": Explicit assignment by pragma or attribute of an incompatible "
839 "symbol to this section?"));
840 }
841
842 return Section;
843}
844
846 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
848 NextUniqueID, Used.count(GO),
849 /* ForceUnique = */false);
850}
851
853 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
854 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
855 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
856
857 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
858 Flags |= ExtraFlags;
859
860 // Get the section entry size based on the kind.
861 unsigned EntrySize = getEntrySizeForKind(Kind);
862
863 bool UniqueSectionName = false;
864 unsigned UniqueID = MCContext::GenericSectionID;
865 if (EmitUniqueSection) {
866 if (TM.getUniqueSectionNames()) {
867 UniqueSectionName = true;
868 } else {
869 UniqueID = *NextUniqueID;
870 (*NextUniqueID)++;
871 }
872 }
874 GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
875
876 // Use 0 as the unique ID for execute-only text.
877 if (Kind.isExecuteOnly())
878 UniqueID = 0;
879 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
880 EntrySize, Group, IsComdat, UniqueID,
881 AssociatedSymbol);
882}
883
885 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
886 const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
887 unsigned Flags, unsigned *NextUniqueID) {
888 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
889 if (LinkedToSym) {
890 EmitUniqueSection = true;
891 Flags |= ELF::SHF_LINK_ORDER;
892 }
893 if (Retain) {
894 if (TM.getTargetTriple().isOSSolaris()) {
895 EmitUniqueSection = true;
897 } else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
898 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) {
899 EmitUniqueSection = true;
900 Flags |= ELF::SHF_GNU_RETAIN;
901 }
902 }
903
905 Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
906 NextUniqueID, LinkedToSym);
907 assert(Section->getLinkedToSymbol() == LinkedToSym);
908 return Section;
909}
910
912 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
913 unsigned Flags = getELFSectionFlags(Kind);
914
915 // If we have -ffunction-section or -fdata-section then we should emit the
916 // global value to a uniqued section specifically for it.
917 bool EmitUniqueSection = false;
918 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
919 if (Kind.isText())
920 EmitUniqueSection = TM.getFunctionSections();
921 else
922 EmitUniqueSection = TM.getDataSections();
923 }
924 EmitUniqueSection |= GO->hasComdat();
925 return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
926 Used.count(GO), EmitUniqueSection, Flags,
927 &NextUniqueID);
928}
929
931 const Function &F, const TargetMachine &TM) const {
933 unsigned Flags = getELFSectionFlags(Kind);
934 // If the function's section names is pre-determined via pragma or a
935 // section attribute, call selectExplicitSectionGlobal.
936 if (F.hasSection())
938 &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
939 Used.count(&F), /* ForceUnique = */true);
940 else
942 getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
943 /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
944}
945
947 const Function &F, const TargetMachine &TM) const {
948 // If the function can be removed, produce a unique section so that
949 // the table doesn't prevent the removal.
950 const Comdat *C = F.getComdat();
951 bool EmitUniqueSection = TM.getFunctionSections() || C;
952 if (!EmitUniqueSection)
953 return ReadOnlySection;
954
956 getMangler(), TM, EmitUniqueSection,
957 ELF::SHF_ALLOC, &NextUniqueID,
958 /* AssociatedSymbol */ nullptr);
959}
960
962 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
963 // If neither COMDAT nor function sections, use the monolithic LSDA section.
964 // Re-use this path if LSDASection is null as in the Arm EHABI.
965 if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
966 return LSDASection;
967
968 const auto *LSDA = cast<MCSectionELF>(LSDASection);
969 unsigned Flags = LSDA->getFlags();
970 const MCSymbolELF *LinkedToSym = nullptr;
971 StringRef Group;
972 bool IsComdat = false;
973 if (const Comdat *C = getELFComdat(&F)) {
974 Flags |= ELF::SHF_GROUP;
975 Group = C->getName();
976 IsComdat = C->getSelectionKind() == Comdat::Any;
977 }
978 // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
979 // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
980 if (TM.getFunctionSections() &&
981 (getContext().getAsmInfo()->useIntegratedAssembler() &&
982 getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
983 Flags |= ELF::SHF_LINK_ORDER;
984 LinkedToSym = cast<MCSymbolELF>(&FnSym);
985 }
986
987 // Append the function name as the suffix like GCC, assuming
988 // -funique-section-names applies to .gcc_except_table sections.
989 return getContext().getELFSection(
990 (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
991 : LSDA->getName()),
992 LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
993 LinkedToSym);
994}
995
997 bool UsesLabelDifference, const Function &F) const {
998 // We can always create relative relocations, so use another section
999 // that can be marked non-executable.
1000 return false;
1001}
1002
1003/// Given a mergeable constant with the specified size and relocation
1004/// information, return a section that it should be placed in.
1006 const DataLayout &DL, SectionKind Kind, const Constant *C,
1007 Align &Alignment) const {
1008 if (Kind.isMergeableConst4() && MergeableConst4Section)
1010 if (Kind.isMergeableConst8() && MergeableConst8Section)
1012 if (Kind.isMergeableConst16() && MergeableConst16Section)
1014 if (Kind.isMergeableConst32() && MergeableConst32Section)
1016 if (Kind.isReadOnly())
1017 return ReadOnlySection;
1018
1019 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
1020 return DataRelROSection;
1021}
1022
1023/// Returns a unique section for the given machine basic block.
1025 const Function &F, const MachineBasicBlock &MBB,
1026 const TargetMachine &TM) const {
1027 assert(MBB.isBeginSection() && "Basic block does not start a section!");
1028 unsigned UniqueID = MCContext::GenericSectionID;
1029
1030 // For cold sections use the .text.split. prefix along with the parent
1031 // function name. All cold blocks for the same function go to the same
1032 // section. Similarly all exception blocks are grouped by symbol name
1033 // under the .text.eh prefix. For regular sections, we either use a unique
1034 // name, or a unique ID for the section.
1036 StringRef FunctionSectionName = MBB.getParent()->getSection()->getName();
1037 if (FunctionSectionName == ".text" ||
1038 FunctionSectionName.starts_with(".text.")) {
1039 // Function is in a regular .text section.
1040 StringRef FunctionName = MBB.getParent()->getName();
1043 Name += FunctionName;
1045 Name += ".text.eh.";
1046 Name += FunctionName;
1047 } else {
1048 Name += FunctionSectionName;
1050 if (!Name.ends_with("."))
1051 Name += ".";
1052 Name += MBB.getSymbol()->getName();
1053 } else {
1054 UniqueID = NextUniqueID++;
1055 }
1056 }
1057 } else {
1058 // If the original function has a custom non-dot-text section, then emit
1059 // all basic block sections into that section too, each with a unique id.
1060 Name = FunctionSectionName;
1061 UniqueID = NextUniqueID++;
1062 }
1063
1064 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
1065 std::string GroupName;
1066 if (F.hasComdat()) {
1067 Flags |= ELF::SHF_GROUP;
1068 GroupName = F.getComdat()->getName().str();
1069 }
1071 0 /* Entry Size */, GroupName,
1072 F.hasComdat(), UniqueID, nullptr);
1073}
1074
1075static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1076 bool IsCtor, unsigned Priority,
1077 const MCSymbol *KeySym) {
1078 std::string Name;
1079 unsigned Type;
1080 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1081 StringRef Comdat = KeySym ? KeySym->getName() : "";
1082
1083 if (KeySym)
1084 Flags |= ELF::SHF_GROUP;
1085
1086 if (UseInitArray) {
1087 if (IsCtor) {
1089 Name = ".init_array";
1090 } else {
1092 Name = ".fini_array";
1093 }
1094 if (Priority != 65535) {
1095 Name += '.';
1096 Name += utostr(Priority);
1097 }
1098 } else {
1099 // The default scheme is .ctor / .dtor, so we have to invert the priority
1100 // numbering.
1101 if (IsCtor)
1102 Name = ".ctors";
1103 else
1104 Name = ".dtors";
1105 if (Priority != 65535)
1106 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1108 }
1109
1110 return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1111}
1112
1114 unsigned Priority, const MCSymbol *KeySym) const {
1115 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1116 KeySym);
1117}
1118
1120 unsigned Priority, const MCSymbol *KeySym) const {
1121 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1122 KeySym);
1123}
1124
1126 const GlobalValue *LHS, const GlobalValue *RHS,
1127 const TargetMachine &TM) const {
1128 // We may only use a PLT-relative relocation to refer to unnamed_addr
1129 // functions.
1130 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1131 return nullptr;
1132
1133 // Basic correctness checks.
1134 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1135 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1136 RHS->isThreadLocal())
1137 return nullptr;
1138
1141 getContext()),
1143}
1144
1146 const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1148
1149 const auto *GV = Equiv->getGlobalValue();
1150
1151 // A PLT entry is not needed for dso_local globals.
1152 if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1154
1156 getContext());
1157}
1158
1160 // Use ".GCC.command.line" since this feature is to support clang's
1161 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1162 // same name.
1163 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1165}
1166
1167void
1169 UseInitArray = UseInitArray_;
1170 MCContext &Ctx = getContext();
1171 if (!UseInitArray) {
1174
1177 return;
1178 }
1179
1184}
1185
1186//===----------------------------------------------------------------------===//
1187// MachO
1188//===----------------------------------------------------------------------===//
1189
1192}
1193
1195 const TargetMachine &TM) {
1198 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1200 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1202 } else {
1203 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1206 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1209 }
1210
1216}
1217
1219 unsigned Priority, const MCSymbol *KeySym) const {
1220 return StaticDtorSection;
1221 // In userspace, we lower global destructors via atexit(), but kernel/kext
1222 // environments do not provide this function so we still need to support the
1223 // legacy way here.
1224 // See the -disable-atexit-based-global-dtor-lowering CodeGen flag for more
1225 // context.
1226}
1227
1229 Module &M) const {
1230 // Emit the linker options if present.
1231 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1232 for (const auto *Option : LinkerOptions->operands()) {
1233 SmallVector<std::string, 4> StrOptions;
1234 for (const auto &Piece : cast<MDNode>(Option)->operands())
1235 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1236 Streamer.emitLinkerOptions(StrOptions);
1237 }
1238 }
1239
1240 unsigned VersionVal = 0;
1241 unsigned ImageInfoFlags = 0;
1242 StringRef SectionVal;
1243
1244 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1245 emitCGProfileMetadata(Streamer, M);
1246
1247 // The section is mandatory. If we don't have it, then we don't have GC info.
1248 if (SectionVal.empty())
1249 return;
1250
1251 StringRef Segment, Section;
1252 unsigned TAA = 0, StubSize = 0;
1253 bool TAAParsed;
1255 SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1256 // If invalid, report the error with report_fatal_error.
1257 report_fatal_error("Invalid section specifier '" + Section +
1258 "': " + toString(std::move(E)) + ".");
1259 }
1260
1261 // Get the section.
1263 Segment, Section, TAA, StubSize, SectionKind::getData());
1264 Streamer.switchSection(S);
1265 Streamer.emitLabel(getContext().
1266 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1267 Streamer.emitInt32(VersionVal);
1268 Streamer.emitInt32(ImageInfoFlags);
1269 Streamer.addBlankLine();
1270}
1271
1272static void checkMachOComdat(const GlobalValue *GV) {
1273 const Comdat *C = GV->getComdat();
1274 if (!C)
1275 return;
1276
1277 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1278 "' cannot be lowered.");
1279}
1280
1282 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1283
1285
1286 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
1287 if (GV && GV->hasImplicitSection()) {
1288 auto Attrs = GV->getAttributes();
1289 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
1290 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
1291 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
1292 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
1293 } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
1294 SectionName = Attrs.getAttribute("relro-section").getValueAsString();
1295 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
1296 SectionName = Attrs.getAttribute("data-section").getValueAsString();
1297 }
1298 }
1299
1300 // Parse the section specifier and create it if valid.
1301 StringRef Segment, Section;
1302 unsigned TAA = 0, StubSize = 0;
1303 bool TAAParsed;
1304
1305 checkMachOComdat(GO);
1306
1308 SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1309 // If invalid, report the error with report_fatal_error.
1310 report_fatal_error("Global variable '" + GO->getName() +
1311 "' has an invalid section specifier '" +
1312 GO->getSection() + "': " + toString(std::move(E)) + ".");
1313 }
1314
1315 // Get the section.
1316 MCSectionMachO *S =
1317 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1318
1319 // If TAA wasn't set by ParseSectionSpecifier() above,
1320 // use the value returned by getMachOSection() as a default.
1321 if (!TAAParsed)
1322 TAA = S->getTypeAndAttributes();
1323
1324 // Okay, now that we got the section, verify that the TAA & StubSize agree.
1325 // If the user declared multiple globals with different section flags, we need
1326 // to reject it here.
1327 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1328 // If invalid, report the error with report_fatal_error.
1329 report_fatal_error("Global variable '" + GO->getName() +
1330 "' section type or attributes does not match previous"
1331 " section specifier");
1332 }
1333
1334 return S;
1335}
1336
1338 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1339 checkMachOComdat(GO);
1340
1341 // Handle thread local data.
1342 if (Kind.isThreadBSS()) return TLSBSSSection;
1343 if (Kind.isThreadData()) return TLSDataSection;
1344
1345 if (Kind.isText())
1347
1348 // If this is weak/linkonce, put this in a coalescable section, either in text
1349 // or data depending on if it is writable.
1350 if (GO->isWeakForLinker()) {
1351 if (Kind.isReadOnly())
1352 return ConstTextCoalSection;
1353 if (Kind.isReadOnlyWithRel())
1354 return ConstDataCoalSection;
1355 return DataCoalSection;
1356 }
1357
1358 // FIXME: Alignment check should be handled by section classifier.
1359 if (Kind.isMergeable1ByteCString() &&
1361 cast<GlobalVariable>(GO)) < Align(32))
1362 return CStringSection;
1363
1364 // Do not put 16-bit arrays in the UString section if they have an
1365 // externally visible label, this runs into issues with certain linker
1366 // versions.
1367 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1369 cast<GlobalVariable>(GO)) < Align(32))
1370 return UStringSection;
1371
1372 // With MachO only variables whose corresponding symbol starts with 'l' or
1373 // 'L' can be merged, so we only try merging GVs with private linkage.
1374 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1375 if (Kind.isMergeableConst4())
1377 if (Kind.isMergeableConst8())
1379 if (Kind.isMergeableConst16())
1381 }
1382
1383 // Otherwise, if it is readonly, but not something we can specially optimize,
1384 // just drop it in .const.
1385 if (Kind.isReadOnly())
1386 return ReadOnlySection;
1387
1388 // If this is marked const, put it into a const section. But if the dynamic
1389 // linker needs to write to it, put it in the data segment.
1390 if (Kind.isReadOnlyWithRel())
1391 return ConstDataSection;
1392
1393 // Put zero initialized globals with strong external linkage in the
1394 // DATA, __common section with the .zerofill directive.
1395 if (Kind.isBSSExtern())
1396 return DataCommonSection;
1397
1398 // Put zero initialized globals with local linkage in __DATA,__bss directive
1399 // with the .zerofill directive (aka .lcomm).
1400 if (Kind.isBSSLocal())
1401 return DataBSSSection;
1402
1403 // Otherwise, just drop the variable in the normal data section.
1404 return DataSection;
1405}
1406
1408 const DataLayout &DL, SectionKind Kind, const Constant *C,
1409 Align &Alignment) const {
1410 // If this constant requires a relocation, we have to put it in the data
1411 // segment, not in the text segment.
1412 if (Kind.isData() || Kind.isReadOnlyWithRel())
1413 return ConstDataSection;
1414
1415 if (Kind.isMergeableConst4())
1417 if (Kind.isMergeableConst8())
1419 if (Kind.isMergeableConst16())
1421 return ReadOnlySection; // .const
1422}
1423
1425 return getContext().getMachOSection("__TEXT", "__command_line", 0,
1427}
1428
1430 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1431 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1432 // The mach-o version of this method defaults to returning a stub reference.
1433
1434 if (Encoding & DW_EH_PE_indirect) {
1435 MachineModuleInfoMachO &MachOMMI =
1437
1438 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1439
1440 // Add information about the stub reference to MachOMMI so that the stub
1441 // gets emitted by the asmprinter.
1442 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1443 if (!StubSym.getPointer()) {
1444 MCSymbol *Sym = TM.getSymbol(GV);
1446 }
1447
1450 Encoding & ~DW_EH_PE_indirect, Streamer);
1451 }
1452
1454 MMI, Streamer);
1455}
1456
1458 const GlobalValue *GV, const TargetMachine &TM,
1459 MachineModuleInfo *MMI) const {
1460 // The mach-o version of this method defaults to returning a stub reference.
1461 MachineModuleInfoMachO &MachOMMI =
1463
1464 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1465
1466 // Add information about the stub reference to MachOMMI so that the stub
1467 // gets emitted by the asmprinter.
1468 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1469 if (!StubSym.getPointer()) {
1470 MCSymbol *Sym = TM.getSymbol(GV);
1472 }
1473
1474 return SSym;
1475}
1476
1478 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1479 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1480 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1481 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1482 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1483 // computation of deltas to final external symbols. Example:
1484 //
1485 // _extgotequiv:
1486 // .long _extfoo
1487 //
1488 // _delta:
1489 // .long _extgotequiv-_delta
1490 //
1491 // is transformed to:
1492 //
1493 // _delta:
1494 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1495 //
1496 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1497 // L_extfoo$non_lazy_ptr:
1498 // .indirect_symbol _extfoo
1499 // .long 0
1500 //
1501 // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1502 // may point to both local (same translation unit) and global (other
1503 // translation units) symbols. Example:
1504 //
1505 // .section __DATA,__pointers,non_lazy_symbol_pointers
1506 // L1:
1507 // .indirect_symbol _myGlobal
1508 // .long 0
1509 // L2:
1510 // .indirect_symbol _myLocal
1511 // .long _myLocal
1512 //
1513 // If the symbol is local, instead of the symbol's index, the assembler
1514 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1515 // Then the linker will notice the constant in the table and will look at the
1516 // content of the symbol.
1517 MachineModuleInfoMachO &MachOMMI =
1519 MCContext &Ctx = getContext();
1520
1521 // The offset must consider the original displacement from the base symbol
1522 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1523 Offset = -MV.getConstant();
1524 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1525
1526 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1527 // non_lazy_ptr stubs.
1529 StringRef Suffix = "$non_lazy_ptr";
1531 Name += Sym->getName();
1532 Name += Suffix;
1533 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1534
1535 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1536
1537 if (!StubSym.getPointer())
1538 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1539 !GV->hasLocalLinkage());
1540
1541 const MCExpr *BSymExpr =
1543 const MCExpr *LHS =
1545
1546 if (!Offset)
1547 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1548
1549 const MCExpr *RHS =
1551 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1552}
1553
1554static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1555 const MCSection &Section) {
1556 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1557 return true;
1558
1559 // FIXME: we should be able to use private labels for sections that can't be
1560 // dead-stripped (there's no issue with blocking atomization there), but `ld
1561 // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1562 // we don't allow it.
1563 return false;
1564}
1565
1567 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1568 const TargetMachine &TM) const {
1569 bool CannotUsePrivateLabel = true;
1570 if (auto *GO = GV->getAliaseeObject()) {
1572 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1573 CannotUsePrivateLabel =
1574 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1575 }
1576 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1577}
1578
1579//===----------------------------------------------------------------------===//
1580// COFF
1581//===----------------------------------------------------------------------===//
1582
1583static unsigned
1585 unsigned Flags = 0;
1586 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1587
1588 if (K.isMetadata())
1589 Flags |=
1591 else if (K.isExclude())
1592 Flags |=
1594 else if (K.isText())
1595 Flags |=
1600 else if (K.isBSS())
1601 Flags |=
1605 else if (K.isThreadLocal())
1606 Flags |=
1610 else if (K.isReadOnly() || K.isReadOnlyWithRel())
1611 Flags |=
1614 else if (K.isWriteable())
1615 Flags |=
1619
1620 return Flags;
1621}
1622
1624 const Comdat *C = GV->getComdat();
1625 assert(C && "expected GV to have a Comdat!");
1626
1627 StringRef ComdatGVName = C->getName();
1628 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1629 if (!ComdatGV)
1630 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1631 "' does not exist.");
1632
1633 if (ComdatGV->getComdat() != C)
1634 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1635 "' is not a key for its COMDAT.");
1636
1637 return ComdatGV;
1638}
1639
1640static int getSelectionForCOFF(const GlobalValue *GV) {
1641 if (const Comdat *C = GV->getComdat()) {
1642 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1643 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1644 ComdatKey = GA->getAliaseeObject();
1645 if (ComdatKey == GV) {
1646 switch (C->getSelectionKind()) {
1647 case Comdat::Any:
1649 case Comdat::ExactMatch:
1651 case Comdat::Largest:
1655 case Comdat::SameSize:
1657 }
1658 } else {
1660 }
1661 }
1662 return 0;
1663}
1664
1666 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1667 StringRef Name = GO->getSection();
1668 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::COFF,
1669 /*AddSegmentInfo=*/false) ||
1671 /*AddSegmentInfo=*/false) ||
1672 Name == getInstrProfSectionName(IPSK_covdata, Triple::COFF,
1673 /*AddSegmentInfo=*/false) ||
1674 Name == getInstrProfSectionName(IPSK_covname, Triple::COFF,
1675 /*AddSegmentInfo=*/false))
1676 Kind = SectionKind::getMetadata();
1677 int Selection = 0;
1678 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1679 StringRef COMDATSymName = "";
1680 if (GO->hasComdat()) {
1682 const GlobalValue *ComdatGV;
1684 ComdatGV = getComdatGVForCOFF(GO);
1685 else
1686 ComdatGV = GO;
1687
1688 if (!ComdatGV->hasPrivateLinkage()) {
1689 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1690 COMDATSymName = Sym->getName();
1692 } else {
1693 Selection = 0;
1694 }
1695 }
1696
1697 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1698 Selection);
1699}
1700
1702 if (Kind.isText())
1703 return ".text";
1704 if (Kind.isBSS())
1705 return ".bss";
1706 if (Kind.isThreadLocal())
1707 return ".tls$";
1708 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1709 return ".rdata";
1710 return ".data";
1711}
1712
1714 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1715 // If we have -ffunction-sections then we should emit the global value to a
1716 // uniqued section specifically for it.
1717 bool EmitUniquedSection;
1718 if (Kind.isText())
1719 EmitUniquedSection = TM.getFunctionSections();
1720 else
1721 EmitUniquedSection = TM.getDataSections();
1722
1723 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1725
1726 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1727
1730 if (!Selection)
1732 const GlobalValue *ComdatGV;
1733 if (GO->hasComdat())
1734 ComdatGV = getComdatGVForCOFF(GO);
1735 else
1736 ComdatGV = GO;
1737
1738 unsigned UniqueID = MCContext::GenericSectionID;
1739 if (EmitUniquedSection)
1740 UniqueID = NextUniqueID++;
1741
1742 if (!ComdatGV->hasPrivateLinkage()) {
1743 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1744 StringRef COMDATSymName = Sym->getName();
1745
1746 if (const auto *F = dyn_cast<Function>(GO))
1747 if (std::optional<StringRef> Prefix = F->getSectionPrefix())
1748 raw_svector_ostream(Name) << '$' << *Prefix;
1749
1750 // Append "$symbol" to the section name *before* IR-level mangling is
1751 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1752 // COFF linker will not properly handle comdats otherwise.
1753 if (getContext().getTargetTriple().isWindowsGNUEnvironment())
1754 raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1755
1757 COMDATSymName, Selection, UniqueID);
1758 } else {
1759 SmallString<256> TmpData;
1760 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1761 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1762 Selection, UniqueID);
1763 }
1764 }
1765
1766 if (Kind.isText())
1767 return TextSection;
1768
1769 if (Kind.isThreadLocal())
1770 return TLSDataSection;
1771
1772 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1773 return ReadOnlySection;
1774
1775 // Note: we claim that common symbols are put in BSSSection, but they are
1776 // really emitted with the magic .comm directive, which creates a symbol table
1777 // entry but not a section.
1778 if (Kind.isBSS() || Kind.isCommon())
1779 return BSSSection;
1780
1781 return DataSection;
1782}
1783
1785 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1786 const TargetMachine &TM) const {
1787 bool CannotUsePrivateLabel = false;
1788 if (GV->hasPrivateLinkage() &&
1789 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1790 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1791 CannotUsePrivateLabel = true;
1792
1793 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1794}
1795
1797 const Function &F, const TargetMachine &TM) const {
1798 // If the function can be removed, produce a unique section so that
1799 // the table doesn't prevent the removal.
1800 const Comdat *C = F.getComdat();
1801 bool EmitUniqueSection = TM.getFunctionSections() || C;
1802 if (!EmitUniqueSection)
1803 return ReadOnlySection;
1804
1805 // FIXME: we should produce a symbol for F instead.
1806 if (F.hasPrivateLinkage())
1807 return ReadOnlySection;
1808
1809 MCSymbol *Sym = TM.getSymbol(&F);
1810 StringRef COMDATSymName = Sym->getName();
1811
1814 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1816 unsigned UniqueID = NextUniqueID++;
1817
1818 return getContext().getCOFFSection(
1819 SecName, Characteristics, Kind, COMDATSymName,
1821}
1822
1824 bool UsesLabelDifference, const Function &F) const {
1825 if (TM->getTargetTriple().getArch() == Triple::x86_64) {
1827 // We can always create relative relocations, so use another section
1828 // that can be marked non-executable.
1829 return false;
1830 }
1831 }
1833 UsesLabelDifference, F);
1834}
1835
1837 Module &M) const {
1838 emitLinkerDirectives(Streamer, M);
1839
1840 unsigned Version = 0;
1841 unsigned Flags = 0;
1842 StringRef Section;
1843
1844 GetObjCImageInfo(M, Version, Flags, Section);
1845 if (!Section.empty()) {
1846 auto &C = getContext();
1847 auto *S = C.getCOFFSection(Section,
1851 Streamer.switchSection(S);
1852 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1853 Streamer.emitInt32(Version);
1854 Streamer.emitInt32(Flags);
1855 Streamer.addBlankLine();
1856 }
1857
1858 emitCGProfileMetadata(Streamer, M);
1859}
1860
1861void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1862 MCStreamer &Streamer, Module &M) const {
1863 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1864 // Emit the linker options to the linker .drectve section. According to the
1865 // spec, this section is a space-separated string containing flags for
1866 // linker.
1868 Streamer.switchSection(Sec);
1869 for (const auto *Option : LinkerOptions->operands()) {
1870 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1871 // Lead with a space for consistency with our dllexport implementation.
1872 std::string Directive(" ");
1873 Directive.append(std::string(cast<MDString>(Piece)->getString()));
1874 Streamer.emitBytes(Directive);
1875 }
1876 }
1877 }
1878
1879 // Emit /EXPORT: flags for each exported global as necessary.
1880 std::string Flags;
1881 for (const GlobalValue &GV : M.global_values()) {
1882 raw_string_ostream OS(Flags);
1883 emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
1884 getMangler());
1885 OS.flush();
1886 if (!Flags.empty()) {
1887 Streamer.switchSection(getDrectveSection());
1888 Streamer.emitBytes(Flags);
1889 }
1890 Flags.clear();
1891 }
1892
1893 // Emit /INCLUDE: flags for each used global as necessary.
1894 if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1895 assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1896 assert(isa<ArrayType>(LU->getValueType()) &&
1897 "expected llvm.used to be an array type");
1898 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1899 for (const Value *Op : A->operands()) {
1900 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1901 // Global symbols with internal or private linkage are not visible to
1902 // the linker, and thus would cause an error when the linker tried to
1903 // preserve the symbol due to the `/include:` directive.
1904 if (GV->hasLocalLinkage())
1905 continue;
1906
1907 raw_string_ostream OS(Flags);
1908 emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
1909 getMangler());
1910 OS.flush();
1911
1912 if (!Flags.empty()) {
1913 Streamer.switchSection(getDrectveSection());
1914 Streamer.emitBytes(Flags);
1915 }
1916 Flags.clear();
1917 }
1918 }
1919 }
1920}
1921
1923 const TargetMachine &TM) {
1925 this->TM = &TM;
1926 const Triple &T = TM.getTargetTriple();
1927 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1936 } else {
1945 }
1946}
1947
1949 const Triple &T, bool IsCtor,
1950 unsigned Priority,
1951 const MCSymbol *KeySym,
1953 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1954 // If the priority is the default, use .CRT$XCU, possibly associative.
1955 if (Priority == 65535)
1956 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1957
1958 // Otherwise, we need to compute a new section name. Low priorities should
1959 // run earlier. The linker will sort sections ASCII-betically, and we need a
1960 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1961 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1962 // low priorities need to sort before 'L', since the CRT uses that
1963 // internally, so we use ".CRT$XCA00001" for them. We have a contract with
1964 // the frontend that "init_seg(compiler)" corresponds to priority 200 and
1965 // "init_seg(lib)" corresponds to priority 400, and those respectively use
1966 // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
1967 // use 'C' with the priority as a suffix.
1969 char LastLetter = 'T';
1970 bool AddPrioritySuffix = Priority != 200 && Priority != 400;
1971 if (Priority < 200)
1972 LastLetter = 'A';
1973 else if (Priority < 400)
1974 LastLetter = 'C';
1975 else if (Priority == 400)
1976 LastLetter = 'L';
1978 OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
1979 if (AddPrioritySuffix)
1980 OS << format("%05u", Priority);
1981 MCSectionCOFF *Sec = Ctx.getCOFFSection(
1984 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1985 }
1986
1987 std::string Name = IsCtor ? ".ctors" : ".dtors";
1988 if (Priority != 65535)
1989 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1990
1991 return Ctx.getAssociativeCOFFSection(
1996 KeySym, 0);
1997}
1998
2000 unsigned Priority, const MCSymbol *KeySym) const {
2002 getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
2003 cast<MCSectionCOFF>(StaticCtorSection));
2004}
2005
2007 unsigned Priority, const MCSymbol *KeySym) const {
2009 getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
2010 cast<MCSectionCOFF>(StaticDtorSection));
2011}
2012
2014 const GlobalValue *LHS, const GlobalValue *RHS,
2015 const TargetMachine &TM) const {
2016 const Triple &T = TM.getTargetTriple();
2017 if (T.isOSCygMing())
2018 return nullptr;
2019
2020 // Our symbols should exist in address space zero, cowardly no-op if
2021 // otherwise.
2022 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2024 return nullptr;
2025
2026 // Both ptrtoint instructions must wrap global objects:
2027 // - Only global variables are eligible for image relative relocations.
2028 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
2029 // We expect __ImageBase to be a global variable without a section, externally
2030 // defined.
2031 //
2032 // It should look something like this: @__ImageBase = external constant i8
2033 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
2034 LHS->isThreadLocal() || RHS->isThreadLocal() ||
2035 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
2036 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
2037 return nullptr;
2038
2039 return MCSymbolRefExpr::create(TM.getSymbol(LHS),
2041 getContext());
2042}
2043
2044static std::string APIntToHexString(const APInt &AI) {
2045 unsigned Width = (AI.getBitWidth() / 8) * 2;
2046 std::string HexString = toString(AI, 16, /*Signed=*/false);
2047 llvm::transform(HexString, HexString.begin(), tolower);
2048 unsigned Size = HexString.size();
2049 assert(Width >= Size && "hex string is too large!");
2050 HexString.insert(HexString.begin(), Width - Size, '0');
2051
2052 return HexString;
2053}
2054
2055static std::string scalarConstantToHexString(const Constant *C) {
2056 Type *Ty = C->getType();
2057 if (isa<UndefValue>(C)) {
2059 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
2060 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2061 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
2062 return APIntToHexString(CI->getValue());
2063 } else {
2064 unsigned NumElements;
2065 if (auto *VTy = dyn_cast<VectorType>(Ty))
2066 NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2067 else
2068 NumElements = Ty->getArrayNumElements();
2069 std::string HexString;
2070 for (int I = NumElements - 1, E = -1; I != E; --I)
2071 HexString += scalarConstantToHexString(C->getAggregateElement(I));
2072 return HexString;
2073 }
2074}
2075
2077 const DataLayout &DL, SectionKind Kind, const Constant *C,
2078 Align &Alignment) const {
2079 if (Kind.isMergeableConst() && C &&
2080 getContext().getAsmInfo()->hasCOFFComdatConstants()) {
2081 // This creates comdat sections with the given symbol name, but unless
2082 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
2083 // will be created with a null storage class, which makes GNU binutils
2084 // error out.
2088 std::string COMDATSymName;
2089 if (Kind.isMergeableConst4()) {
2090 if (Alignment <= 4) {
2091 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2092 Alignment = Align(4);
2093 }
2094 } else if (Kind.isMergeableConst8()) {
2095 if (Alignment <= 8) {
2096 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2097 Alignment = Align(8);
2098 }
2099 } else if (Kind.isMergeableConst16()) {
2100 // FIXME: These may not be appropriate for non-x86 architectures.
2101 if (Alignment <= 16) {
2102 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
2103 Alignment = Align(16);
2104 }
2105 } else if (Kind.isMergeableConst32()) {
2106 if (Alignment <= 32) {
2107 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
2108 Alignment = Align(32);
2109 }
2110 }
2111
2112 if (!COMDATSymName.empty())
2113 return getContext().getCOFFSection(".rdata", Characteristics, Kind,
2114 COMDATSymName,
2116 }
2117
2119 Alignment);
2120}
2121
2122//===----------------------------------------------------------------------===//
2123// Wasm
2124//===----------------------------------------------------------------------===//
2125
2126static const Comdat *getWasmComdat(const GlobalValue *GV) {
2127 const Comdat *C = GV->getComdat();
2128 if (!C)
2129 return nullptr;
2130
2131 if (C->getSelectionKind() != Comdat::Any)
2132 report_fatal_error("WebAssembly COMDATs only support "
2133 "SelectionKind::Any, '" + C->getName() + "' cannot be "
2134 "lowered.");
2135
2136 return C;
2137}
2138
2139static unsigned getWasmSectionFlags(SectionKind K, bool Retain) {
2140 unsigned Flags = 0;
2141
2142 if (K.isThreadLocal())
2143 Flags |= wasm::WASM_SEG_FLAG_TLS;
2144
2145 if (K.isMergeableCString())
2147
2148 if (Retain)
2150
2151 // TODO(sbc): Add suport for K.isMergeableConst()
2152
2153 return Flags;
2154}
2155
2158 collectUsedGlobalVariables(M, Vec, false);
2159 for (GlobalValue *GV : Vec)
2160 if (auto *GO = dyn_cast<GlobalObject>(GV))
2161 Used.insert(GO);
2162}
2163
2165 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2166 // We don't support explict section names for functions in the wasm object
2167 // format. Each function has to be in its own unique section.
2168 if (isa<Function>(GO)) {
2169 return SelectSectionForGlobal(GO, Kind, TM);
2170 }
2171
2172 StringRef Name = GO->getSection();
2173
2174 // Certain data sections we treat as named custom sections rather than
2175 // segments within the data section.
2176 // This could be avoided if all data segements (the wasm sense) were
2177 // represented as their own sections (in the llvm sense).
2178 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
2179 if (Name == ".llvmcmd" || Name == ".llvmbc")
2180 Kind = SectionKind::getMetadata();
2181
2182 StringRef Group = "";
2183 if (const Comdat *C = getWasmComdat(GO)) {
2184 Group = C->getName();
2185 }
2186
2187 unsigned Flags = getWasmSectionFlags(Kind, Used.count(GO));
2189 Name, Kind, Flags, Group, MCContext::GenericSectionID);
2190
2191 return Section;
2192}
2193
2194static MCSectionWasm *
2196 SectionKind Kind, Mangler &Mang,
2197 const TargetMachine &TM, bool EmitUniqueSection,
2198 unsigned *NextUniqueID, bool Retain) {
2199 StringRef Group = "";
2200 if (const Comdat *C = getWasmComdat(GO)) {
2201 Group = C->getName();
2202 }
2203
2204 bool UniqueSectionNames = TM.getUniqueSectionNames();
2205 SmallString<128> Name = getSectionPrefixForGlobal(Kind, /*IsLarge=*/false);
2206
2207 if (const auto *F = dyn_cast<Function>(GO)) {
2208 const auto &OptionalPrefix = F->getSectionPrefix();
2209 if (OptionalPrefix)
2210 raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2211 }
2212
2213 if (EmitUniqueSection && UniqueSectionNames) {
2214 Name.push_back('.');
2215 TM.getNameWithPrefix(Name, GO, Mang, true);
2216 }
2217 unsigned UniqueID = MCContext::GenericSectionID;
2218 if (EmitUniqueSection && !UniqueSectionNames) {
2219 UniqueID = *NextUniqueID;
2220 (*NextUniqueID)++;
2221 }
2222
2223 unsigned Flags = getWasmSectionFlags(Kind, Retain);
2224 return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2225}
2226
2228 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2229
2230 if (Kind.isCommon())
2231 report_fatal_error("mergable sections not supported yet on wasm");
2232
2233 // If we have -ffunction-section or -fdata-section then we should emit the
2234 // global value to a uniqued section specifically for it.
2235 bool EmitUniqueSection = false;
2236 if (Kind.isText())
2237 EmitUniqueSection = TM.getFunctionSections();
2238 else
2239 EmitUniqueSection = TM.getDataSections();
2240 EmitUniqueSection |= GO->hasComdat();
2241 bool Retain = Used.count(GO);
2242 EmitUniqueSection |= Retain;
2243
2244 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2245 EmitUniqueSection, &NextUniqueID, Retain);
2246}
2247
2249 bool UsesLabelDifference, const Function &F) const {
2250 // We can always create relative relocations, so use another section
2251 // that can be marked non-executable.
2252 return false;
2253}
2254
2256 const GlobalValue *LHS, const GlobalValue *RHS,
2257 const TargetMachine &TM) const {
2258 // We may only use a PLT-relative relocation to refer to unnamed_addr
2259 // functions.
2260 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2261 return nullptr;
2262
2263 // Basic correctness checks.
2264 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2265 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2266 RHS->isThreadLocal())
2267 return nullptr;
2268
2271 getContext()),
2273}
2274
2278
2279 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2280 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2282}
2283
2285 unsigned Priority, const MCSymbol *KeySym) const {
2286 return Priority == UINT16_MAX ?
2288 getContext().getWasmSection(".init_array." + utostr(Priority),
2290}
2291
2293 unsigned Priority, const MCSymbol *KeySym) const {
2294 report_fatal_error("@llvm.global_dtors should have been lowered already");
2295}
2296
2297//===----------------------------------------------------------------------===//
2298// XCOFF
2299//===----------------------------------------------------------------------===//
2301 const MachineFunction *MF) {
2302 if (!MF->getLandingPads().empty())
2303 return true;
2304
2305 const Function &F = MF->getFunction();
2306 if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2307 return false;
2308
2309 const GlobalValue *Per =
2310 dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2311 assert(Per && "Personality routine is not a GlobalValue type.");
2313 return false;
2314
2315 return true;
2316}
2317
2319 const MachineFunction *MF) {
2320 const Function &F = MF->getFunction();
2321 if (!F.hasStackProtectorFnAttr())
2322 return false;
2323 // FIXME: check presence of canary word
2324 // There are cases that the stack protectors are not really inserted even if
2325 // the attributes are on.
2326 return true;
2327}
2328
2329MCSymbol *
2331 MCSymbol *EHInfoSym = MF->getMMI().getContext().getOrCreateSymbol(
2332 "__ehinfo." + Twine(MF->getFunctionNumber()));
2333 cast<MCSymbolXCOFF>(EHInfoSym)->setEHInfo();
2334 return EHInfoSym;
2335}
2336
2337MCSymbol *
2339 const TargetMachine &TM) const {
2340 // We always use a qualname symbol for a GV that represents
2341 // a declaration, a function descriptor, or a common symbol.
2342 // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2343 // also return a qualname so that a label symbol could be avoided.
2344 // It is inherently ambiguous when the GO represents the address of a
2345 // function, as the GO could either represent a function descriptor or a
2346 // function entry point. We choose to always return a function descriptor
2347 // here.
2348 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2349 if (GO->isDeclarationForLinker())
2350 return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
2351 ->getQualNameSymbol();
2352
2353 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2354 if (GVar->hasAttribute("toc-data"))
2355 return cast<MCSectionXCOFF>(
2357 ->getQualNameSymbol();
2358
2359 SectionKind GOKind = getKindForGlobal(GO, TM);
2360 if (GOKind.isText())
2361 return cast<MCSectionXCOFF>(
2362 getSectionForFunctionDescriptor(cast<Function>(GO), TM))
2363 ->getQualNameSymbol();
2364 if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2365 GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
2366 return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
2367 ->getQualNameSymbol();
2368 }
2369
2370 // For all other cases, fall back to getSymbol to return the unqualified name.
2371 return nullptr;
2372}
2373
2375 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2376 if (!GO->hasSection())
2377 report_fatal_error("#pragma clang section is not yet supported");
2378
2380
2381 // Handle the XCOFF::TD case first, then deal with the rest.
2382 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2383 if (GVar->hasAttribute("toc-data"))
2384 return getContext().getXCOFFSection(
2385 SectionName, Kind,
2387 /* MultiSymbolsAllowed*/ true);
2388
2389 XCOFF::StorageMappingClass MappingClass;
2390 if (Kind.isText())
2391 MappingClass = XCOFF::XMC_PR;
2392 else if (Kind.isData() || Kind.isBSS())
2393 MappingClass = XCOFF::XMC_RW;
2394 else if (Kind.isReadOnlyWithRel())
2395 MappingClass =
2397 else if (Kind.isReadOnly())
2398 MappingClass = XCOFF::XMC_RO;
2399 else
2400 report_fatal_error("XCOFF other section types not yet implemented.");
2401
2402 return getContext().getXCOFFSection(
2403 SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2404 /* MultiSymbolsAllowed*/ true);
2405}
2406
2408 const GlobalObject *GO, const TargetMachine &TM) const {
2410 "Tried to get ER section for a defined global.");
2411
2414
2415 // AIX TLS local-dynamic does not need the external reference for the
2416 // "_$TLSML" symbol.
2418 GO->hasName() && GO->getName() == "_$TLSML") {
2419 return getContext().getXCOFFSection(
2422 }
2423
2425 isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
2426 if (GO->isThreadLocal())
2427 SMC = XCOFF::XMC_UL;
2428
2429 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2430 if (GVar->hasAttribute("toc-data"))
2431 SMC = XCOFF::XMC_TD;
2432
2433 // Externals go into a csect of type ER.
2434 return getContext().getXCOFFSection(
2437}
2438
2440 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2441 // Handle the XCOFF::TD case first, then deal with the rest.
2442 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2443 if (GVar->hasAttribute("toc-data")) {
2446 XCOFF::SymbolType symType =
2448 return getContext().getXCOFFSection(
2449 Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, symType),
2450 /* MultiSymbolsAllowed*/ true);
2451 }
2452
2453 // Common symbols go into a csect with matching name which will get mapped
2454 // into the .bss section.
2455 // Zero-initialized local TLS symbols go into a csect with matching name which
2456 // will get mapped into the .tbss section.
2457 if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2460 XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2461 : Kind.isCommon() ? XCOFF::XMC_RW
2462 : XCOFF::XMC_UL;
2463 return getContext().getXCOFFSection(
2465 }
2466
2467 if (Kind.isText()) {
2468 if (TM.getFunctionSections()) {
2469 return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2470 ->getRepresentedCsect();
2471 }
2472 return TextSection;
2473 }
2474
2475 if (TM.Options.XCOFFReadOnlyPointers && Kind.isReadOnlyWithRel()) {
2476 if (!TM.getDataSections())
2478 "ReadOnlyPointers is supported only if data sections is turned on");
2479
2482 return getContext().getXCOFFSection(
2485 }
2486
2487 // For BSS kind, zero initialized data must be emitted to the .data section
2488 // because external linkage control sections that get mapped to the .bss
2489 // section will be linked as tentative defintions, which is only appropriate
2490 // for SectionKind::Common.
2491 if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2492 if (TM.getDataSections()) {
2495 return getContext().getXCOFFSection(
2498 }
2499 return DataSection;
2500 }
2501
2502 if (Kind.isReadOnly()) {
2503 if (TM.getDataSections()) {
2506 return getContext().getXCOFFSection(
2509 }
2510 return ReadOnlySection;
2511 }
2512
2513 // External/weak TLS data and initialized local TLS data are not eligible
2514 // to be put into common csect. If data sections are enabled, thread
2515 // data are emitted into separate sections. Otherwise, thread data
2516 // are emitted into the .tdata section.
2517 if (Kind.isThreadLocal()) {
2518 if (TM.getDataSections()) {
2521 return getContext().getXCOFFSection(
2523 }
2524 return TLSDataSection;
2525 }
2526
2527 report_fatal_error("XCOFF other section types not yet implemented.");
2528}
2529
2531 const Function &F, const TargetMachine &TM) const {
2532 assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2533
2534 if (!TM.getFunctionSections())
2535 return ReadOnlySection;
2536
2537 // If the function can be removed, produce a unique section so that
2538 // the table doesn't prevent the removal.
2539 SmallString<128> NameStr(".rodata.jmp..");
2540 getNameWithPrefix(NameStr, &F, TM);
2541 return getContext().getXCOFFSection(
2542 NameStr, SectionKind::getReadOnly(),
2544}
2545
2547 bool UsesLabelDifference, const Function &F) const {
2548 return false;
2549}
2550
2551/// Given a mergeable constant with the specified size and relocation
2552/// information, return a section that it should be placed in.
2554 const DataLayout &DL, SectionKind Kind, const Constant *C,
2555 Align &Alignment) const {
2556 // TODO: Enable emiting constant pool to unique sections when we support it.
2557 if (Alignment > Align(16))
2558 report_fatal_error("Alignments greater than 16 not yet supported.");
2559
2560 if (Alignment == Align(8)) {
2561 assert(ReadOnly8Section && "Section should always be initialized.");
2562 return ReadOnly8Section;
2563 }
2564
2565 if (Alignment == Align(16)) {
2566 assert(ReadOnly16Section && "Section should always be initialized.");
2567 return ReadOnly16Section;
2568 }
2569
2570 return ReadOnlySection;
2571}
2572
2574 const TargetMachine &TgtM) {
2581 LSDAEncoding = 0;
2583
2584 // AIX debug for thread local location is not ready. And for integrated as
2585 // mode, the relocatable address for the thread local variable will cause
2586 // linker error. So disable the location attribute generation for thread local
2587 // variables for now.
2588 // FIXME: when TLS debug on AIX is ready, remove this setting.
2590}
2591
2593 unsigned Priority, const MCSymbol *KeySym) const {
2594 report_fatal_error("no static constructor section on AIX");
2595}
2596
2598 unsigned Priority, const MCSymbol *KeySym) const {
2599 report_fatal_error("no static destructor section on AIX");
2600}
2601
2603 const GlobalValue *LHS, const GlobalValue *RHS,
2604 const TargetMachine &TM) const {
2605 /* Not implemented yet, but don't crash, return nullptr. */
2606 return nullptr;
2607}
2608
2611 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2612
2613 switch (GV->getLinkage()) {
2616 return XCOFF::C_HIDEXT;
2620 return XCOFF::C_EXT;
2626 return XCOFF::C_WEAKEXT;
2629 "There is no mapping that implements AppendingLinkage for XCOFF.");
2630 }
2631 llvm_unreachable("Unknown linkage type!");
2632}
2633
2635 const GlobalValue *Func, const TargetMachine &TM) const {
2636 assert((isa<Function>(Func) ||
2637 (isa<GlobalAlias>(Func) &&
2638 isa_and_nonnull<Function>(
2639 cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2640 "Func must be a function or an alias which has a function as base "
2641 "object.");
2642
2643 SmallString<128> NameStr;
2644 NameStr.push_back('.');
2645 getNameWithPrefix(NameStr, Func, TM);
2646
2647 // When -function-sections is enabled and explicit section is not specified,
2648 // it's not necessary to emit function entry point label any more. We will use
2649 // function entry point csect instead. And for function delcarations, the
2650 // undefined symbols gets treated as csect with XTY_ER property.
2651 if (((TM.getFunctionSections() && !Func->hasSection()) ||
2652 Func->isDeclarationForLinker()) &&
2653 isa<Function>(Func)) {
2654 return getContext()
2656 NameStr, SectionKind::getText(),
2657 XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclarationForLinker()
2659 : XCOFF::XTY_SD))
2661 }
2662
2663 return getContext().getOrCreateSymbol(NameStr);
2664}
2665
2667 const Function *F, const TargetMachine &TM) const {
2668 SmallString<128> NameStr;
2669 getNameWithPrefix(NameStr, F, TM);
2670 return getContext().getXCOFFSection(
2671 NameStr, SectionKind::getData(),
2673}
2674
2676 const MCSymbol *Sym, const TargetMachine &TM) const {
2677 const XCOFF::StorageMappingClass SMC = [](const MCSymbol *Sym,
2678 const TargetMachine &TM) {
2679 const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(Sym);
2680
2681 // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC,
2682 // otherwise the AIX assembler will complain.
2683 if (XSym->getSymbolTableName() == "_$TLSML")
2684 return XCOFF::XMC_TC;
2685
2686 // Use large code model toc entries for ehinfo symbols as they are
2687 // never referenced directly. The runtime loads their TOC entry
2688 // addresses from the trace-back table.
2689 if (XSym->isEHInfo())
2690 return XCOFF::XMC_TE;
2691
2692 // If the symbol does not have a code model specified use the module value.
2693 if (!XSym->hasPerSymbolCodeModel())
2695 : XCOFF::XMC_TC;
2696
2699 : XCOFF::XMC_TC;
2700 }(Sym, TM);
2701
2702 return getContext().getXCOFFSection(
2703 cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
2705}
2706
2708 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2709 auto *LSDA = cast<MCSectionXCOFF>(LSDASection);
2710 if (TM.getFunctionSections()) {
2711 // If option -ffunction-sections is on, append the function name to the
2712 // name of the LSDA csect so that each function has its own LSDA csect.
2713 // This helps the linker to garbage-collect EH info of unused functions.
2714 SmallString<128> NameStr = LSDA->getName();
2715 raw_svector_ostream(NameStr) << '.' << F.getName();
2716 LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
2717 LSDA->getCsectProp());
2718 }
2719 return LSDA;
2720}
2721//===----------------------------------------------------------------------===//
2722// GOFF
2723//===----------------------------------------------------------------------===//
2725
2727 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2728 return SelectSectionForGlobal(GO, Kind, TM);
2729}
2730
2732 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2733 std::string Name = ".gcc_exception_table." + F.getName().str();
2735 nullptr);
2736}
2737
2739 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2740 auto *Symbol = TM.getSymbol(GO);
2741 if (Kind.isBSS())
2742 return getContext().getGOFFSection(Symbol->getName(), SectionKind::getBSS(),
2743 nullptr, nullptr);
2744
2746}
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")
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:479
This file declares the MCSectionGOFF class, which contains all of the necessary machine code sections...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
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 bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, const MCSection &Section)
static MCSection * selectExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM, MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID, bool Retain, bool ForceUnique)
static int getSelectionForCOFF(const GlobalValue *GV)
static MCSectionCOFF * getCOFFStaticStructorSection(MCContext &Ctx, const Triple &T, bool IsCtor, unsigned Priority, const MCSymbol *KeySym, MCSectionCOFF *Default)
static unsigned getEntrySizeForKind(SectionKind Kind)
static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, StringRef &Section)
static const GlobalValue * getComdatGVForCOFF(const GlobalValue *GV)
static unsigned getCOFFSectionFlags(SectionKind K, const TargetMachine &TM)
static unsigned getELFSectionType(StringRef Name, SectionKind K)
static bool hasPrefix(StringRef SectionName, StringRef Prefix)
static MCSectionWasm * selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID, bool Retain)
static const MCSymbolELF * getLinkedToSymbol(const GlobalObject *GO, const TargetMachine &TM)
static unsigned calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName, SectionKind Kind, const TargetMachine &TM, MCContext &Ctx, Mangler &Mang, unsigned &Flags, unsigned &EntrySize, unsigned &NextUniqueID, const bool Retain, const bool ForceUnique)
Calculate an appropriate unique ID for a section, and update Flags, EntrySize and NextUniqueID where ...
static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K)
static const Comdat * getWasmComdat(const GlobalValue *GV)
static MCSectionELF * getStaticStructorSection(MCContext &Ctx, bool UseInitArray, bool IsCtor, unsigned Priority, const MCSymbol *KeySym)
static unsigned getWasmSectionFlags(SectionKind K, bool Retain)
static void checkMachOComdat(const GlobalValue *GV)
static std::string APIntToHexString(const APInt &AI)
static cl::opt< bool > JumpTableInFunctionSection("jumptable-in-function-section", cl::Hidden, cl::init(false), cl::desc("Putting Jump Table in function section"))
static StringRef getSectionPrefixForGlobal(SectionKind Kind, bool IsLarge)
Return the section prefix name used by options FunctionsSections and DataSections.
static MCSectionELF * selectELFSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol)
static SmallString< 128 > getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, unsigned EntrySize, bool UniqueSectionName)
static std::string scalarConstantToHexString(const Constant *C)
static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind)
static const Comdat * getELFComdat(const GlobalValue *GV)
static std::tuple< StringRef, bool, unsigned > getGlobalObjectInfo(const GlobalObject *GO, const TargetMachine &TM)
static unsigned getELFSectionFlags(SectionKind K)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:76
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1439
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:178
@ 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:935
GlobalValue * getGlobalValue() const
Definition: Constants.h:954
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:332
This is the base abstract class for diagnostic reporting in the backend.
Interface for custom diagnostic printing.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:118
bool hasComdat() const
Definition: GlobalObject.h:128
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:110
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:565
bool hasExternalLinkage() const
Definition: GlobalValue.h:511
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:263
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
bool hasLocalLinkage() const
Definition: GlobalValue.h:528
bool hasPrivateLinkage() const
Definition: GlobalValue.h:527
const Comdat * getComdat() const
Definition: Globals.cpp:184
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
bool isDeclarationForLinker() const
Definition: GlobalValue.h:618
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:375
bool hasCommonLinkage() const
Definition: GlobalValue.h:532
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:458
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
AttributeSet getAttributes() const
Return the attribute set for this global.
bool hasImplicitSection() const
Check if section name is present.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
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:842
virtual bool isSectionAtomizableBySymbols(const MCSection &Section) const
True if the section is atomized using the symbols in it.
Definition: MCAsmInfo.cpp:79
bool binutilsIsAtLeast(int Major, int Minor) const
Definition: MCAsmInfo.h:849
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:780
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:536
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:621
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:81
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:457
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:442
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K, unsigned Flags=0)
Definition: MCContext.h:659
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:521
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:578
bool isELFGenericMergeableSection(StringRef Name)
Definition: MCContext.cpp:640
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:784
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:646
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:453
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:672
@ GenericSectionID
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:561
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:201
bool isELFImplicitMergeableSectionNamePrefix(StringRef Name)
Definition: MCContext.cpp:635
MCSectionGOFF * getGOFFSection(StringRef Section, SectionKind Kind, MCSection *Parent, const MCExpr *SubsectionId)
Definition: MCContext.cpp:654
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:711
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:755
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:754
void emitInt8(uint64_t Value)
Definition: MCStreamer.h:752
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
const MCSymbol & getSymbol() const
Definition: MCExpr.h:410
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:397
StringRef getSymbolTableName() const
Definition: MCSymbolXCOFF.h:67
bool hasPerSymbolCodeModel() const
Definition: MCSymbolXCOFF.h:77
CodeModel getPerSymbolCodeModel() const
Definition: MCSymbolXCOFF.h:79
bool isEHInfo() const
Definition: MCSymbolXCOFF.h:73
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
This represents an "assembler immediate".
Definition: MCValue.h:36
int64_t getConstant() const
Definition: MCValue.h:43
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:45
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
Metadata * get() const
Definition: Metadata.h:918
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:120
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:278
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition: Module.cpp:135
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:293
A tuple of MDNodes.
Definition: Metadata.h:1729
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:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
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 * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Get MachO PC relative GOT entry relocation.
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit the module flags that specify the garbage collection information.
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForCommandLines() const override
If supported, return the section to use for the llvm.commandline metadata.
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
The mach-o version of this method defaults to returning a stub reference.
void getModuleMetadata(Module &M) override
Get the module-level metadata that the platform cares about.
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
static bool ShouldSetSSPCanaryBitInTB(const MachineFunction *MF)
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForTOCEntry(const MCSymbol *Sym, const TargetMachine &TM) const override
On targets that support TOC entries, return a section for the entry given the symbol it refers to.
MCSection * getSectionForExternalReference(const GlobalObject *GO, const TargetMachine &TM) const override
For external functions, this will always return a function descriptor csect.
MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const override
If supported, return the function entry point symbol.
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
static MCSymbol * getEHInfoTableSymbol(const MachineFunction *MF)
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
static XCOFF::StorageClass getStorageClassForGlobal(const GlobalValue *GV)
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getTargetSymbol(const GlobalValue *GV, const TargetMachine &TM) const override
For functions, this will always return a function descriptor symbol.
MCSection * getSectionForFunctionDescriptor(const Function *F, const TargetMachine &TM) const override
On targets that use separate function descriptor symbols, return a section for the descriptor given i...
static bool ShouldEmitEHBlock(const MachineFunction *MF)
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
For functions, this will return the LSDA section.
void emitCGProfileMetadata(MCStreamer &Streamer, Module &M) const
Emit Call Graph Profile metadata.
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
MCSection * StaticDtorSection
This section contains the static destructor pointer list.
unsigned PersonalityEncoding
PersonalityEncoding, LSDAEncoding, TTypeEncoding - Some encoding values for EH.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
bool supportDSOLocalEquivalentLowering() const
Target supports a native lowering of a dso_local_equivalent constant without needing to replace it wi...
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
This method must be called before any actual lowering is done.
MCSection * StaticCtorSection
This section contains the static constructor pointer list.
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Return an MCExpr to use for a reference to the specified global variable from exception handling info...
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:76
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:373
EnvironmentType getEnvironment() const
Get the parsed environment type of this triple.
Definition: Triple.h:390
bool isOSFreeBSD() const
Definition: Triple.h:584
bool isArch32Bit() const
Test whether the architecture is 32-bit.
Definition: Triple.cpp:1663
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:1074
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:690
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SectionCharacteristics
Definition: COFF.h:297
@ IMAGE_SCN_LNK_REMOVE
Definition: COFF.h:307
@ IMAGE_SCN_CNT_CODE
Definition: COFF.h:302
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:335
@ IMAGE_SCN_MEM_EXECUTE
Definition: COFF.h:334
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:304
@ IMAGE_SCN_MEM_DISCARDABLE
Definition: COFF.h:330
@ IMAGE_SCN_MEM_16BIT
Definition: COFF.h:311
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:303
@ IMAGE_SCN_LNK_COMDAT
Definition: COFF.h:308
@ IMAGE_SCN_MEM_WRITE
Definition: COFF.h:336
@ IMAGE_COMDAT_SELECT_NODUPLICATES
Definition: COFF.h:421
@ IMAGE_COMDAT_SELECT_LARGEST
Definition: COFF.h:426
@ IMAGE_COMDAT_SELECT_SAME_SIZE
Definition: COFF.h:423
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition: COFF.h:425
@ IMAGE_COMDAT_SELECT_EXACT_MATCH
Definition: COFF.h:424
@ IMAGE_COMDAT_SELECT_ANY
Definition: COFF.h:422
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SHF_MERGE
Definition: ELF.h:1163
@ SHF_STRINGS
Definition: ELF.h:1166
@ SHF_EXCLUDE
Definition: ELF.h:1191
@ SHF_ALLOC
Definition: ELF.h:1157
@ SHF_LINK_ORDER
Definition: ELF.h:1172
@ SHF_GROUP
Definition: ELF.h:1179
@ SHF_SUNW_NODISCARD
Definition: ELF.h:1198
@ SHF_X86_64_LARGE
Definition: ELF.h:1220
@ SHF_GNU_RETAIN
Definition: ELF.h:1188
@ SHF_WRITE
Definition: ELF.h:1154
@ SHF_TLS
Definition: ELF.h:1182
@ SHF_ARM_PURECODE
Definition: ELF.h:1252
@ SHF_EXECINSTR
Definition: ELF.h:1160
@ SHT_LLVM_DEPENDENT_LIBRARIES
Definition: ELF.h:1091
@ SHT_PROGBITS
Definition: ELF.h:1063
@ SHT_LLVM_LINKER_OPTIONS
Definition: ELF.h:1088
@ SHT_NOBITS
Definition: ELF.h:1070
@ SHT_LLVM_OFFLOADING
Definition: ELF.h:1101
@ SHT_PREINIT_ARRAY
Definition: ELF.h:1076
@ SHT_INIT_ARRAY
Definition: ELF.h:1074
@ SHT_NOTE
Definition: ELF.h:1069
@ SHT_FINI_ARRAY
Definition: ELF.h:1075
@ S_MOD_TERM_FUNC_POINTERS
S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for termination.
Definition: MachO.h:150
@ S_MOD_INIT_FUNC_POINTERS
S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for initialization.
Definition: MachO.h:147
StorageClass
Definition: XCOFF.h:170
@ C_WEAKEXT
Definition: XCOFF.h:199
@ C_HIDEXT
Definition: XCOFF.h:206
StorageMappingClass
Storage Mapping Class definitions.
Definition: XCOFF.h:103
@ XMC_TE
Symbol mapped at the end of TOC.
Definition: XCOFF.h:128
@ XMC_DS
Descriptor csect.
Definition: XCOFF.h:121
@ XMC_RW
Read Write Data.
Definition: XCOFF.h:117
@ XMC_TL
Initialized thread-local variable.
Definition: XCOFF.h:126
@ XMC_RO
Read Only Constant.
Definition: XCOFF.h:106
@ XMC_UA
Unclassified - Treated as Read Write.
Definition: XCOFF.h:122
@ XMC_TD
Scalar data item in the TOC.
Definition: XCOFF.h:120
@ XMC_UL
Uninitialized thread-local variable.
Definition: XCOFF.h:127
@ XMC_PR
Program Code.
Definition: XCOFF.h:105
@ XMC_BS
BSS class (uninitialized static internal)
Definition: XCOFF.h:123
@ XMC_TC
General TOC item.
Definition: XCOFF.h:119
@ XTY_CM
Common csect definition. For uninitialized storage.
Definition: XCOFF.h:245
@ XTY_SD
Csect definition for initialized storage.
Definition: XCOFF.h:242
@ XTY_ER
External reference.
Definition: XCOFF.h:241
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
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:850
@ DW_EH_PE_pcrel
Definition: Dwarf.h:848
@ DW_EH_PE_sdata4
Definition: Dwarf.h:845
@ DW_EH_PE_sdata8
Definition: Dwarf.h:846
@ DW_EH_PE_absptr
Definition: Dwarf.h:837
@ DW_EH_PE_udata4
Definition: Dwarf.h:841
@ DW_EH_PE_udata8
Definition: Dwarf.h:842
@ DW_EH_PE_indirect
Definition: Dwarf.h:853
@ WASM_SEG_FLAG_RETAIN
Definition: Wasm.h:219
@ WASM_SEG_FLAG_TLS
Definition: Wasm.h:218
@ WASM_SEG_FLAG_STRINGS
Definition: Wasm.h:217
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:231
@ 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:1928
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:156
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:279
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Error
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:213
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:845
constexpr const char * PseudoProbeDescMetadataName
Definition: PseudoProbe.h:25
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
static const MBBSectionID ExceptionSectionID
static const MBBSectionID ColdSectionID