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