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 MCAsmInfo for this target.
65 /// The MCRegisterInfo for this target.
66 const MCRegisterInfo *MRI;
68 /// The MCObjectFileInfo for this target.
69 const MCObjectFileInfo *MOFI;
71 std::unique_ptr<CodeViewContext> CVContext;
73 /// Allocator object used for creating machine code objects.
75 /// We use a bump pointer allocator to avoid the need to track all allocated
77 BumpPtrAllocator Allocator;
79 SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
80 SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
81 SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
83 /// Bindings of names to symbols.
86 /// Sections can have a corresponding symbol. This maps one to the
88 DenseMap<const MCSection *, MCSymbol *> SectionSymbols;
90 /// A mapping from a local label number and an instance count to a symbol.
91 /// For example, in the assembly
95 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
96 DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
98 /// Keeps tracks of names that were used both for used declared and
99 /// artificial symbols. The value is "true" if the name has been used for a
100 /// non-section symbol (there can be at most one of those, plus an unlimited
101 /// number of section symbols with the same name).
102 StringMap<bool, BumpPtrAllocator &> UsedNames;
104 /// The next ID to dole out to an unnamed assembler temporary symbol with
106 StringMap<unsigned> NextID;
108 /// Instances of directional local labels.
109 DenseMap<unsigned, MCLabel *> Instances;
110 /// NextInstance() creates the next instance of the directional local label
111 /// for the LocalLabelVal and adds it to the map if needed.
112 unsigned NextInstance(unsigned LocalLabelVal);
113 /// GetInstance() gets the current instance of the directional local label
114 /// for the LocalLabelVal and adds it to the map if needed.
115 unsigned GetInstance(unsigned LocalLabelVal);
117 /// The file name of the log file from the environment variable
118 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
119 /// directive is used or it is an error.
121 /// The stream that gets written to for the .secure_log_unique directive.
122 std::unique_ptr<raw_fd_ostream> SecureLog;
123 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
124 /// catch errors if .secure_log_unique appears twice without
125 /// .secure_log_reset appearing between them.
128 /// The compilation directory to use for DW_AT_comp_dir.
129 SmallString<128> CompilationDir;
131 /// The main file name if passed in explicitly.
132 std::string MainFileName;
134 /// The dwarf file and directory tables from the dwarf .file directive.
135 /// We now emit a line table for each compile unit. To reduce the prologue
136 /// size of each line table, the files and directories used by each compile
137 /// unit are separated.
138 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
140 /// The current dwarf line information from the last dwarf .loc directive.
141 MCDwarfLoc CurrentDwarfLoc;
144 /// Generate dwarf debugging info for assembly source files.
145 bool GenDwarfForAssembly;
147 /// The current dwarf file number when generate dwarf debugging info for
148 /// assembly source files.
149 unsigned GenDwarfFileNumber;
151 /// Sections for generating the .debug_ranges and .debug_aranges sections.
152 SetVector<MCSection *> SectionsForRanges;
154 /// The information gathered from labels that will have dwarf label
155 /// entries when generating dwarf assembly source files.
156 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
158 /// The string to embed in the debug information for the compile unit, if
160 StringRef DwarfDebugFlags;
162 /// The string to embed in as the dwarf AT_producer for the compile unit, if
164 StringRef DwarfDebugProducer;
166 /// The maximum version of dwarf that we should emit.
167 uint16_t DwarfVersion;
169 /// Honor temporary labels, this is useful for debugging semantic
170 /// differences between temporary and non-temporary labels (primarily on
172 bool AllowTemporaryLabels;
173 bool UseNamesOnTempLabels = true;
175 /// The Compile Unit ID that we are currently processing.
176 unsigned DwarfCompileUnitID;
178 struct ELFSectionKey {
179 std::string SectionName;
182 ELFSectionKey(StringRef SectionName, StringRef GroupName,
184 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
186 bool operator<(const ELFSectionKey &Other) const {
187 if (SectionName != Other.SectionName)
188 return SectionName < Other.SectionName;
189 if (GroupName != Other.GroupName)
190 return GroupName < Other.GroupName;
191 return UniqueID < Other.UniqueID;
195 struct COFFSectionKey {
196 std::string SectionName;
200 COFFSectionKey(StringRef SectionName, StringRef GroupName,
201 int SelectionKey, unsigned UniqueID)
202 : SectionName(SectionName), GroupName(GroupName),
203 SelectionKey(SelectionKey), UniqueID(UniqueID) {}
204 bool operator<(const COFFSectionKey &Other) const {
205 if (SectionName != Other.SectionName)
206 return SectionName < Other.SectionName;
207 if (GroupName != Other.GroupName)
208 return GroupName < Other.GroupName;
209 if (SelectionKey != Other.SelectionKey)
210 return SelectionKey < Other.SelectionKey;
211 return UniqueID < Other.UniqueID;
215 StringMap<MCSectionMachO *> MachOUniquingMap;
216 std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
217 std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
218 StringMap<bool> ELFRelSecNames;
220 SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
222 /// Do automatic reset in destructor
227 MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
229 MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
232 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
236 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
237 const MCObjectFileInfo *MOFI,
238 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
241 const SourceMgr *getSourceManager() const { return SrcMgr; }
243 const MCAsmInfo *getAsmInfo() const { return MAI; }
245 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
247 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
249 CodeViewContext &getCVContext();
251 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
252 void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
254 /// \name Module Lifetime Management
257 /// reset - return object to right after construction state to prepare
258 /// to process a new module
263 /// \name Symbol Management
266 /// Create and return a new linker temporary symbol with a unique but
267 /// unspecified name.
268 MCSymbol *createLinkerPrivateTempSymbol();
270 /// Create and return a new assembler temporary symbol with a unique but
271 /// unspecified name.
272 MCSymbol *createTempSymbol(bool CanBeUnnamed = true);
274 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
275 bool CanBeUnnamed = true);
277 /// Create the definition of a directional local symbol for numbered label
278 /// (used for "1:" definitions).
279 MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
281 /// Create and return a directional local symbol for numbered label (used
282 /// for "1b" or 1f" references).
283 MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
285 /// Lookup the symbol inside with the specified \p Name. If it exists,
286 /// return it. If not, create a forward reference and return it.
288 /// \param Name - The symbol name, which must be unique across all symbols.
289 MCSymbol *getOrCreateSymbol(const Twine &Name);
291 MCSymbolELF *getOrCreateSectionSymbol(const MCSectionELF &Section);
293 /// Gets a symbol that will be defined to the final stack offset of a local
294 /// variable after codegen.
296 /// \param Idx - The index of a local variable passed to @llvm.localescape.
297 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
299 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
301 MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
303 /// Get the symbol for \p Name, or null.
304 MCSymbol *lookupSymbol(const Twine &Name) const;
306 /// Set value for a symbol.
307 void setSymbolValue(MCStreamer &Streamer, StringRef Sym, uint64_t Val);
309 /// getSymbols - Get a reference for the symbol table for clients that
310 /// want to, for example, iterate over all symbols. 'const' because we
311 /// still want any modifications to the table itself to use the MCContext
313 const SymbolTable &getSymbols() const { return Symbols; }
317 /// \name Section Management
321 /// Pass this value as the UniqueID during section creation to get the
322 /// generic section with the given name and characteristics. The usual
323 /// sections such as .text use this ID.
324 GenericSectionID = ~0U
327 /// Return the MCSection for the specified mach-o section. This requires
328 /// the operands to be valid.
329 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
330 unsigned TypeAndAttributes,
331 unsigned Reserved2, SectionKind K,
332 const char *BeginSymName = nullptr);
334 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
335 unsigned TypeAndAttributes, SectionKind K,
336 const char *BeginSymName = nullptr) {
337 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
341 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
343 return getELFSection(Section, Type, Flags, nullptr);
346 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
347 unsigned Flags, const char *BeginSymName) {
348 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
351 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
352 unsigned Flags, unsigned EntrySize,
353 const Twine &Group) {
354 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
357 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
358 unsigned Flags, unsigned EntrySize,
359 const Twine &Group, const char *BeginSymName) {
360 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
364 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
365 unsigned Flags, unsigned EntrySize,
366 const Twine &Group, unsigned UniqueID) {
367 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
371 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
372 unsigned Flags, unsigned EntrySize,
373 const Twine &Group, unsigned UniqueID,
374 const char *BeginSymName);
376 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
377 unsigned Flags, unsigned EntrySize,
378 const MCSymbolELF *Group, unsigned UniqueID,
379 const char *BeginSymName,
380 const MCSectionELF *Associated);
382 /// Get a section with the provided group identifier. This section is
383 /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
384 /// describes the type of the section and \p Flags are used to further
385 /// configure this named section.
386 MCSectionELF *getELFNamedSection(const Twine &Prefix, const Twine &Suffix,
387 unsigned Type, unsigned Flags,
388 unsigned EntrySize = 0);
390 MCSectionELF *createELFRelSection(const Twine &Name, unsigned Type,
391 unsigned Flags, unsigned EntrySize,
392 const MCSymbolELF *Group,
393 const MCSectionELF *Associated);
395 void renameELFSection(MCSectionELF *Section, StringRef Name);
397 MCSectionELF *createELFGroupSection(const MCSymbolELF *Group);
399 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
400 SectionKind Kind, StringRef COMDATSymName,
402 unsigned UniqueID = GenericSectionID,
403 const char *BeginSymName = nullptr);
405 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
407 const char *BeginSymName = nullptr);
409 MCSectionCOFF *getCOFFSection(StringRef Section);
411 /// Gets or creates a section equivalent to Sec that is associated with the
412 /// section containing KeySym. For example, to create a debug info section
413 /// associated with an inline function, pass the normal debug info section
414 /// as Sec and the function symbol as KeySym.
416 getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
417 unsigned UniqueID = GenericSectionID);
419 // Create and save a copy of STI and return a reference to the copy.
420 MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
424 /// \name Dwarf Management
427 /// \brief Get the compilation directory for DW_AT_comp_dir
428 /// The compilation directory should be set with \c setCompilationDir before
429 /// calling this function. If it is unset, an empty string will be returned.
430 StringRef getCompilationDir() const { return CompilationDir; }
432 /// \brief Set the compilation directory for DW_AT_comp_dir
433 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
435 /// \brief Get the main file name for use in error messages and debug
436 /// info. This can be set to ensure we've got the correct file name
437 /// after preprocessing or for -save-temps.
438 const std::string &getMainFileName() const { return MainFileName; }
440 /// \brief Set the main file name and override the default.
441 void setMainFileName(StringRef S) { MainFileName = S; }
443 /// Creates an entry in the dwarf file and directory tables.
444 unsigned getDwarfFile(StringRef Directory, StringRef FileName,
445 unsigned FileNumber, unsigned CUID);
447 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
449 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
450 return MCDwarfLineTablesCUMap;
453 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
454 return MCDwarfLineTablesCUMap[CUID];
457 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
458 auto I = MCDwarfLineTablesCUMap.find(CUID);
459 assert(I != MCDwarfLineTablesCUMap.end());
463 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
464 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
466 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
467 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
470 bool hasMCLineSections() const {
471 for (const auto &Table : MCDwarfLineTablesCUMap)
472 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
476 unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
477 void setDwarfCompileUnitID(unsigned CUIndex) {
478 DwarfCompileUnitID = CUIndex;
480 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
481 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
484 /// Saves the information from the currently parsed dwarf .loc directive
485 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
486 /// in the line number table with this information and the address of the
487 /// instruction will be created.
488 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
489 unsigned Flags, unsigned Isa,
490 unsigned Discriminator) {
491 CurrentDwarfLoc.setFileNum(FileNum);
492 CurrentDwarfLoc.setLine(Line);
493 CurrentDwarfLoc.setColumn(Column);
494 CurrentDwarfLoc.setFlags(Flags);
495 CurrentDwarfLoc.setIsa(Isa);
496 CurrentDwarfLoc.setDiscriminator(Discriminator);
499 void clearDwarfLocSeen() { DwarfLocSeen = false; }
501 bool getDwarfLocSeen() { return DwarfLocSeen; }
502 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
504 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
505 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
506 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
507 void setGenDwarfFileNumber(unsigned FileNumber) {
508 GenDwarfFileNumber = FileNumber;
510 const SetVector<MCSection *> &getGenDwarfSectionSyms() {
511 return SectionsForRanges;
513 bool addGenDwarfSection(MCSection *Sec) {
514 return SectionsForRanges.insert(Sec);
517 void finalizeDwarfSections(MCStreamer &MCOS);
518 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
519 return MCGenDwarfLabelEntries;
521 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
522 MCGenDwarfLabelEntries.push_back(E);
525 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
526 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
528 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
529 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
530 dwarf::DwarfFormat getDwarfFormat() const {
531 // TODO: Support DWARF64
532 return dwarf::DWARF32;
534 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
535 uint16_t getDwarfVersion() const { return DwarfVersion; }
539 char *getSecureLogFile() { return SecureLogFile; }
540 raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
541 bool getSecureLogUsed() { return SecureLogUsed; }
542 void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
543 SecureLog = std::move(Value);
545 void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
547 void *allocate(unsigned Size, unsigned Align = 8) {
548 return Allocator.Allocate(Size, Align);
550 void deallocate(void *Ptr) {}
552 bool hadError() { return HadError; }
553 void reportError(SMLoc L, const Twine &Msg);
554 // Unrecoverable error has occurred. Display the best diagnostic we can
555 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
556 // FIXME: We should really do something about that.
557 LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
561 } // end namespace llvm
563 // operator new and delete aren't allowed inside namespaces.
564 // The throw specifications are mandated by the standard.
565 /// \brief Placement new for using the MCContext's allocator.
567 /// This placement form of operator new uses the MCContext's allocator for
568 /// obtaining memory. It is a non-throwing new, which means that it returns
569 /// null on error. (If that is what the allocator does. The current does, so if
570 /// this ever changes, this operator will have to be changed, too.)
571 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
573 /// // Default alignment (8)
574 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
575 /// // Specific alignment
576 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
578 /// Please note that you cannot use delete on the pointer; it must be
579 /// deallocated using an explicit destructor call followed by
580 /// \c Context.Deallocate(Ptr).
582 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
583 /// \param C The MCContext that provides the allocator.
584 /// \param Alignment The alignment of the allocated memory (if the underlying
585 /// allocator supports it).
586 /// \return The allocated memory. Could be NULL.
587 inline void *operator new(size_t Bytes, llvm::MCContext &C,
588 size_t Alignment = 8) noexcept {
589 return C.allocate(Bytes, Alignment);
591 /// \brief Placement delete companion to the new above.
593 /// This operator is just a companion to the new above. There is no way of
594 /// invoking it directly; see the new operator for more details. This operator
595 /// is called implicitly by the compiler if a placement new expression using
596 /// the MCContext throws in the object constructor.
597 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept {
601 /// This placement form of operator new[] uses the MCContext's allocator for
602 /// obtaining memory. It is a non-throwing new[], which means that it returns
604 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
606 /// // Default alignment (8)
607 /// char *data = new (Context) char[10];
608 /// // Specific alignment
609 /// char *data = new (Context, 4) char[10];
611 /// Please note that you cannot use delete on the pointer; it must be
612 /// deallocated using an explicit destructor call followed by
613 /// \c Context.Deallocate(Ptr).
615 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
616 /// \param C The MCContext that provides the allocator.
617 /// \param Alignment The alignment of the allocated memory (if the underlying
618 /// allocator supports it).
619 /// \return The allocated memory. Could be NULL.
620 inline void *operator new[](size_t Bytes, llvm::MCContext &C,
621 size_t Alignment = 8) noexcept {
622 return C.allocate(Bytes, Alignment);
625 /// \brief Placement delete[] companion to the new[] above.
627 /// This operator is just a companion to the new[] above. There is no way of
628 /// invoking it directly; see the new[] operator for more details. This operator
629 /// is called implicitly by the compiler if a placement new[] expression using
630 /// the MCContext throws in the object constructor.
631 inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept {