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