1 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_MC_MCCONTEXT_H
11 #define LLVM_MC_MCCONTEXT_H
13 #include "llvm/ADT/DenseMap.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/Twine.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/SectionKind.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/raw_ostream.h"
28 #include <vector> // FIXME: Shouldn't be needed.
39 class MCObjectFileInfo;
46 class CodeViewContext;
48 /// Context object for machine code objects. This class owns all of the
49 /// sections that it creates.
52 MCContext(const MCContext &) = delete;
53 MCContext &operator=(const MCContext &) = delete;
56 typedef StringMap<MCSymbol *, BumpPtrAllocator &> SymbolTable;
59 /// The SourceMgr for this object, if any.
60 const SourceMgr *SrcMgr;
62 /// The SourceMgr for inline assembly, if any.
63 SourceMgr *InlineSrcMgr;
65 /// The MCAsmInfo for this target.
68 /// The MCRegisterInfo for this target.
69 const MCRegisterInfo *MRI;
71 /// The MCObjectFileInfo for this target.
72 const MCObjectFileInfo *MOFI;
74 std::unique_ptr<CodeViewContext> CVContext;
76 /// Allocator object used for creating machine code objects.
78 /// We use a bump pointer allocator to avoid the need to track all allocated
80 BumpPtrAllocator Allocator;
82 SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
83 SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
84 SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
86 /// Bindings of names to symbols.
89 /// Sections can have a corresponding symbol. This maps one to the
91 DenseMap<const MCSection *, MCSymbol *> SectionSymbols;
93 /// A mapping from a local label number and an instance count to a symbol.
94 /// For example, in the assembly
98 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
99 DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
101 /// Keeps tracks of names that were used both for used declared and
102 /// artificial symbols. The value is "true" if the name has been used for a
103 /// non-section symbol (there can be at most one of those, plus an unlimited
104 /// number of section symbols with the same name).
105 StringMap<bool, BumpPtrAllocator &> UsedNames;
107 /// The next ID to dole out to an unnamed assembler temporary symbol with
109 StringMap<unsigned> NextID;
111 /// Instances of directional local labels.
112 DenseMap<unsigned, MCLabel *> Instances;
113 /// NextInstance() creates the next instance of the directional local label
114 /// for the LocalLabelVal and adds it to the map if needed.
115 unsigned NextInstance(unsigned LocalLabelVal);
116 /// GetInstance() gets the current instance of the directional local label
117 /// for the LocalLabelVal and adds it to the map if needed.
118 unsigned GetInstance(unsigned LocalLabelVal);
120 /// The file name of the log file from the environment variable
121 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
122 /// directive is used or it is an error.
124 /// The stream that gets written to for the .secure_log_unique directive.
125 std::unique_ptr<raw_fd_ostream> SecureLog;
126 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
127 /// catch errors if .secure_log_unique appears twice without
128 /// .secure_log_reset appearing between them.
131 /// The compilation directory to use for DW_AT_comp_dir.
132 SmallString<128> CompilationDir;
134 /// The main file name if passed in explicitly.
135 std::string MainFileName;
137 /// The dwarf file and directory tables from the dwarf .file directive.
138 /// We now emit a line table for each compile unit. To reduce the prologue
139 /// size of each line table, the files and directories used by each compile
140 /// unit are separated.
141 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
143 /// The current dwarf line information from the last dwarf .loc directive.
144 MCDwarfLoc CurrentDwarfLoc;
147 /// Generate dwarf debugging info for assembly source files.
148 bool GenDwarfForAssembly;
150 /// The current dwarf file number when generate dwarf debugging info for
151 /// assembly source files.
152 unsigned GenDwarfFileNumber;
154 /// Sections for generating the .debug_ranges and .debug_aranges sections.
155 SetVector<MCSection *> SectionsForRanges;
157 /// The information gathered from labels that will have dwarf label
158 /// entries when generating dwarf assembly source files.
159 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
161 /// The string to embed in the debug information for the compile unit, if
163 StringRef DwarfDebugFlags;
165 /// The string to embed in as the dwarf AT_producer for the compile unit, if
167 StringRef DwarfDebugProducer;
169 /// The maximum version of dwarf that we should emit.
170 uint16_t DwarfVersion;
172 /// Honor temporary labels, this is useful for debugging semantic
173 /// differences between temporary and non-temporary labels (primarily on
175 bool AllowTemporaryLabels;
176 bool UseNamesOnTempLabels = true;
178 /// The Compile Unit ID that we are currently processing.
179 unsigned DwarfCompileUnitID;
181 struct ELFSectionKey {
182 std::string SectionName;
185 ELFSectionKey(StringRef SectionName, StringRef GroupName,
187 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
189 bool operator<(const ELFSectionKey &Other) const {
190 if (SectionName != Other.SectionName)
191 return SectionName < Other.SectionName;
192 if (GroupName != Other.GroupName)
193 return GroupName < Other.GroupName;
194 return UniqueID < Other.UniqueID;
198 struct COFFSectionKey {
199 std::string SectionName;
203 COFFSectionKey(StringRef SectionName, StringRef GroupName,
204 int SelectionKey, unsigned UniqueID)
205 : SectionName(SectionName), GroupName(GroupName),
206 SelectionKey(SelectionKey), UniqueID(UniqueID) {}
207 bool operator<(const COFFSectionKey &Other) const {
208 if (SectionName != Other.SectionName)
209 return SectionName < Other.SectionName;
210 if (GroupName != Other.GroupName)
211 return GroupName < Other.GroupName;
212 if (SelectionKey != Other.SelectionKey)
213 return SelectionKey < Other.SelectionKey;
214 return UniqueID < Other.UniqueID;
218 StringMap<MCSectionMachO *> MachOUniquingMap;
219 std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
220 std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
221 StringMap<bool> ELFRelSecNames;
223 SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
225 /// Do automatic reset in destructor
230 MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
232 MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
235 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
239 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
240 const MCObjectFileInfo *MOFI,
241 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
244 const SourceMgr *getSourceManager() const { return SrcMgr; }
246 void setInlineSourceManager(SourceMgr *SM) { InlineSrcMgr = SM; }
248 const MCAsmInfo *getAsmInfo() const { return MAI; }
250 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
252 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
254 CodeViewContext &getCVContext();
256 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
257 void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
259 /// \name Module Lifetime Management
262 /// reset - return object to right after construction state to prepare
263 /// to process a new module
268 /// \name Symbol Management
271 /// Create and return a new linker temporary symbol with a unique but
272 /// unspecified name.
273 MCSymbol *createLinkerPrivateTempSymbol();
275 /// Create and return a new assembler temporary symbol with a unique but
276 /// unspecified name.
277 MCSymbol *createTempSymbol(bool CanBeUnnamed = true);
279 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
280 bool CanBeUnnamed = true);
282 /// Create the definition of a directional local symbol for numbered label
283 /// (used for "1:" definitions).
284 MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
286 /// Create and return a directional local symbol for numbered label (used
287 /// for "1b" or 1f" references).
288 MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
290 /// Lookup the symbol inside with the specified \p Name. If it exists,
291 /// return it. If not, create a forward reference and return it.
293 /// \param Name - The symbol name, which must be unique across all symbols.
294 MCSymbol *getOrCreateSymbol(const Twine &Name);
296 MCSymbolELF *getOrCreateSectionSymbol(const MCSectionELF &Section);
298 /// Gets a symbol that will be defined to the final stack offset of a local
299 /// variable after codegen.
301 /// \param Idx - The index of a local variable passed to @llvm.localescape.
302 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
304 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
306 MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
308 /// Get the symbol for \p Name, or null.
309 MCSymbol *lookupSymbol(const Twine &Name) const;
311 /// Set value for a symbol.
312 void setSymbolValue(MCStreamer &Streamer, StringRef Sym, uint64_t Val);
314 /// getSymbols - Get a reference for the symbol table for clients that
315 /// want to, for example, iterate over all symbols. 'const' because we
316 /// still want any modifications to the table itself to use the MCContext
318 const SymbolTable &getSymbols() const { return Symbols; }
322 /// \name Section Management
326 /// Pass this value as the UniqueID during section creation to get the
327 /// generic section with the given name and characteristics. The usual
328 /// sections such as .text use this ID.
329 GenericSectionID = ~0U
332 /// Return the MCSection for the specified mach-o section. This requires
333 /// the operands to be valid.
334 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
335 unsigned TypeAndAttributes,
336 unsigned Reserved2, SectionKind K,
337 const char *BeginSymName = nullptr);
339 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
340 unsigned TypeAndAttributes, SectionKind K,
341 const char *BeginSymName = nullptr) {
342 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
346 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
348 return getELFSection(Section, Type, Flags, nullptr);
351 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
352 unsigned Flags, const char *BeginSymName) {
353 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
356 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
357 unsigned Flags, unsigned EntrySize,
358 const Twine &Group) {
359 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
362 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
363 unsigned Flags, unsigned EntrySize,
364 const Twine &Group, const char *BeginSymName) {
365 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
369 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
370 unsigned Flags, unsigned EntrySize,
371 const Twine &Group, unsigned UniqueID) {
372 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
376 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
377 unsigned Flags, unsigned EntrySize,
378 const Twine &Group, unsigned UniqueID,
379 const char *BeginSymName);
381 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
382 unsigned Flags, unsigned EntrySize,
383 const MCSymbolELF *Group, unsigned UniqueID,
384 const char *BeginSymName,
385 const MCSectionELF *Associated);
387 /// Get a section with the provided group identifier. This section is
388 /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
389 /// describes the type of the section and \p Flags are used to further
390 /// configure this named section.
391 MCSectionELF *getELFNamedSection(const Twine &Prefix, const Twine &Suffix,
392 unsigned Type, unsigned Flags,
393 unsigned EntrySize = 0);
395 MCSectionELF *createELFRelSection(const Twine &Name, unsigned Type,
396 unsigned Flags, unsigned EntrySize,
397 const MCSymbolELF *Group,
398 const MCSectionELF *Associated);
400 void renameELFSection(MCSectionELF *Section, StringRef Name);
402 MCSectionELF *createELFGroupSection(const MCSymbolELF *Group);
404 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
405 SectionKind Kind, StringRef COMDATSymName,
407 unsigned UniqueID = GenericSectionID,
408 const char *BeginSymName = nullptr);
410 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
412 const char *BeginSymName = nullptr);
414 MCSectionCOFF *getCOFFSection(StringRef Section);
416 /// Gets or creates a section equivalent to Sec that is associated with the
417 /// section containing KeySym. For example, to create a debug info section
418 /// associated with an inline function, pass the normal debug info section
419 /// as Sec and the function symbol as KeySym.
421 getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
422 unsigned UniqueID = GenericSectionID);
424 // Create and save a copy of STI and return a reference to the copy.
425 MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
429 /// \name Dwarf Management
432 /// \brief Get the compilation directory for DW_AT_comp_dir
433 /// The compilation directory should be set with \c setCompilationDir before
434 /// calling this function. If it is unset, an empty string will be returned.
435 StringRef getCompilationDir() const { return CompilationDir; }
437 /// \brief Set the compilation directory for DW_AT_comp_dir
438 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
440 /// \brief Get the main file name for use in error messages and debug
441 /// info. This can be set to ensure we've got the correct file name
442 /// after preprocessing or for -save-temps.
443 const std::string &getMainFileName() const { return MainFileName; }
445 /// \brief Set the main file name and override the default.
446 void setMainFileName(StringRef S) { MainFileName = S; }
448 /// Creates an entry in the dwarf file and directory tables.
449 unsigned getDwarfFile(StringRef Directory, StringRef FileName,
450 unsigned FileNumber, unsigned CUID);
452 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
454 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
455 return MCDwarfLineTablesCUMap;
458 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
459 return MCDwarfLineTablesCUMap[CUID];
462 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
463 auto I = MCDwarfLineTablesCUMap.find(CUID);
464 assert(I != MCDwarfLineTablesCUMap.end());
468 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
469 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
471 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
472 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
475 bool hasMCLineSections() const {
476 for (const auto &Table : MCDwarfLineTablesCUMap)
477 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
481 unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
482 void setDwarfCompileUnitID(unsigned CUIndex) {
483 DwarfCompileUnitID = CUIndex;
485 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
486 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
489 /// Saves the information from the currently parsed dwarf .loc directive
490 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
491 /// in the line number table with this information and the address of the
492 /// instruction will be created.
493 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
494 unsigned Flags, unsigned Isa,
495 unsigned Discriminator) {
496 CurrentDwarfLoc.setFileNum(FileNum);
497 CurrentDwarfLoc.setLine(Line);
498 CurrentDwarfLoc.setColumn(Column);
499 CurrentDwarfLoc.setFlags(Flags);
500 CurrentDwarfLoc.setIsa(Isa);
501 CurrentDwarfLoc.setDiscriminator(Discriminator);
504 void clearDwarfLocSeen() { DwarfLocSeen = false; }
506 bool getDwarfLocSeen() { return DwarfLocSeen; }
507 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
509 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
510 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
511 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
512 void setGenDwarfFileNumber(unsigned FileNumber) {
513 GenDwarfFileNumber = FileNumber;
515 const SetVector<MCSection *> &getGenDwarfSectionSyms() {
516 return SectionsForRanges;
518 bool addGenDwarfSection(MCSection *Sec) {
519 return SectionsForRanges.insert(Sec);
522 void finalizeDwarfSections(MCStreamer &MCOS);
523 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
524 return MCGenDwarfLabelEntries;
526 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
527 MCGenDwarfLabelEntries.push_back(E);
530 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
531 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
533 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
534 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
535 dwarf::DwarfFormat getDwarfFormat() const {
536 // TODO: Support DWARF64
537 return dwarf::DWARF32;
539 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
540 uint16_t getDwarfVersion() const { return DwarfVersion; }
544 char *getSecureLogFile() { return SecureLogFile; }
545 raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
546 bool getSecureLogUsed() { return SecureLogUsed; }
547 void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
548 SecureLog = std::move(Value);
550 void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
552 void *allocate(unsigned Size, unsigned Align = 8) {
553 return Allocator.Allocate(Size, Align);
555 void deallocate(void *Ptr) {}
557 bool hadError() { return HadError; }
558 void reportError(SMLoc L, const Twine &Msg);
559 // Unrecoverable error has occurred. Display the best diagnostic we can
560 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
561 // FIXME: We should really do something about that.
562 LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
566 } // end namespace llvm
568 // operator new and delete aren't allowed inside namespaces.
569 // The throw specifications are mandated by the standard.
570 /// \brief Placement new for using the MCContext's allocator.
572 /// This placement form of operator new uses the MCContext's allocator for
573 /// obtaining memory. It is a non-throwing new, which means that it returns
574 /// null on error. (If that is what the allocator does. The current does, so if
575 /// this ever changes, this operator will have to be changed, too.)
576 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
578 /// // Default alignment (8)
579 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
580 /// // Specific alignment
581 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
583 /// Please note that you cannot use delete on the pointer; it must be
584 /// deallocated using an explicit destructor call followed by
585 /// \c Context.Deallocate(Ptr).
587 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
588 /// \param C The MCContext that provides the allocator.
589 /// \param Alignment The alignment of the allocated memory (if the underlying
590 /// allocator supports it).
591 /// \return The allocated memory. Could be NULL.
592 inline void *operator new(size_t Bytes, llvm::MCContext &C,
593 size_t Alignment = 8) noexcept {
594 return C.allocate(Bytes, Alignment);
596 /// \brief Placement delete companion to the new above.
598 /// This operator is just a companion to the new above. There is no way of
599 /// invoking it directly; see the new operator for more details. This operator
600 /// is called implicitly by the compiler if a placement new expression using
601 /// the MCContext throws in the object constructor.
602 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept {
606 /// This placement form of operator new[] uses the MCContext's allocator for
607 /// obtaining memory. It is a non-throwing new[], which means that it returns
609 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
611 /// // Default alignment (8)
612 /// char *data = new (Context) char[10];
613 /// // Specific alignment
614 /// char *data = new (Context, 4) char[10];
616 /// Please note that you cannot use delete on the pointer; it must be
617 /// deallocated using an explicit destructor call followed by
618 /// \c Context.Deallocate(Ptr).
620 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
621 /// \param C The MCContext that provides the allocator.
622 /// \param Alignment The alignment of the allocated memory (if the underlying
623 /// allocator supports it).
624 /// \return The allocated memory. Could be NULL.
625 inline void *operator new[](size_t Bytes, llvm::MCContext &C,
626 size_t Alignment = 8) noexcept {
627 return C.allocate(Bytes, Alignment);
630 /// \brief Placement delete[] companion to the new[] above.
632 /// This operator is just a companion to the new[] above. There is no way of
633 /// invoking it directly; see the new[] operator for more details. This operator
634 /// is called implicitly by the compiler if a placement new[] expression using
635 /// the MCContext throws in the object constructor.
636 inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept {