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