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