xref: /freebsd/contrib/llvm-project/llvm/include/llvm/MC/MCContext.h (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
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 #ifndef LLVM_MC_MCCONTEXT_H
10 #define LLVM_MC_MCCONTEXT_H
11 
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/BinaryFormat/XCOFF.h"
20 #include "llvm/MC/MCAsmMacro.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCGOFFAttributes.h"
23 #include "llvm/MC/MCPseudoProbe.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionGOFF.h"
26 #include "llvm/MC/MCSymbolTableEntry.h"
27 #include "llvm/MC/SectionKind.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Error.h"
31 #include "llvm/Support/MD5.h"
32 #include "llvm/Support/StringSaver.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstddef>
37 #include <cstdint>
38 #include <functional>
39 #include <map>
40 #include <memory>
41 #include <optional>
42 #include <string>
43 #include <utility>
44 #include <vector>
45 
46 namespace llvm {
47 
48 class CodeViewContext;
49 class MCAsmInfo;
50 class MCDataFragment;
51 class MCInst;
52 class MCLabel;
53 class MCObjectFileInfo;
54 class MCRegisterInfo;
55 class MCSection;
56 class MCSectionCOFF;
57 class MCSectionDXContainer;
58 class MCSectionELF;
59 class MCSectionMachO;
60 class MCSectionSPIRV;
61 class MCSectionWasm;
62 class MCSectionXCOFF;
63 class MCStreamer;
64 class MCSubtargetInfo;
65 class MCSymbol;
66 class MCSymbolELF;
67 class MCSymbolWasm;
68 class MCSymbolXCOFF;
69 class MCTargetOptions;
70 class MDNode;
71 template <typename T> class SmallVectorImpl;
72 class SMDiagnostic;
73 class SMLoc;
74 class SourceMgr;
75 enum class EmitDwarfUnwindType;
76 
77 namespace wasm {
78 struct WasmSignature;
79 }
80 
81 /// Context object for machine code objects.  This class owns all of the
82 /// sections that it creates.
83 ///
84 class MCContext {
85 public:
86   using SymbolTable = StringMap<MCSymbolTableValue, BumpPtrAllocator &>;
87   using DiagHandlerTy =
88       std::function<void(const SMDiagnostic &, bool, const SourceMgr &,
89                          std::vector<const MDNode *> &)>;
90   enum Environment {
91     IsMachO,
92     IsELF,
93     IsGOFF,
94     IsCOFF,
95     IsSPIRV,
96     IsWasm,
97     IsXCOFF,
98     IsDXContainer
99   };
100 
101 private:
102   Environment Env;
103 
104   /// The name of the Segment where Swift5 Reflection Section data will be
105   /// outputted
106   StringRef Swift5ReflectionSegmentName;
107 
108   /// The triple for this object.
109   Triple TT;
110 
111   /// The SourceMgr for this object, if any.
112   const SourceMgr *SrcMgr = nullptr;
113 
114   /// The SourceMgr for inline assembly, if any.
115   std::unique_ptr<SourceMgr> InlineSrcMgr;
116   std::vector<const MDNode *> LocInfos;
117 
118   DiagHandlerTy DiagHandler;
119 
120   /// The MCAsmInfo for this target.
121   const MCAsmInfo *MAI = nullptr;
122 
123   /// The MCRegisterInfo for this target.
124   const MCRegisterInfo *MRI = nullptr;
125 
126   /// The MCObjectFileInfo for this target.
127   const MCObjectFileInfo *MOFI = nullptr;
128 
129   /// The MCSubtargetInfo for this target.
130   const MCSubtargetInfo *MSTI = nullptr;
131 
132   std::unique_ptr<CodeViewContext> CVContext;
133 
134   /// Allocator object used for creating machine code objects.
135   ///
136   /// We use a bump pointer allocator to avoid the need to track all allocated
137   /// objects.
138   BumpPtrAllocator Allocator;
139 
140   /// For MCFragment instances.
141   BumpPtrAllocator FragmentAllocator;
142 
143   SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
144   SpecificBumpPtrAllocator<MCSectionDXContainer> DXCAllocator;
145   SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
146   SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
147   SpecificBumpPtrAllocator<MCSectionGOFF> GOFFAllocator;
148   SpecificBumpPtrAllocator<MCSectionSPIRV> SPIRVAllocator;
149   SpecificBumpPtrAllocator<MCSectionWasm> WasmAllocator;
150   SpecificBumpPtrAllocator<MCSectionXCOFF> XCOFFAllocator;
151   SpecificBumpPtrAllocator<MCInst> MCInstAllocator;
152 
153   SpecificBumpPtrAllocator<wasm::WasmSignature> WasmSignatureAllocator;
154 
155   /// Bindings of names to symbol table values.
156   SymbolTable Symbols;
157 
158   /// A mapping from a local label number and an instance count to a symbol.
159   /// For example, in the assembly
160   ///     1:
161   ///     2:
162   ///     1:
163   /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
164   DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
165 
166   /// Keeps track of labels that are used in inline assembly.
167   StringMap<MCSymbol *, BumpPtrAllocator &> InlineAsmUsedLabelNames;
168 
169   /// Instances of directional local labels.
170   DenseMap<unsigned, MCLabel *> Instances;
171   /// NextInstance() creates the next instance of the directional local label
172   /// for the LocalLabelVal and adds it to the map if needed.
173   unsigned NextInstance(unsigned LocalLabelVal);
174   /// GetInstance() gets the current instance of the directional local label
175   /// for the LocalLabelVal and adds it to the map if needed.
176   unsigned GetInstance(unsigned LocalLabelVal);
177 
178   /// SHT_LLVM_BB_ADDR_MAP version to emit.
179   uint8_t BBAddrMapVersion = 3;
180 
181   /// The file name of the log file from the environment variable
182   /// AS_SECURE_LOG_FILE.  Which must be set before the .secure_log_unique
183   /// directive is used or it is an error.
184   std::string SecureLogFile;
185   /// The stream that gets written to for the .secure_log_unique directive.
186   std::unique_ptr<raw_fd_ostream> SecureLog;
187   /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
188   /// catch errors if .secure_log_unique appears twice without
189   /// .secure_log_reset appearing between them.
190   bool SecureLogUsed = false;
191 
192   /// The compilation directory to use for DW_AT_comp_dir.
193   SmallString<128> CompilationDir;
194 
195   /// Prefix replacement map for source file information.
196   SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap;
197 
198   /// The main file name if passed in explicitly.
199   std::string MainFileName;
200 
201   /// The dwarf file and directory tables from the dwarf .file directive.
202   /// We now emit a line table for each compile unit. To reduce the prologue
203   /// size of each line table, the files and directories used by each compile
204   /// unit are separated.
205   std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
206 
207   /// The current dwarf line information from the last dwarf .loc directive.
208   MCDwarfLoc CurrentDwarfLoc;
209   bool DwarfLocSeen = false;
210 
211   /// Generate dwarf debugging info for assembly source files.
212   bool GenDwarfForAssembly = false;
213 
214   /// The current dwarf file number when generate dwarf debugging info for
215   /// assembly source files.
216   unsigned GenDwarfFileNumber = 0;
217 
218   /// Sections for generating the .debug_ranges and .debug_aranges sections.
219   SetVector<MCSection *> SectionsForRanges;
220 
221   /// The information gathered from labels that will have dwarf label
222   /// entries when generating dwarf assembly source files.
223   std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
224 
225   /// The string to embed in the debug information for the compile unit, if
226   /// non-empty.
227   StringRef DwarfDebugFlags;
228 
229   /// The string to embed in as the dwarf AT_producer for the compile unit, if
230   /// non-empty.
231   StringRef DwarfDebugProducer;
232 
233   /// The maximum version of dwarf that we should emit.
234   uint16_t DwarfVersion = 4;
235 
236   /// The format of dwarf that we emit.
237   dwarf::DwarfFormat DwarfFormat = dwarf::DWARF32;
238 
239   /// Honor temporary labels, this is useful for debugging semantic
240   /// differences between temporary and non-temporary labels (primarily on
241   /// Darwin).
242   bool SaveTempLabels = false;
243   bool UseNamesOnTempLabels = false;
244 
245   /// The Compile Unit ID that we are currently processing.
246   unsigned DwarfCompileUnitID = 0;
247 
248   /// A collection of MCPseudoProbe in the current module
249   MCPseudoProbeTable PseudoProbeTable;
250 
251   struct COFFSectionKey {
252     std::string SectionName;
253     StringRef GroupName;
254     int SelectionKey;
255     unsigned UniqueID;
256 
COFFSectionKeyCOFFSectionKey257     COFFSectionKey(StringRef SectionName, StringRef GroupName, int SelectionKey,
258                    unsigned UniqueID)
259         : SectionName(SectionName), GroupName(GroupName),
260           SelectionKey(SelectionKey), UniqueID(UniqueID) {}
261 
262     bool operator<(const COFFSectionKey &Other) const {
263       return std::tie(SectionName, GroupName, SelectionKey, UniqueID) <
264              std::tie(Other.SectionName, Other.GroupName, Other.SelectionKey,
265                       Other.UniqueID);
266     }
267   };
268 
269   struct WasmSectionKey {
270     std::string SectionName;
271     StringRef GroupName;
272     unsigned UniqueID;
273 
WasmSectionKeyWasmSectionKey274     WasmSectionKey(StringRef SectionName, StringRef GroupName,
275                    unsigned UniqueID)
276         : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {}
277 
278     bool operator<(const WasmSectionKey &Other) const {
279       return std::tie(SectionName, GroupName, UniqueID) <
280              std::tie(Other.SectionName, Other.GroupName, Other.UniqueID);
281     }
282   };
283 
284   struct XCOFFSectionKey {
285     // Section name.
286     std::string SectionName;
287     // Section property.
288     // For csect section, it is storage mapping class.
289     // For debug section, it is section type flags.
290     union {
291       XCOFF::StorageMappingClass MappingClass;
292       XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags;
293     };
294     bool IsCsect;
295 
XCOFFSectionKeyXCOFFSectionKey296     XCOFFSectionKey(StringRef SectionName,
297                     XCOFF::StorageMappingClass MappingClass)
298         : SectionName(SectionName), MappingClass(MappingClass), IsCsect(true) {}
299 
XCOFFSectionKeyXCOFFSectionKey300     XCOFFSectionKey(StringRef SectionName,
301                     XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags)
302         : SectionName(SectionName), DwarfSubtypeFlags(DwarfSubtypeFlags),
303           IsCsect(false) {}
304 
305     bool operator<(const XCOFFSectionKey &Other) const {
306       if (IsCsect && Other.IsCsect)
307         return std::tie(SectionName, MappingClass) <
308                std::tie(Other.SectionName, Other.MappingClass);
309       if (IsCsect != Other.IsCsect)
310         return IsCsect;
311       return std::tie(SectionName, DwarfSubtypeFlags) <
312              std::tie(Other.SectionName, Other.DwarfSubtypeFlags);
313     }
314   };
315 
316   StringMap<MCSectionMachO *> MachOUniquingMap;
317   std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
318   StringMap<MCSectionELF *> ELFUniquingMap;
319   std::map<std::string, MCSectionGOFF *> GOFFUniquingMap;
320   std::map<WasmSectionKey, MCSectionWasm *> WasmUniquingMap;
321   std::map<XCOFFSectionKey, MCSectionXCOFF *> XCOFFUniquingMap;
322   StringMap<MCSectionDXContainer *> DXCUniquingMap;
323   StringMap<bool> RelSecNames;
324 
325   SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
326 
327   /// Do automatic reset in destructor
328   bool AutoReset;
329 
330   MCTargetOptions const *TargetOptions;
331 
332   bool HadError = false;
333 
334   void reportCommon(SMLoc Loc,
335                     std::function<void(SMDiagnostic &, const SourceMgr *)>);
336 
337   MCDataFragment *allocInitialFragment(MCSection &Sec);
338 
339   MCSymbolTableEntry &getSymbolTableEntry(StringRef Name);
340 
341   MCSymbol *createSymbolImpl(const MCSymbolTableEntry *Name, bool IsTemporary);
342   MCSymbol *createRenamableSymbol(const Twine &Name, bool AlwaysAddSuffix,
343                                   bool IsTemporary);
344 
345   MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
346                                               unsigned Instance);
347 
348   template <typename Symbol>
349   Symbol *getOrCreateSectionSymbol(StringRef Section);
350 
351   MCSectionELF *createELFSectionImpl(StringRef Section, unsigned Type,
352                                      unsigned Flags, unsigned EntrySize,
353                                      const MCSymbolELF *Group, bool IsComdat,
354                                      unsigned UniqueID,
355                                      const MCSymbolELF *LinkedToSym);
356 
357   MCSymbolXCOFF *createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,
358                                        bool IsTemporary);
359 
360   template <typename TAttr>
361   MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
362                                 TAttr SDAttributes, MCSection *Parent,
363                                 bool IsVirtual);
364 
365   /// Map of currently defined macros.
366   StringMap<MCAsmMacro> MacroMap;
367 
368   // Symbols must be assigned to a section with a compatible entry size and
369   // flags. This map is used to assign unique IDs to sections to distinguish
370   // between sections with identical names but incompatible entry sizes and/or
371   // flags. This can occur when a symbol is explicitly assigned to a section,
372   // e.g. via __attribute__((section("myname"))). The map key is the tuple
373   // (section name, flags, entry size).
374   DenseMap<std::tuple<StringRef, unsigned, unsigned>, unsigned> ELFEntrySizeMap;
375 
376   // This set is used to record the generic mergeable section names seen.
377   // These are sections that are created as mergeable e.g. .debug_str. We need
378   // to avoid assigning non-mergeable symbols to these sections. It is used
379   // to prevent non-mergeable symbols being explicitly assigned  to mergeable
380   // sections (e.g. via _attribute_((section("myname")))).
381   DenseSet<StringRef> ELFSeenGenericMergeableSections;
382 
383 public:
384   LLVM_ABI explicit MCContext(const Triple &TheTriple, const MCAsmInfo *MAI,
385                               const MCRegisterInfo *MRI,
386                               const MCSubtargetInfo *MSTI,
387                               const SourceMgr *Mgr = nullptr,
388                               MCTargetOptions const *TargetOpts = nullptr,
389                               bool DoAutoReset = true,
390                               StringRef Swift5ReflSegmentName = {});
391   MCContext(const MCContext &) = delete;
392   MCContext &operator=(const MCContext &) = delete;
393   LLVM_ABI ~MCContext();
394 
getObjectFileType()395   Environment getObjectFileType() const { return Env; }
396 
getSwift5ReflectionSegmentName()397   const StringRef &getSwift5ReflectionSegmentName() const {
398     return Swift5ReflectionSegmentName;
399   }
getTargetTriple()400   const Triple &getTargetTriple() const { return TT; }
getSourceManager()401   const SourceMgr *getSourceManager() const { return SrcMgr; }
402 
403   LLVM_ABI void initInlineSourceManager();
getInlineSourceManager()404   SourceMgr *getInlineSourceManager() { return InlineSrcMgr.get(); }
getLocInfos()405   std::vector<const MDNode *> &getLocInfos() { return LocInfos; }
setDiagnosticHandler(DiagHandlerTy DiagHandler)406   void setDiagnosticHandler(DiagHandlerTy DiagHandler) {
407     this->DiagHandler = DiagHandler;
408   }
409 
setObjectFileInfo(const MCObjectFileInfo * Mofi)410   void setObjectFileInfo(const MCObjectFileInfo *Mofi) { MOFI = Mofi; }
411 
getAsmInfo()412   const MCAsmInfo *getAsmInfo() const { return MAI; }
413 
getRegisterInfo()414   const MCRegisterInfo *getRegisterInfo() const { return MRI; }
415 
getObjectFileInfo()416   const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
417 
getSubtargetInfo()418   const MCSubtargetInfo *getSubtargetInfo() const { return MSTI; }
419 
getTargetOptions()420   const MCTargetOptions *getTargetOptions() const { return TargetOptions; }
421 
422   LLVM_ABI CodeViewContext &getCVContext();
423 
setUseNamesOnTempLabels(bool Value)424   void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
425 
426   /// \name Module Lifetime Management
427   /// @{
428 
429   /// reset - return object to right after construction state to prepare
430   /// to process a new module
431   LLVM_ABI void reset();
432 
433   /// @}
434 
435   /// \name McInst Management
436 
437   /// Create and return a new MC instruction.
438   LLVM_ABI MCInst *createMCInst();
439 
allocFragment(Args &&...args)440   template <typename F, typename... Args> F *allocFragment(Args &&...args) {
441     return new (FragmentAllocator.Allocate(sizeof(F), alignof(F)))
442         F(std::forward<Args>(args)...);
443   }
444 
445   /// \name Symbol Management
446   /// @{
447 
448   /// Create a new linker temporary symbol with the specified prefix (Name) or
449   /// "tmp". This creates a "l"-prefixed symbol for Mach-O and is identical to
450   /// createNamedTempSymbol for other object file formats.
451   LLVM_ABI MCSymbol *createLinkerPrivateTempSymbol();
452   LLVM_ABI MCSymbol *createLinkerPrivateSymbol(const Twine &Name);
453 
454   /// Create a temporary symbol with a unique name. The name will be omitted
455   /// in the symbol table if UseNamesOnTempLabels is false (default except
456   /// MCAsmStreamer). The overload without Name uses an unspecified name.
457   LLVM_ABI MCSymbol *createTempSymbol();
458   LLVM_ABI MCSymbol *createTempSymbol(const Twine &Name,
459                                       bool AlwaysAddSuffix = true);
460 
461   /// Create a temporary symbol with a unique name whose name cannot be
462   /// omitted in the symbol table. This is rarely used.
463   LLVM_ABI MCSymbol *createNamedTempSymbol();
464   LLVM_ABI MCSymbol *createNamedTempSymbol(const Twine &Name);
465 
466   /// Get or create a symbol for a basic block. For non-always-emit symbols,
467   /// this behaves like createTempSymbol, except that it uses the
468   /// PrivateLabelPrefix instead of the PrivateGlobalPrefix. When AlwaysEmit is
469   /// true, behaves like getOrCreateSymbol, prefixed with PrivateLabelPrefix.
470   LLVM_ABI MCSymbol *createBlockSymbol(const Twine &Name,
471                                        bool AlwaysEmit = false);
472 
473   /// Create a local, non-temporary symbol like an ELF mapping symbol. Calling
474   /// the function with the same name will generate new, unique instances.
475   LLVM_ABI MCSymbol *createLocalSymbol(StringRef Name);
476 
477   /// Create the definition of a directional local symbol for numbered label
478   /// (used for "1:" definitions).
479   LLVM_ABI MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
480 
481   /// Create and return a directional local symbol for numbered label (used
482   /// for "1b" or 1f" references).
483   LLVM_ABI MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal,
484                                                bool Before);
485 
486   /// Lookup the symbol inside with the specified \p Name.  If it exists,
487   /// return it.  If not, create a forward reference and return it.
488   ///
489   /// \param Name - The symbol name, which must be unique across all symbols.
490   LLVM_ABI MCSymbol *getOrCreateSymbol(const Twine &Name);
491 
492   /// Variant of getOrCreateSymbol that handles backslash-escaped symbols.
493   /// For example, parse "a\"b\\" as a"\.
494   LLVM_ABI MCSymbol *parseSymbol(const Twine &Name);
495 
496   /// Gets a symbol that will be defined to the final stack offset of a local
497   /// variable after codegen.
498   ///
499   /// \param Idx - The index of a local variable passed to \@llvm.localescape.
500   LLVM_ABI MCSymbol *getOrCreateFrameAllocSymbol(const Twine &FuncName,
501                                                  unsigned Idx);
502 
503   LLVM_ABI MCSymbol *getOrCreateParentFrameOffsetSymbol(const Twine &FuncName);
504 
505   LLVM_ABI MCSymbol *getOrCreateLSDASymbol(const Twine &FuncName);
506 
507   /// Get the symbol for \p Name, or null.
508   LLVM_ABI MCSymbol *lookupSymbol(const Twine &Name) const;
509 
510   /// Clone a symbol for the .set directive, replacing it in the symbol table.
511   /// Existing references to the original symbol remain unchanged, and the
512   /// original symbol is not emitted to the symbol table.
513   LLVM_ABI MCSymbol *cloneSymbol(MCSymbol &Sym);
514 
515   /// Set value for a symbol.
516   LLVM_ABI void setSymbolValue(MCStreamer &Streamer, const Twine &Sym,
517                                uint64_t Val);
518 
519   /// getSymbols - Get a reference for the symbol table for clients that
520   /// want to, for example, iterate over all symbols. 'const' because we
521   /// still want any modifications to the table itself to use the MCContext
522   /// APIs.
getSymbols()523   const SymbolTable &getSymbols() const { return Symbols; }
524 
525   /// isInlineAsmLabel - Return true if the name is a label referenced in
526   /// inline assembly.
getInlineAsmLabel(StringRef Name)527   MCSymbol *getInlineAsmLabel(StringRef Name) const {
528     return InlineAsmUsedLabelNames.lookup(Name);
529   }
530 
531   /// registerInlineAsmLabel - Records that the name is a label referenced in
532   /// inline assembly.
533   LLVM_ABI void registerInlineAsmLabel(MCSymbol *Sym);
534 
535   /// Allocates and returns a new `WasmSignature` instance (with empty parameter
536   /// and return type lists).
537   LLVM_ABI wasm::WasmSignature *createWasmSignature();
538 
539   /// @}
540 
541   /// \name Section Management
542   /// @{
543 
544   /// Return the MCSection for the specified mach-o section.  This requires
545   /// the operands to be valid.
546   LLVM_ABI MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
547                                            unsigned TypeAndAttributes,
548                                            unsigned Reserved2, SectionKind K,
549                                            const char *BeginSymName = nullptr);
550 
551   MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
552                                   unsigned TypeAndAttributes, SectionKind K,
553                                   const char *BeginSymName = nullptr) {
554     return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
555                            BeginSymName);
556   }
557 
getELFSection(const Twine & Section,unsigned Type,unsigned Flags)558   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
559                               unsigned Flags) {
560     return getELFSection(Section, Type, Flags, 0, "", false);
561   }
562 
getELFSection(const Twine & Section,unsigned Type,unsigned Flags,unsigned EntrySize)563   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
564                               unsigned Flags, unsigned EntrySize) {
565     return getELFSection(Section, Type, Flags, EntrySize, "", false,
566                          MCSection::NonUniqueID, nullptr);
567   }
568 
getELFSection(const Twine & Section,unsigned Type,unsigned Flags,unsigned EntrySize,const Twine & Group,bool IsComdat)569   MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
570                               unsigned Flags, unsigned EntrySize,
571                               const Twine &Group, bool IsComdat) {
572     return getELFSection(Section, Type, Flags, EntrySize, Group, IsComdat,
573                          MCSection::NonUniqueID, nullptr);
574   }
575 
576   LLVM_ABI MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
577                                        unsigned Flags, unsigned EntrySize,
578                                        const Twine &Group, bool IsComdat,
579                                        unsigned UniqueID,
580                                        const MCSymbolELF *LinkedToSym);
581 
582   LLVM_ABI MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
583                                        unsigned Flags, unsigned EntrySize,
584                                        const MCSymbolELF *Group, bool IsComdat,
585                                        unsigned UniqueID,
586                                        const MCSymbolELF *LinkedToSym);
587 
588   /// Get a section with the provided group identifier. This section is
589   /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
590   /// describes the type of the section and \p Flags are used to further
591   /// configure this named section.
592   LLVM_ABI MCSectionELF *getELFNamedSection(const Twine &Prefix,
593                                             const Twine &Suffix, unsigned Type,
594                                             unsigned Flags,
595                                             unsigned EntrySize = 0);
596 
597   LLVM_ABI MCSectionELF *
598   createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,
599                       unsigned EntrySize, const MCSymbolELF *Group,
600                       const MCSectionELF *RelInfoSection);
601 
602   LLVM_ABI MCSectionELF *createELFGroupSection(const MCSymbolELF *Group,
603                                                bool IsComdat);
604 
605   LLVM_ABI void recordELFMergeableSectionInfo(StringRef SectionName,
606                                               unsigned Flags, unsigned UniqueID,
607                                               unsigned EntrySize);
608 
609   LLVM_ABI bool isELFImplicitMergeableSectionNamePrefix(StringRef Name);
610 
611   LLVM_ABI bool isELFGenericMergeableSection(StringRef Name);
612 
613   /// Return the unique ID of the section with the given name, flags and entry
614   /// size, if it exists.
615   LLVM_ABI std::optional<unsigned>
616   getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags,
617                            unsigned EntrySize);
618 
619   LLVM_ABI MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
620                                          GOFF::SDAttr SDAttributes);
621   LLVM_ABI MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
622                                          GOFF::EDAttr EDAttributes,
623                                          MCSection *Parent);
624   LLVM_ABI MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
625                                          GOFF::PRAttr PRAttributes,
626                                          MCSection *Parent);
627 
628   LLVM_ABI MCSectionCOFF *
629   getCOFFSection(StringRef Section, unsigned Characteristics,
630                  StringRef COMDATSymName, int Selection,
631                  unsigned UniqueID = MCSection::NonUniqueID);
632 
633   LLVM_ABI MCSectionCOFF *getCOFFSection(StringRef Section,
634                                          unsigned Characteristics);
635 
636   /// Gets or creates a section equivalent to Sec that is associated with the
637   /// section containing KeySym. For example, to create a debug info section
638   /// associated with an inline function, pass the normal debug info section
639   /// as Sec and the function symbol as KeySym.
640   LLVM_ABI MCSectionCOFF *
641   getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
642                             unsigned UniqueID = MCSection::NonUniqueID);
643 
644   LLVM_ABI MCSectionSPIRV *getSPIRVSection();
645 
646   MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
647                                 unsigned Flags = 0) {
648     return getWasmSection(Section, K, Flags, "", ~0);
649   }
650 
651   LLVM_ABI MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
652                                          unsigned Flags, const Twine &Group,
653                                          unsigned UniqueID);
654 
655   LLVM_ABI MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
656                                          unsigned Flags,
657                                          const MCSymbolWasm *Group,
658                                          unsigned UniqueID);
659 
660   /// Get the section for the provided Section name
661   LLVM_ABI MCSectionDXContainer *getDXContainerSection(StringRef Section,
662                                                        SectionKind K);
663 
664   LLVM_ABI bool hasXCOFFSection(StringRef Section,
665                                 XCOFF::CsectProperties CsectProp) const;
666 
667   LLVM_ABI MCSectionXCOFF *getXCOFFSection(
668       StringRef Section, SectionKind K,
669       std::optional<XCOFF::CsectProperties> CsectProp = std::nullopt,
670       bool MultiSymbolsAllowed = false,
671       std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSubtypeFlags =
672           std::nullopt);
673 
674   // Create and save a copy of STI and return a reference to the copy.
675   LLVM_ABI MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
676 
getBBAddrMapVersion()677   uint8_t getBBAddrMapVersion() const { return BBAddrMapVersion; }
678 
679   /// @}
680 
681   /// \name Dwarf Management
682   /// @{
683 
684   /// Get the compilation directory for DW_AT_comp_dir
685   /// The compilation directory should be set with \c setCompilationDir before
686   /// calling this function. If it is unset, an empty string will be returned.
getCompilationDir()687   StringRef getCompilationDir() const { return CompilationDir; }
688 
689   /// Set the compilation directory for DW_AT_comp_dir
setCompilationDir(StringRef S)690   void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
691 
692   /// Add an entry to the debug prefix map.
693   LLVM_ABI void addDebugPrefixMapEntry(const std::string &From,
694                                        const std::string &To);
695 
696   /// Remap one path in-place as per the debug prefix map.
697   LLVM_ABI void remapDebugPath(SmallVectorImpl<char> &Path);
698 
699   // Remaps all debug directory paths in-place as per the debug prefix map.
700   LLVM_ABI void RemapDebugPaths();
701 
702   /// Get the main file name for use in error messages and debug
703   /// info. This can be set to ensure we've got the correct file name
704   /// after preprocessing or for -save-temps.
getMainFileName()705   const std::string &getMainFileName() const { return MainFileName; }
706 
707   /// Set the main file name and override the default.
setMainFileName(StringRef S)708   void setMainFileName(StringRef S) { MainFileName = std::string(S); }
709 
710   /// Creates an entry in the dwarf file and directory tables.
711   LLVM_ABI Expected<unsigned>
712   getDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber,
713                std::optional<MD5::MD5Result> Checksum,
714                std::optional<StringRef> Source, unsigned CUID);
715 
716   LLVM_ABI bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
717 
getMCDwarfLineTables()718   const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
719     return MCDwarfLineTablesCUMap;
720   }
721 
getMCDwarfLineTable(unsigned CUID)722   MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
723     return MCDwarfLineTablesCUMap[CUID];
724   }
725 
getMCDwarfLineTable(unsigned CUID)726   const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
727     auto I = MCDwarfLineTablesCUMap.find(CUID);
728     assert(I != MCDwarfLineTablesCUMap.end());
729     return I->second;
730   }
731 
732   const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
733     return getMCDwarfLineTable(CUID).getMCDwarfFiles();
734   }
735 
736   const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
737     return getMCDwarfLineTable(CUID).getMCDwarfDirs();
738   }
739 
getDwarfCompileUnitID()740   unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
741 
setDwarfCompileUnitID(unsigned CUIndex)742   void setDwarfCompileUnitID(unsigned CUIndex) { DwarfCompileUnitID = CUIndex; }
743 
744   /// Specifies the "root" file and directory of the compilation unit.
745   /// These are "file 0" and "directory 0" in DWARF v5.
setMCLineTableRootFile(unsigned CUID,StringRef CompilationDir,StringRef Filename,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source)746   void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir,
747                               StringRef Filename,
748                               std::optional<MD5::MD5Result> Checksum,
749                               std::optional<StringRef> Source) {
750     getMCDwarfLineTable(CUID).setRootFile(CompilationDir, Filename, Checksum,
751                                           Source);
752   }
753 
754   /// Reports whether MD5 checksum usage is consistent (all-or-none).
isDwarfMD5UsageConsistent(unsigned CUID)755   bool isDwarfMD5UsageConsistent(unsigned CUID) const {
756     return getMCDwarfLineTable(CUID).isMD5UsageConsistent();
757   }
758 
759   /// Saves the information from the currently parsed dwarf .loc directive
760   /// and sets DwarfLocSeen.  When the next instruction is assembled an entry
761   /// in the line number table with this information and the address of the
762   /// instruction will be created.
setCurrentDwarfLoc(unsigned FileNum,unsigned Line,unsigned Column,unsigned Flags,unsigned Isa,unsigned Discriminator)763   void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
764                           unsigned Flags, unsigned Isa,
765                           unsigned Discriminator) {
766     CurrentDwarfLoc.setFileNum(FileNum);
767     CurrentDwarfLoc.setLine(Line);
768     CurrentDwarfLoc.setColumn(Column);
769     CurrentDwarfLoc.setFlags(Flags);
770     CurrentDwarfLoc.setIsa(Isa);
771     CurrentDwarfLoc.setDiscriminator(Discriminator);
772     DwarfLocSeen = true;
773   }
774 
clearDwarfLocSeen()775   void clearDwarfLocSeen() { DwarfLocSeen = false; }
776 
getDwarfLocSeen()777   bool getDwarfLocSeen() { return DwarfLocSeen; }
getCurrentDwarfLoc()778   const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
779 
getGenDwarfForAssembly()780   bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
setGenDwarfForAssembly(bool Value)781   void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
getGenDwarfFileNumber()782   unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
783   LLVM_ABI EmitDwarfUnwindType emitDwarfUnwindInfo() const;
784   LLVM_ABI bool emitCompactUnwindNonCanonical() const;
785 
setGenDwarfFileNumber(unsigned FileNumber)786   void setGenDwarfFileNumber(unsigned FileNumber) {
787     GenDwarfFileNumber = FileNumber;
788   }
789 
790   /// Specifies information about the "root file" for assembler clients
791   /// (e.g., llvm-mc). Assumes compilation dir etc. have been set up.
792   LLVM_ABI void setGenDwarfRootFile(StringRef FileName, StringRef Buffer);
793 
getGenDwarfSectionSyms()794   const SetVector<MCSection *> &getGenDwarfSectionSyms() {
795     return SectionsForRanges;
796   }
797 
addGenDwarfSection(MCSection * Sec)798   bool addGenDwarfSection(MCSection *Sec) {
799     return SectionsForRanges.insert(Sec);
800   }
801 
802   LLVM_ABI void finalizeDwarfSections(MCStreamer &MCOS);
803 
getMCGenDwarfLabelEntries()804   const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
805     return MCGenDwarfLabelEntries;
806   }
807 
addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry & E)808   void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
809     MCGenDwarfLabelEntries.push_back(E);
810   }
811 
setDwarfDebugFlags(StringRef S)812   void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
getDwarfDebugFlags()813   StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
814 
setDwarfDebugProducer(StringRef S)815   void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
getDwarfDebugProducer()816   StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
817 
setDwarfFormat(dwarf::DwarfFormat f)818   void setDwarfFormat(dwarf::DwarfFormat f) { DwarfFormat = f; }
getDwarfFormat()819   dwarf::DwarfFormat getDwarfFormat() const { return DwarfFormat; }
820 
setDwarfVersion(uint16_t v)821   void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
getDwarfVersion()822   uint16_t getDwarfVersion() const { return DwarfVersion; }
823 
824   /// @}
825 
getSecureLogFile()826   StringRef getSecureLogFile() { return SecureLogFile; }
getSecureLog()827   raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
828 
setSecureLog(std::unique_ptr<raw_fd_ostream> Value)829   void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
830     SecureLog = std::move(Value);
831   }
832 
getSecureLogUsed()833   bool getSecureLogUsed() { return SecureLogUsed; }
setSecureLogUsed(bool Value)834   void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
835 
836   void *allocate(unsigned Size, unsigned Align = 8) {
837     return Allocator.Allocate(Size, Align);
838   }
839 
deallocate(void * Ptr)840   void deallocate(void *Ptr) {}
841 
842   /// Allocates a copy of the given string on the allocator managed by this
843   /// context and returns the result.
allocateString(StringRef s)844   StringRef allocateString(StringRef s) {
845     return StringSaver(Allocator).save(s);
846   }
847 
hadError()848   bool hadError() { return HadError; }
849   LLVM_ABI void diagnose(const SMDiagnostic &SMD);
850   LLVM_ABI void reportError(SMLoc L, const Twine &Msg);
851   LLVM_ABI void reportWarning(SMLoc L, const Twine &Msg);
852 
lookupMacro(StringRef Name)853   MCAsmMacro *lookupMacro(StringRef Name) {
854     StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
855     return (I == MacroMap.end()) ? nullptr : &I->getValue();
856   }
857 
defineMacro(StringRef Name,MCAsmMacro Macro)858   void defineMacro(StringRef Name, MCAsmMacro Macro) {
859     MacroMap.insert(std::make_pair(Name, std::move(Macro)));
860   }
861 
undefineMacro(StringRef Name)862   void undefineMacro(StringRef Name) { MacroMap.erase(Name); }
863 
getMCPseudoProbeTable()864   MCPseudoProbeTable &getMCPseudoProbeTable() { return PseudoProbeTable; }
865 };
866 
867 } // end namespace llvm
868 
869 // operator new and delete aren't allowed inside namespaces.
870 // The throw specifications are mandated by the standard.
871 /// Placement new for using the MCContext's allocator.
872 ///
873 /// This placement form of operator new uses the MCContext's allocator for
874 /// obtaining memory. It is a non-throwing new, which means that it returns
875 /// null on error. (If that is what the allocator does. The current does, so if
876 /// this ever changes, this operator will have to be changed, too.)
877 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
878 /// \code
879 /// // Default alignment (8)
880 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
881 /// // Specific alignment
882 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
883 /// \endcode
884 /// Please note that you cannot use delete on the pointer; it must be
885 /// deallocated using an explicit destructor call followed by
886 /// \c Context.Deallocate(Ptr).
887 ///
888 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
889 /// \param C The MCContext that provides the allocator.
890 /// \param Alignment The alignment of the allocated memory (if the underlying
891 ///                  allocator supports it).
892 /// \return The allocated memory. Could be NULL.
893 inline void *operator new(size_t Bytes, llvm::MCContext &C,
894                           size_t Alignment = 8) noexcept {
895   return C.allocate(Bytes, Alignment);
896 }
897 /// Placement delete companion to the new above.
898 ///
899 /// This operator is just a companion to the new above. There is no way of
900 /// invoking it directly; see the new operator for more details. This operator
901 /// is called implicitly by the compiler if a placement new expression using
902 /// the MCContext throws in the object constructor.
delete(void * Ptr,llvm::MCContext & C,size_t)903 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept {
904   C.deallocate(Ptr);
905 }
906 
907 /// This placement form of operator new[] uses the MCContext's allocator for
908 /// obtaining memory. It is a non-throwing new[], which means that it returns
909 /// null on error.
910 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
911 /// \code
912 /// // Default alignment (8)
913 /// char *data = new (Context) char[10];
914 /// // Specific alignment
915 /// char *data = new (Context, 4) char[10];
916 /// \endcode
917 /// Please note that you cannot use delete on the pointer; it must be
918 /// deallocated using an explicit destructor call followed by
919 /// \c Context.Deallocate(Ptr).
920 ///
921 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
922 /// \param C The MCContext that provides the allocator.
923 /// \param Alignment The alignment of the allocated memory (if the underlying
924 ///                  allocator supports it).
925 /// \return The allocated memory. Could be NULL.
926 inline void *operator new[](size_t Bytes, llvm::MCContext &C,
927                             size_t Alignment = 8) noexcept {
928   return C.allocate(Bytes, Alignment);
929 }
930 
931 /// Placement delete[] companion to the new[] above.
932 ///
933 /// This operator is just a companion to the new[] above. There is no way of
934 /// invoking it directly; see the new[] operator for more details. This operator
935 /// is called implicitly by the compiler if a placement new[] expression using
936 /// the MCContext throws in the object constructor.
937 inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept {
938   C.deallocate(Ptr);
939 }
940 
941 #endif // LLVM_MC_MCCONTEXT_H
942