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