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