Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:12

0001 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLVM_MC_MCCONTEXT_H
0010 #define LLVM_MC_MCCONTEXT_H
0011 
0012 #include "llvm/ADT/DenseMap.h"
0013 #include "llvm/ADT/SetVector.h"
0014 #include "llvm/ADT/SmallString.h"
0015 #include "llvm/ADT/StringMap.h"
0016 #include "llvm/ADT/StringRef.h"
0017 #include "llvm/ADT/Twine.h"
0018 #include "llvm/BinaryFormat/Dwarf.h"
0019 #include "llvm/BinaryFormat/XCOFF.h"
0020 #include "llvm/MC/MCAsmMacro.h"
0021 #include "llvm/MC/MCDwarf.h"
0022 #include "llvm/MC/MCPseudoProbe.h"
0023 #include "llvm/MC/MCSection.h"
0024 #include "llvm/MC/MCSymbolTableEntry.h"
0025 #include "llvm/MC/SectionKind.h"
0026 #include "llvm/Support/Allocator.h"
0027 #include "llvm/Support/Compiler.h"
0028 #include "llvm/Support/Error.h"
0029 #include "llvm/Support/MD5.h"
0030 #include "llvm/Support/StringSaver.h"
0031 #include "llvm/Support/raw_ostream.h"
0032 #include <algorithm>
0033 #include <cassert>
0034 #include <cstddef>
0035 #include <cstdint>
0036 #include <functional>
0037 #include <map>
0038 #include <memory>
0039 #include <optional>
0040 #include <string>
0041 #include <utility>
0042 #include <vector>
0043 
0044 namespace llvm {
0045 
0046 class CodeViewContext;
0047 class MCAsmInfo;
0048 class MCDataFragment;
0049 class MCInst;
0050 class MCLabel;
0051 class MCObjectFileInfo;
0052 class MCRegisterInfo;
0053 class MCSection;
0054 class MCSectionCOFF;
0055 class MCSectionDXContainer;
0056 class MCSectionELF;
0057 class MCSectionGOFF;
0058 class MCSectionMachO;
0059 class MCSectionSPIRV;
0060 class MCSectionWasm;
0061 class MCSectionXCOFF;
0062 class MCStreamer;
0063 class MCSubtargetInfo;
0064 class MCSymbol;
0065 class MCSymbolELF;
0066 class MCSymbolWasm;
0067 class MCSymbolXCOFF;
0068 class MCTargetOptions;
0069 class MDNode;
0070 template <typename T> class SmallVectorImpl;
0071 class SMDiagnostic;
0072 class SMLoc;
0073 class SourceMgr;
0074 enum class EmitDwarfUnwindType;
0075 
0076 namespace wasm {
0077 struct WasmSignature;
0078 }
0079 
0080 /// Context object for machine code objects.  This class owns all of the
0081 /// sections that it creates.
0082 ///
0083 class MCContext {
0084 public:
0085   using SymbolTable = StringMap<MCSymbolTableValue, BumpPtrAllocator &>;
0086   using DiagHandlerTy =
0087       std::function<void(const SMDiagnostic &, bool, const SourceMgr &,
0088                          std::vector<const MDNode *> &)>;
0089   enum Environment {
0090     IsMachO,
0091     IsELF,
0092     IsGOFF,
0093     IsCOFF,
0094     IsSPIRV,
0095     IsWasm,
0096     IsXCOFF,
0097     IsDXContainer
0098   };
0099 
0100 private:
0101   Environment Env;
0102 
0103   /// The name of the Segment where Swift5 Reflection Section data will be
0104   /// outputted
0105   StringRef Swift5ReflectionSegmentName;
0106 
0107   /// The triple for this object.
0108   Triple TT;
0109 
0110   /// The SourceMgr for this object, if any.
0111   const SourceMgr *SrcMgr = nullptr;
0112 
0113   /// The SourceMgr for inline assembly, if any.
0114   std::unique_ptr<SourceMgr> InlineSrcMgr;
0115   std::vector<const MDNode *> LocInfos;
0116 
0117   DiagHandlerTy DiagHandler;
0118 
0119   /// The MCAsmInfo for this target.
0120   const MCAsmInfo *MAI = nullptr;
0121 
0122   /// The MCRegisterInfo for this target.
0123   const MCRegisterInfo *MRI = nullptr;
0124 
0125   /// The MCObjectFileInfo for this target.
0126   const MCObjectFileInfo *MOFI = nullptr;
0127 
0128   /// The MCSubtargetInfo for this target.
0129   const MCSubtargetInfo *MSTI = nullptr;
0130 
0131   std::unique_ptr<CodeViewContext> CVContext;
0132 
0133   /// Allocator object used for creating machine code objects.
0134   ///
0135   /// We use a bump pointer allocator to avoid the need to track all allocated
0136   /// objects.
0137   BumpPtrAllocator Allocator;
0138 
0139   /// For MCFragment instances.
0140   BumpPtrAllocator FragmentAllocator;
0141 
0142   SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
0143   SpecificBumpPtrAllocator<MCSectionDXContainer> DXCAllocator;
0144   SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
0145   SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
0146   SpecificBumpPtrAllocator<MCSectionGOFF> GOFFAllocator;
0147   SpecificBumpPtrAllocator<MCSectionSPIRV> SPIRVAllocator;
0148   SpecificBumpPtrAllocator<MCSectionWasm> WasmAllocator;
0149   SpecificBumpPtrAllocator<MCSectionXCOFF> XCOFFAllocator;
0150   SpecificBumpPtrAllocator<MCInst> MCInstAllocator;
0151 
0152   SpecificBumpPtrAllocator<wasm::WasmSignature> WasmSignatureAllocator;
0153 
0154   /// Bindings of names to symbol table values.
0155   SymbolTable Symbols;
0156 
0157   /// A mapping from a local label number and an instance count to a symbol.
0158   /// For example, in the assembly
0159   ///     1:
0160   ///     2:
0161   ///     1:
0162   /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
0163   DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
0164 
0165   /// Keeps track of labels that are used in inline assembly.
0166   StringMap<MCSymbol *, BumpPtrAllocator &> InlineAsmUsedLabelNames;
0167 
0168   /// Instances of directional local labels.
0169   DenseMap<unsigned, MCLabel *> Instances;
0170   /// NextInstance() creates the next instance of the directional local label
0171   /// for the LocalLabelVal and adds it to the map if needed.
0172   unsigned NextInstance(unsigned LocalLabelVal);
0173   /// GetInstance() gets the current instance of the directional local label
0174   /// for the LocalLabelVal and adds it to the map if needed.
0175   unsigned GetInstance(unsigned LocalLabelVal);
0176 
0177   /// LLVM_BB_ADDR_MAP version to emit.
0178   uint8_t BBAddrMapVersion = 2;
0179 
0180   /// The file name of the log file from the environment variable
0181   /// AS_SECURE_LOG_FILE.  Which must be set before the .secure_log_unique
0182   /// directive is used or it is an error.
0183   std::string SecureLogFile;
0184   /// The stream that gets written to for the .secure_log_unique directive.
0185   std::unique_ptr<raw_fd_ostream> SecureLog;
0186   /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
0187   /// catch errors if .secure_log_unique appears twice without
0188   /// .secure_log_reset appearing between them.
0189   bool SecureLogUsed = false;
0190 
0191   /// The compilation directory to use for DW_AT_comp_dir.
0192   SmallString<128> CompilationDir;
0193 
0194   /// Prefix replacement map for source file information.
0195   SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap;
0196 
0197   /// The main file name if passed in explicitly.
0198   std::string MainFileName;
0199 
0200   /// The dwarf file and directory tables from the dwarf .file directive.
0201   /// We now emit a line table for each compile unit. To reduce the prologue
0202   /// size of each line table, the files and directories used by each compile
0203   /// unit are separated.
0204   std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
0205 
0206   /// The current dwarf line information from the last dwarf .loc directive.
0207   MCDwarfLoc CurrentDwarfLoc;
0208   bool DwarfLocSeen = false;
0209 
0210   /// Generate dwarf debugging info for assembly source files.
0211   bool GenDwarfForAssembly = false;
0212 
0213   /// The current dwarf file number when generate dwarf debugging info for
0214   /// assembly source files.
0215   unsigned GenDwarfFileNumber = 0;
0216 
0217   /// Sections for generating the .debug_ranges and .debug_aranges sections.
0218   SetVector<MCSection *> SectionsForRanges;
0219 
0220   /// The information gathered from labels that will have dwarf label
0221   /// entries when generating dwarf assembly source files.
0222   std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
0223 
0224   /// The string to embed in the debug information for the compile unit, if
0225   /// non-empty.
0226   StringRef DwarfDebugFlags;
0227 
0228   /// The string to embed in as the dwarf AT_producer for the compile unit, if
0229   /// non-empty.
0230   StringRef DwarfDebugProducer;
0231 
0232   /// The maximum version of dwarf that we should emit.
0233   uint16_t DwarfVersion = 4;
0234 
0235   /// The format of dwarf that we emit.
0236   dwarf::DwarfFormat DwarfFormat = dwarf::DWARF32;
0237 
0238   /// Honor temporary labels, this is useful for debugging semantic
0239   /// differences between temporary and non-temporary labels (primarily on
0240   /// Darwin).
0241   bool SaveTempLabels = false;
0242   bool UseNamesOnTempLabels = false;
0243 
0244   /// The Compile Unit ID that we are currently processing.
0245   unsigned DwarfCompileUnitID = 0;
0246 
0247   /// A collection of MCPseudoProbe in the current module
0248   MCPseudoProbeTable PseudoProbeTable;
0249 
0250   struct COFFSectionKey {
0251     std::string SectionName;
0252     StringRef GroupName;
0253     int SelectionKey;
0254     unsigned UniqueID;
0255 
0256     COFFSectionKey(StringRef SectionName, StringRef GroupName, int SelectionKey,
0257                    unsigned UniqueID)
0258         : SectionName(SectionName), GroupName(GroupName),
0259           SelectionKey(SelectionKey), UniqueID(UniqueID) {}
0260 
0261     bool operator<(const COFFSectionKey &Other) const {
0262       if (SectionName != Other.SectionName)
0263         return SectionName < Other.SectionName;
0264       if (GroupName != Other.GroupName)
0265         return GroupName < Other.GroupName;
0266       if (SelectionKey != Other.SelectionKey)
0267         return SelectionKey < Other.SelectionKey;
0268       return UniqueID < Other.UniqueID;
0269     }
0270   };
0271 
0272   struct WasmSectionKey {
0273     std::string SectionName;
0274     StringRef GroupName;
0275     unsigned UniqueID;
0276 
0277     WasmSectionKey(StringRef SectionName, StringRef GroupName,
0278                    unsigned UniqueID)
0279         : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {}
0280 
0281     bool operator<(const WasmSectionKey &Other) const {
0282       if (SectionName != Other.SectionName)
0283         return SectionName < Other.SectionName;
0284       if (GroupName != Other.GroupName)
0285         return GroupName < Other.GroupName;
0286       return UniqueID < Other.UniqueID;
0287     }
0288   };
0289 
0290   struct XCOFFSectionKey {
0291     // Section name.
0292     std::string SectionName;
0293     // Section property.
0294     // For csect section, it is storage mapping class.
0295     // For debug section, it is section type flags.
0296     union {
0297       XCOFF::StorageMappingClass MappingClass;
0298       XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags;
0299     };
0300     bool IsCsect;
0301 
0302     XCOFFSectionKey(StringRef SectionName,
0303                     XCOFF::StorageMappingClass MappingClass)
0304         : SectionName(SectionName), MappingClass(MappingClass), IsCsect(true) {}
0305 
0306     XCOFFSectionKey(StringRef SectionName,
0307                     XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags)
0308         : SectionName(SectionName), DwarfSubtypeFlags(DwarfSubtypeFlags),
0309           IsCsect(false) {}
0310 
0311     bool operator<(const XCOFFSectionKey &Other) const {
0312       if (IsCsect && Other.IsCsect)
0313         return std::tie(SectionName, MappingClass) <
0314                std::tie(Other.SectionName, Other.MappingClass);
0315       if (IsCsect != Other.IsCsect)
0316         return IsCsect;
0317       return std::tie(SectionName, DwarfSubtypeFlags) <
0318              std::tie(Other.SectionName, Other.DwarfSubtypeFlags);
0319     }
0320   };
0321 
0322   StringMap<MCSectionMachO *> MachOUniquingMap;
0323   std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
0324   StringMap<MCSectionELF *> ELFUniquingMap;
0325   std::map<std::string, MCSectionGOFF *> GOFFUniquingMap;
0326   std::map<WasmSectionKey, MCSectionWasm *> WasmUniquingMap;
0327   std::map<XCOFFSectionKey, MCSectionXCOFF *> XCOFFUniquingMap;
0328   StringMap<MCSectionDXContainer *> DXCUniquingMap;
0329   StringMap<bool> RelSecNames;
0330 
0331   SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
0332 
0333   /// Do automatic reset in destructor
0334   bool AutoReset;
0335 
0336   MCTargetOptions const *TargetOptions;
0337 
0338   bool HadError = false;
0339 
0340   void reportCommon(SMLoc Loc,
0341                     std::function<void(SMDiagnostic &, const SourceMgr *)>);
0342 
0343   MCDataFragment *allocInitialFragment(MCSection &Sec);
0344 
0345   MCSymbolTableEntry &getSymbolTableEntry(StringRef Name);
0346 
0347   MCSymbol *createSymbolImpl(const MCSymbolTableEntry *Name, bool IsTemporary);
0348   MCSymbol *createRenamableSymbol(const Twine &Name, bool AlwaysAddSuffix,
0349                                   bool IsTemporary);
0350 
0351   MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
0352                                               unsigned Instance);
0353 
0354   template <typename Symbol>
0355   Symbol *getOrCreateSectionSymbol(StringRef Section);
0356 
0357   MCSectionELF *createELFSectionImpl(StringRef Section, unsigned Type,
0358                                      unsigned Flags, unsigned EntrySize,
0359                                      const MCSymbolELF *Group, bool IsComdat,
0360                                      unsigned UniqueID,
0361                                      const MCSymbolELF *LinkedToSym);
0362 
0363   MCSymbolXCOFF *createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,
0364                                        bool IsTemporary);
0365 
0366   /// Map of currently defined macros.
0367   StringMap<MCAsmMacro> MacroMap;
0368 
0369   // Symbols must be assigned to a section with a compatible entry size and
0370   // flags. This map is used to assign unique IDs to sections to distinguish
0371   // between sections with identical names but incompatible entry sizes and/or
0372   // flags. This can occur when a symbol is explicitly assigned to a section,
0373   // e.g. via __attribute__((section("myname"))). The map key is the tuple
0374   // (section name, flags, entry size).
0375   DenseMap<std::tuple<StringRef, unsigned, unsigned>, unsigned> ELFEntrySizeMap;
0376 
0377   // This set is used to record the generic mergeable section names seen.
0378   // These are sections that are created as mergeable e.g. .debug_str. We need
0379   // to avoid assigning non-mergeable symbols to these sections. It is used
0380   // to prevent non-mergeable symbols being explicitly assigned  to mergeable
0381   // sections (e.g. via _attribute_((section("myname")))).
0382   DenseSet<StringRef> ELFSeenGenericMergeableSections;
0383 
0384 public:
0385   explicit MCContext(const Triple &TheTriple, const MCAsmInfo *MAI,
0386                      const MCRegisterInfo *MRI, const MCSubtargetInfo *MSTI,
0387                      const SourceMgr *Mgr = nullptr,
0388                      MCTargetOptions const *TargetOpts = nullptr,
0389                      bool DoAutoReset = true,
0390                      StringRef Swift5ReflSegmentName = {});
0391   MCContext(const MCContext &) = delete;
0392   MCContext &operator=(const MCContext &) = delete;
0393   ~MCContext();
0394 
0395   Environment getObjectFileType() const { return Env; }
0396 
0397   const StringRef &getSwift5ReflectionSegmentName() const {
0398     return Swift5ReflectionSegmentName;
0399   }
0400   const Triple &getTargetTriple() const { return TT; }
0401   const SourceMgr *getSourceManager() const { return SrcMgr; }
0402 
0403   void initInlineSourceManager();
0404   SourceMgr *getInlineSourceManager() { return InlineSrcMgr.get(); }
0405   std::vector<const MDNode *> &getLocInfos() { return LocInfos; }
0406   void setDiagnosticHandler(DiagHandlerTy DiagHandler) {
0407     this->DiagHandler = DiagHandler;
0408   }
0409 
0410   void setObjectFileInfo(const MCObjectFileInfo *Mofi) { MOFI = Mofi; }
0411 
0412   const MCAsmInfo *getAsmInfo() const { return MAI; }
0413 
0414   const MCRegisterInfo *getRegisterInfo() const { return MRI; }
0415 
0416   const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
0417 
0418   const MCSubtargetInfo *getSubtargetInfo() const { return MSTI; }
0419 
0420   const MCTargetOptions *getTargetOptions() const { return TargetOptions; }
0421 
0422   CodeViewContext &getCVContext();
0423 
0424   void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
0425 
0426   /// \name Module Lifetime Management
0427   /// @{
0428 
0429   /// reset - return object to right after construction state to prepare
0430   /// to process a new module
0431   void reset();
0432 
0433   /// @}
0434 
0435   /// \name McInst Management
0436 
0437   /// Create and return a new MC instruction.
0438   MCInst *createMCInst();
0439 
0440   template <typename F, typename... Args> F *allocFragment(Args &&...args) {
0441     return new (FragmentAllocator.Allocate(sizeof(F), alignof(F)))
0442         F(std::forward<Args>(args)...);
0443   }
0444 
0445   /// \name Symbol Management
0446   /// @{
0447 
0448   /// Create a new linker temporary symbol with the specified prefix (Name) or
0449   /// "tmp". This creates a "l"-prefixed symbol for Mach-O and is identical to
0450   /// createNamedTempSymbol for other object file formats.
0451   MCSymbol *createLinkerPrivateTempSymbol();
0452   MCSymbol *createLinkerPrivateSymbol(const Twine &Name);
0453 
0454   /// Create a temporary symbol with a unique name. The name will be omitted
0455   /// in the symbol table if UseNamesOnTempLabels is false (default except
0456   /// MCAsmStreamer). The overload without Name uses an unspecified name.
0457   MCSymbol *createTempSymbol();
0458   MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix = true);
0459 
0460   /// Create a temporary symbol with a unique name whose name cannot be
0461   /// omitted in the symbol table. This is rarely used.
0462   MCSymbol *createNamedTempSymbol();
0463   MCSymbol *createNamedTempSymbol(const Twine &Name);
0464 
0465   /// Get or create a symbol for a basic block. For non-always-emit symbols,
0466   /// this behaves like createTempSymbol, except that it uses the
0467   /// PrivateLabelPrefix instead of the PrivateGlobalPrefix. When AlwaysEmit is
0468   /// true, behaves like getOrCreateSymbol, prefixed with PrivateLabelPrefix.
0469   MCSymbol *createBlockSymbol(const Twine &Name, bool AlwaysEmit = false);
0470 
0471   /// Create a local, non-temporary symbol like an ELF mapping symbol. Calling
0472   /// the function with the same name will generate new, unique instances.
0473   MCSymbol *createLocalSymbol(StringRef Name);
0474 
0475   /// Create the definition of a directional local symbol for numbered label
0476   /// (used for "1:" definitions).
0477   MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
0478 
0479   /// Create and return a directional local symbol for numbered label (used
0480   /// for "1b" or 1f" references).
0481   MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
0482 
0483   /// Lookup the symbol inside with the specified \p Name.  If it exists,
0484   /// return it.  If not, create a forward reference and return it.
0485   ///
0486   /// \param Name - The symbol name, which must be unique across all symbols.
0487   MCSymbol *getOrCreateSymbol(const Twine &Name);
0488 
0489   /// Gets a symbol that will be defined to the final stack offset of a local
0490   /// variable after codegen.
0491   ///
0492   /// \param Idx - The index of a local variable passed to \@llvm.localescape.
0493   MCSymbol *getOrCreateFrameAllocSymbol(const Twine &FuncName, unsigned Idx);
0494 
0495   MCSymbol *getOrCreateParentFrameOffsetSymbol(const Twine &FuncName);
0496 
0497   MCSymbol *getOrCreateLSDASymbol(const Twine &FuncName);
0498 
0499   /// Get the symbol for \p Name, or null.
0500   MCSymbol *lookupSymbol(const Twine &Name) const;
0501 
0502   /// Set value for a symbol.
0503   void setSymbolValue(MCStreamer &Streamer, const Twine &Sym, uint64_t Val);
0504 
0505   /// getSymbols - Get a reference for the symbol table for clients that
0506   /// want to, for example, iterate over all symbols. 'const' because we
0507   /// still want any modifications to the table itself to use the MCContext
0508   /// APIs.
0509   const SymbolTable &getSymbols() const { return Symbols; }
0510 
0511   /// isInlineAsmLabel - Return true if the name is a label referenced in
0512   /// inline assembly.
0513   MCSymbol *getInlineAsmLabel(StringRef Name) const {
0514     return InlineAsmUsedLabelNames.lookup(Name);
0515   }
0516 
0517   /// registerInlineAsmLabel - Records that the name is a label referenced in
0518   /// inline assembly.
0519   void registerInlineAsmLabel(MCSymbol *Sym);
0520 
0521   /// Allocates and returns a new `WasmSignature` instance (with empty parameter
0522   /// and return type lists).
0523   wasm::WasmSignature *createWasmSignature();
0524 
0525   /// @}
0526 
0527   /// \name Section Management
0528   /// @{
0529 
0530   enum : unsigned {
0531     /// Pass this value as the UniqueID during section creation to get the
0532     /// generic section with the given name and characteristics. The usual
0533     /// sections such as .text use this ID.
0534     GenericSectionID = ~0U
0535   };
0536 
0537   /// Return the MCSection for the specified mach-o section.  This requires
0538   /// the operands to be valid.
0539   MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
0540                                   unsigned TypeAndAttributes,
0541                                   unsigned Reserved2, SectionKind K,
0542                                   const char *BeginSymName = nullptr);
0543 
0544   MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
0545                                   unsigned TypeAndAttributes, SectionKind K,
0546                                   const char *BeginSymName = nullptr) {
0547     return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
0548                            BeginSymName);
0549   }
0550 
0551   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
0552                               unsigned Flags) {
0553     return getELFSection(Section, Type, Flags, 0, "", false);
0554   }
0555 
0556   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
0557                               unsigned Flags, unsigned EntrySize) {
0558     return getELFSection(Section, Type, Flags, EntrySize, "", false,
0559                          MCSection::NonUniqueID, nullptr);
0560   }
0561 
0562   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
0563                               unsigned Flags, unsigned EntrySize,
0564                               const Twine &Group, bool IsComdat) {
0565     return getELFSection(Section, Type, Flags, EntrySize, Group, IsComdat,
0566                          MCSection::NonUniqueID, nullptr);
0567   }
0568 
0569   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
0570                               unsigned Flags, unsigned EntrySize,
0571                               const Twine &Group, bool IsComdat,
0572                               unsigned UniqueID,
0573                               const MCSymbolELF *LinkedToSym);
0574 
0575   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
0576                               unsigned Flags, unsigned EntrySize,
0577                               const MCSymbolELF *Group, bool IsComdat,
0578                               unsigned UniqueID,
0579                               const MCSymbolELF *LinkedToSym);
0580 
0581   /// Get a section with the provided group identifier. This section is
0582   /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
0583   /// describes the type of the section and \p Flags are used to further
0584   /// configure this named section.
0585   MCSectionELF *getELFNamedSection(const Twine &Prefix, const Twine &Suffix,
0586                                    unsigned Type, unsigned Flags,
0587                                    unsigned EntrySize = 0);
0588 
0589   MCSectionELF *createELFRelSection(const Twine &Name, unsigned Type,
0590                                     unsigned Flags, unsigned EntrySize,
0591                                     const MCSymbolELF *Group,
0592                                     const MCSectionELF *RelInfoSection);
0593 
0594   MCSectionELF *createELFGroupSection(const MCSymbolELF *Group, bool IsComdat);
0595 
0596   void recordELFMergeableSectionInfo(StringRef SectionName, unsigned Flags,
0597                                      unsigned UniqueID, unsigned EntrySize);
0598 
0599   bool isELFImplicitMergeableSectionNamePrefix(StringRef Name);
0600 
0601   bool isELFGenericMergeableSection(StringRef Name);
0602 
0603   /// Return the unique ID of the section with the given name, flags and entry
0604   /// size, if it exists.
0605   std::optional<unsigned> getELFUniqueIDForEntsize(StringRef SectionName,
0606                                                    unsigned Flags,
0607                                                    unsigned EntrySize);
0608 
0609   MCSectionGOFF *getGOFFSection(StringRef Section, SectionKind Kind,
0610                                 MCSection *Parent, uint32_t Subsection = 0);
0611 
0612   MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
0613                                 StringRef COMDATSymName, int Selection,
0614                                 unsigned UniqueID = GenericSectionID);
0615 
0616   MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics);
0617 
0618   /// Gets or creates a section equivalent to Sec that is associated with the
0619   /// section containing KeySym. For example, to create a debug info section
0620   /// associated with an inline function, pass the normal debug info section
0621   /// as Sec and the function symbol as KeySym.
0622   MCSectionCOFF *
0623   getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
0624                             unsigned UniqueID = GenericSectionID);
0625 
0626   MCSectionSPIRV *getSPIRVSection();
0627 
0628   MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
0629                                 unsigned Flags = 0) {
0630     return getWasmSection(Section, K, Flags, "", ~0);
0631   }
0632 
0633   MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
0634                                 unsigned Flags, const Twine &Group,
0635                                 unsigned UniqueID);
0636 
0637   MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
0638                                 unsigned Flags, const MCSymbolWasm *Group,
0639                                 unsigned UniqueID);
0640 
0641   /// Get the section for the provided Section name
0642   MCSectionDXContainer *getDXContainerSection(StringRef Section, SectionKind K);
0643 
0644   bool hasXCOFFSection(StringRef Section,
0645                        XCOFF::CsectProperties CsectProp) const;
0646 
0647   MCSectionXCOFF *getXCOFFSection(
0648       StringRef Section, SectionKind K,
0649       std::optional<XCOFF::CsectProperties> CsectProp = std::nullopt,
0650       bool MultiSymbolsAllowed = false,
0651       std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSubtypeFlags =
0652           std::nullopt);
0653 
0654   // Create and save a copy of STI and return a reference to the copy.
0655   MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
0656 
0657   uint8_t getBBAddrMapVersion() const { return BBAddrMapVersion; }
0658 
0659   /// @}
0660 
0661   /// \name Dwarf Management
0662   /// @{
0663 
0664   /// Get the compilation directory for DW_AT_comp_dir
0665   /// The compilation directory should be set with \c setCompilationDir before
0666   /// calling this function. If it is unset, an empty string will be returned.
0667   StringRef getCompilationDir() const { return CompilationDir; }
0668 
0669   /// Set the compilation directory for DW_AT_comp_dir
0670   void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
0671 
0672   /// Add an entry to the debug prefix map.
0673   void addDebugPrefixMapEntry(const std::string &From, const std::string &To);
0674 
0675   /// Remap one path in-place as per the debug prefix map.
0676   void remapDebugPath(SmallVectorImpl<char> &Path);
0677 
0678   // Remaps all debug directory paths in-place as per the debug prefix map.
0679   void RemapDebugPaths();
0680 
0681   /// Get the main file name for use in error messages and debug
0682   /// info. This can be set to ensure we've got the correct file name
0683   /// after preprocessing or for -save-temps.
0684   const std::string &getMainFileName() const { return MainFileName; }
0685 
0686   /// Set the main file name and override the default.
0687   void setMainFileName(StringRef S) { MainFileName = std::string(S); }
0688 
0689   /// Creates an entry in the dwarf file and directory tables.
0690   Expected<unsigned> getDwarfFile(StringRef Directory, StringRef FileName,
0691                                   unsigned FileNumber,
0692                                   std::optional<MD5::MD5Result> Checksum,
0693                                   std::optional<StringRef> Source,
0694                                   unsigned CUID);
0695 
0696   bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
0697 
0698   const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
0699     return MCDwarfLineTablesCUMap;
0700   }
0701 
0702   MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
0703     return MCDwarfLineTablesCUMap[CUID];
0704   }
0705 
0706   const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
0707     auto I = MCDwarfLineTablesCUMap.find(CUID);
0708     assert(I != MCDwarfLineTablesCUMap.end());
0709     return I->second;
0710   }
0711 
0712   const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
0713     return getMCDwarfLineTable(CUID).getMCDwarfFiles();
0714   }
0715 
0716   const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
0717     return getMCDwarfLineTable(CUID).getMCDwarfDirs();
0718   }
0719 
0720   unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
0721 
0722   void setDwarfCompileUnitID(unsigned CUIndex) { DwarfCompileUnitID = CUIndex; }
0723 
0724   /// Specifies the "root" file and directory of the compilation unit.
0725   /// These are "file 0" and "directory 0" in DWARF v5.
0726   void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir,
0727                               StringRef Filename,
0728                               std::optional<MD5::MD5Result> Checksum,
0729                               std::optional<StringRef> Source) {
0730     getMCDwarfLineTable(CUID).setRootFile(CompilationDir, Filename, Checksum,
0731                                           Source);
0732   }
0733 
0734   /// Reports whether MD5 checksum usage is consistent (all-or-none).
0735   bool isDwarfMD5UsageConsistent(unsigned CUID) const {
0736     return getMCDwarfLineTable(CUID).isMD5UsageConsistent();
0737   }
0738 
0739   /// Saves the information from the currently parsed dwarf .loc directive
0740   /// and sets DwarfLocSeen.  When the next instruction is assembled an entry
0741   /// in the line number table with this information and the address of the
0742   /// instruction will be created.
0743   void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
0744                           unsigned Flags, unsigned Isa,
0745                           unsigned Discriminator) {
0746     CurrentDwarfLoc.setFileNum(FileNum);
0747     CurrentDwarfLoc.setLine(Line);
0748     CurrentDwarfLoc.setColumn(Column);
0749     CurrentDwarfLoc.setFlags(Flags);
0750     CurrentDwarfLoc.setIsa(Isa);
0751     CurrentDwarfLoc.setDiscriminator(Discriminator);
0752     DwarfLocSeen = true;
0753   }
0754 
0755   void clearDwarfLocSeen() { DwarfLocSeen = false; }
0756 
0757   bool getDwarfLocSeen() { return DwarfLocSeen; }
0758   const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
0759 
0760   bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
0761   void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
0762   unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
0763   EmitDwarfUnwindType emitDwarfUnwindInfo() const;
0764   bool emitCompactUnwindNonCanonical() const;
0765 
0766   void setGenDwarfFileNumber(unsigned FileNumber) {
0767     GenDwarfFileNumber = FileNumber;
0768   }
0769 
0770   /// Specifies information about the "root file" for assembler clients
0771   /// (e.g., llvm-mc). Assumes compilation dir etc. have been set up.
0772   void setGenDwarfRootFile(StringRef FileName, StringRef Buffer);
0773 
0774   const SetVector<MCSection *> &getGenDwarfSectionSyms() {
0775     return SectionsForRanges;
0776   }
0777 
0778   bool addGenDwarfSection(MCSection *Sec) {
0779     return SectionsForRanges.insert(Sec);
0780   }
0781 
0782   void finalizeDwarfSections(MCStreamer &MCOS);
0783 
0784   const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
0785     return MCGenDwarfLabelEntries;
0786   }
0787 
0788   void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
0789     MCGenDwarfLabelEntries.push_back(E);
0790   }
0791 
0792   void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
0793   StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
0794 
0795   void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
0796   StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
0797 
0798   void setDwarfFormat(dwarf::DwarfFormat f) { DwarfFormat = f; }
0799   dwarf::DwarfFormat getDwarfFormat() const { return DwarfFormat; }
0800 
0801   void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
0802   uint16_t getDwarfVersion() const { return DwarfVersion; }
0803 
0804   /// @}
0805 
0806   StringRef getSecureLogFile() { return SecureLogFile; }
0807   raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
0808 
0809   void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
0810     SecureLog = std::move(Value);
0811   }
0812 
0813   bool getSecureLogUsed() { return SecureLogUsed; }
0814   void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
0815 
0816   void *allocate(unsigned Size, unsigned Align = 8) {
0817     return Allocator.Allocate(Size, Align);
0818   }
0819 
0820   void deallocate(void *Ptr) {}
0821 
0822   /// Allocates a copy of the given string on the allocator managed by this
0823   /// context and returns the result.
0824   StringRef allocateString(StringRef s) {
0825     return StringSaver(Allocator).save(s);
0826   }
0827 
0828   bool hadError() { return HadError; }
0829   void diagnose(const SMDiagnostic &SMD);
0830   void reportError(SMLoc L, const Twine &Msg);
0831   void reportWarning(SMLoc L, const Twine &Msg);
0832 
0833   MCAsmMacro *lookupMacro(StringRef Name) {
0834     StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
0835     return (I == MacroMap.end()) ? nullptr : &I->getValue();
0836   }
0837 
0838   void defineMacro(StringRef Name, MCAsmMacro Macro) {
0839     MacroMap.insert(std::make_pair(Name, std::move(Macro)));
0840   }
0841 
0842   void undefineMacro(StringRef Name) { MacroMap.erase(Name); }
0843 
0844   MCPseudoProbeTable &getMCPseudoProbeTable() { return PseudoProbeTable; }
0845 };
0846 
0847 } // end namespace llvm
0848 
0849 // operator new and delete aren't allowed inside namespaces.
0850 // The throw specifications are mandated by the standard.
0851 /// Placement new for using the MCContext's allocator.
0852 ///
0853 /// This placement form of operator new uses the MCContext's allocator for
0854 /// obtaining memory. It is a non-throwing new, which means that it returns
0855 /// null on error. (If that is what the allocator does. The current does, so if
0856 /// this ever changes, this operator will have to be changed, too.)
0857 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
0858 /// \code
0859 /// // Default alignment (8)
0860 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
0861 /// // Specific alignment
0862 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
0863 /// \endcode
0864 /// Please note that you cannot use delete on the pointer; it must be
0865 /// deallocated using an explicit destructor call followed by
0866 /// \c Context.Deallocate(Ptr).
0867 ///
0868 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
0869 /// \param C The MCContext that provides the allocator.
0870 /// \param Alignment The alignment of the allocated memory (if the underlying
0871 ///                  allocator supports it).
0872 /// \return The allocated memory. Could be NULL.
0873 inline void *operator new(size_t Bytes, llvm::MCContext &C,
0874                           size_t Alignment = 8) noexcept {
0875   return C.allocate(Bytes, Alignment);
0876 }
0877 /// Placement delete companion to the new above.
0878 ///
0879 /// This operator is just a companion to the new above. There is no way of
0880 /// invoking it directly; see the new operator for more details. This operator
0881 /// is called implicitly by the compiler if a placement new expression using
0882 /// the MCContext throws in the object constructor.
0883 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept {
0884   C.deallocate(Ptr);
0885 }
0886 
0887 /// This placement form of operator new[] uses the MCContext's allocator for
0888 /// obtaining memory. It is a non-throwing new[], which means that it returns
0889 /// null on error.
0890 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
0891 /// \code
0892 /// // Default alignment (8)
0893 /// char *data = new (Context) char[10];
0894 /// // Specific alignment
0895 /// char *data = new (Context, 4) char[10];
0896 /// \endcode
0897 /// Please note that you cannot use delete on the pointer; it must be
0898 /// deallocated using an explicit destructor call followed by
0899 /// \c Context.Deallocate(Ptr).
0900 ///
0901 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
0902 /// \param C The MCContext that provides the allocator.
0903 /// \param Alignment The alignment of the allocated memory (if the underlying
0904 ///                  allocator supports it).
0905 /// \return The allocated memory. Could be NULL.
0906 inline void *operator new[](size_t Bytes, llvm::MCContext &C,
0907                             size_t Alignment = 8) noexcept {
0908   return C.allocate(Bytes, Alignment);
0909 }
0910 
0911 /// Placement delete[] companion to the new[] above.
0912 ///
0913 /// This operator is just a companion to the new[] above. There is no way of
0914 /// invoking it directly; see the new[] operator for more details. This operator
0915 /// is called implicitly by the compiler if a placement new[] expression using
0916 /// the MCContext throws in the object constructor.
0917 inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept {
0918   C.deallocate(Ptr);
0919 }
0920 
0921 #endif // LLVM_MC_MCCONTEXT_H