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/SectionKind.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/raw_ostream.h"
26 #include <vector> // FIXME: Shouldn't be needed.
37 class MCObjectFileInfo;
45 /// Context object for machine code objects. This class owns all of the
46 /// sections that it creates.
49 MCContext(const MCContext &) = delete;
50 MCContext &operator=(const MCContext &) = delete;
53 typedef StringMap<MCSymbol *, BumpPtrAllocator &> SymbolTable;
56 /// The SourceMgr for this object, if any.
57 const SourceMgr *SrcMgr;
59 /// The MCAsmInfo for this target.
62 /// The MCRegisterInfo for this target.
63 const MCRegisterInfo *MRI;
65 /// The MCObjectFileInfo for this target.
66 const MCObjectFileInfo *MOFI;
68 /// Allocator object used for creating machine code objects.
70 /// We use a bump pointer allocator to avoid the need to track all allocated
72 BumpPtrAllocator Allocator;
74 SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
75 SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
76 SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
78 /// Bindings of names to symbols.
81 /// ELF sections can have a corresponding symbol. This maps one to the
83 DenseMap<const MCSectionELF *, MCSymbolELF *> SectionSymbols;
85 /// A mapping from a local label number and an instance count to a symbol.
86 /// For example, in the assembly
90 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
91 DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
93 /// Keeps tracks of names that were used both for used declared and
94 /// artificial symbols.
95 StringMap<bool, BumpPtrAllocator &> UsedNames;
97 /// The next ID to dole out to an unnamed assembler temporary symbol with
99 StringMap<unsigned> NextID;
101 /// Instances of directional local labels.
102 DenseMap<unsigned, MCLabel *> Instances;
103 /// NextInstance() creates the next instance of the directional local label
104 /// for the LocalLabelVal and adds it to the map if needed.
105 unsigned NextInstance(unsigned LocalLabelVal);
106 /// GetInstance() gets the current instance of the directional local label
107 /// for the LocalLabelVal and adds it to the map if needed.
108 unsigned GetInstance(unsigned LocalLabelVal);
110 /// The file name of the log file from the environment variable
111 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
112 /// directive is used or it is an error.
114 /// The stream that gets written to for the .secure_log_unique directive.
115 raw_ostream *SecureLog;
116 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
117 /// catch errors if .secure_log_unique appears twice without
118 /// .secure_log_reset appearing between them.
121 /// The compilation directory to use for DW_AT_comp_dir.
122 SmallString<128> CompilationDir;
124 /// The main file name if passed in explicitly.
125 std::string MainFileName;
127 /// The dwarf file and directory tables from the dwarf .file directive.
128 /// We now emit a line table for each compile unit. To reduce the prologue
129 /// size of each line table, the files and directories used by each compile
130 /// unit are separated.
131 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
133 /// The current dwarf line information from the last dwarf .loc directive.
134 MCDwarfLoc CurrentDwarfLoc;
137 /// Generate dwarf debugging info for assembly source files.
138 bool GenDwarfForAssembly;
140 /// The current dwarf file number when generate dwarf debugging info for
141 /// assembly source files.
142 unsigned GenDwarfFileNumber;
144 /// Sections for generating the .debug_ranges and .debug_aranges sections.
145 SetVector<MCSection *> SectionsForRanges;
147 /// The information gathered from labels that will have dwarf label
148 /// entries when generating dwarf assembly source files.
149 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
151 /// The string to embed in the debug information for the compile unit, if
153 StringRef DwarfDebugFlags;
155 /// The string to embed in as the dwarf AT_producer for the compile unit, if
157 StringRef DwarfDebugProducer;
159 /// The maximum version of dwarf that we should emit.
160 uint16_t DwarfVersion;
162 /// Honor temporary labels, this is useful for debugging semantic
163 /// differences between temporary and non-temporary labels (primarily on
165 bool AllowTemporaryLabels;
166 bool UseNamesOnTempLabels = true;
168 /// The Compile Unit ID that we are currently processing.
169 unsigned DwarfCompileUnitID;
171 struct ELFSectionKey {
172 std::string SectionName;
175 ELFSectionKey(StringRef SectionName, StringRef GroupName,
177 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
179 bool operator<(const ELFSectionKey &Other) const {
180 if (SectionName != Other.SectionName)
181 return SectionName < Other.SectionName;
182 if (GroupName != Other.GroupName)
183 return GroupName < Other.GroupName;
184 return UniqueID < Other.UniqueID;
188 struct COFFSectionKey {
189 std::string SectionName;
192 COFFSectionKey(StringRef SectionName, StringRef GroupName,
194 : SectionName(SectionName), GroupName(GroupName),
195 SelectionKey(SelectionKey) {}
196 bool operator<(const COFFSectionKey &Other) const {
197 if (SectionName != Other.SectionName)
198 return SectionName < Other.SectionName;
199 if (GroupName != Other.GroupName)
200 return GroupName < Other.GroupName;
201 return SelectionKey < Other.SelectionKey;
205 StringMap<MCSectionMachO *> MachOUniquingMap;
206 std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
207 std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
208 StringMap<bool> ELFRelSecNames;
210 /// Do automatic reset in destructor
213 MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
215 MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
218 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
222 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
223 const MCObjectFileInfo *MOFI,
224 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
227 const SourceMgr *getSourceManager() const { return SrcMgr; }
229 const MCAsmInfo *getAsmInfo() const { return MAI; }
231 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
233 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
235 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
236 void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
238 /// \name Module Lifetime Management
241 /// reset - return object to right after construction state to prepare
242 /// to process a new module
247 /// \name Symbol Management
250 /// Create and return a new linker temporary symbol with a unique but
251 /// unspecified name.
252 MCSymbol *createLinkerPrivateTempSymbol();
254 /// Create and return a new assembler temporary symbol with a unique but
255 /// unspecified name.
256 MCSymbol *createTempSymbol(bool CanBeUnnamed = true);
258 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
259 bool CanBeUnnamed = true);
261 /// Create the definition of a directional local symbol for numbered label
262 /// (used for "1:" definitions).
263 MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
265 /// Create and return a directional local symbol for numbered label (used
266 /// for "1b" or 1f" references).
267 MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
269 /// Lookup the symbol inside with the specified \p Name. If it exists,
270 /// return it. If not, create a forward reference and return it.
272 /// \param Name - The symbol name, which must be unique across all symbols.
273 MCSymbol *getOrCreateSymbol(const Twine &Name);
275 MCSymbolELF *getOrCreateSectionSymbol(const MCSectionELF &Section);
277 /// Gets a symbol that will be defined to the final stack offset of a local
278 /// variable after codegen.
280 /// \param Idx - The index of a local variable passed to @llvm.localescape.
281 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
283 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
285 MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
287 /// Get the symbol for \p Name, or null.
288 MCSymbol *lookupSymbol(const Twine &Name) const;
290 /// getSymbols - Get a reference for the symbol table for clients that
291 /// want to, for example, iterate over all symbols. 'const' because we
292 /// still want any modifications to the table itself to use the MCContext
294 const SymbolTable &getSymbols() const { return Symbols; }
298 /// \name Section Management
301 /// Return the MCSection for the specified mach-o section. This requires
302 /// the operands to be valid.
303 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
304 unsigned TypeAndAttributes,
305 unsigned Reserved2, SectionKind K,
306 const char *BeginSymName = nullptr);
308 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
309 unsigned TypeAndAttributes, SectionKind K,
310 const char *BeginSymName = nullptr) {
311 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
315 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
317 return getELFSection(Section, Type, Flags, nullptr);
320 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
321 unsigned Flags, const char *BeginSymName) {
322 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
325 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
326 unsigned Flags, unsigned EntrySize,
328 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
331 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
332 unsigned Flags, unsigned EntrySize,
333 StringRef Group, const char *BeginSymName) {
334 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
338 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
339 unsigned Flags, unsigned EntrySize,
340 StringRef Group, unsigned UniqueID) {
341 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
345 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
346 unsigned Flags, unsigned EntrySize,
347 StringRef Group, unsigned UniqueID,
348 const char *BeginSymName);
350 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
351 unsigned Flags, unsigned EntrySize,
352 const MCSymbolELF *Group, unsigned UniqueID,
353 const char *BeginSymName,
354 const MCSectionELF *Associated);
356 MCSectionELF *createELFRelSection(StringRef Name, unsigned Type,
357 unsigned Flags, unsigned EntrySize,
358 const MCSymbolELF *Group,
359 const MCSectionELF *Associated);
361 void renameELFSection(MCSectionELF *Section, StringRef Name);
363 MCSectionELF *createELFGroupSection(const MCSymbolELF *Group);
365 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
366 SectionKind Kind, StringRef COMDATSymName,
368 const char *BeginSymName = nullptr);
370 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
372 const char *BeginSymName = nullptr);
374 MCSectionCOFF *getCOFFSection(StringRef Section);
376 /// Gets or creates a section equivalent to Sec that is associated with the
377 /// section containing KeySym. For example, to create a debug info section
378 /// associated with an inline function, pass the normal debug info section
379 /// as Sec and the function symbol as KeySym.
380 MCSectionCOFF *getAssociativeCOFFSection(MCSectionCOFF *Sec,
381 const MCSymbol *KeySym);
385 /// \name Dwarf Management
388 /// \brief Get the compilation directory for DW_AT_comp_dir
389 /// This can be overridden by clients which want to control the reported
390 /// compilation directory and have it be something other than the current
391 /// working directory.
392 /// Returns an empty string if the current directory cannot be determined.
393 StringRef getCompilationDir() const { return CompilationDir; }
395 /// \brief Set the compilation directory for DW_AT_comp_dir
396 /// Override the default (CWD) compilation directory.
397 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
399 /// \brief Get the main file name for use in error messages and debug
400 /// info. This can be set to ensure we've got the correct file name
401 /// after preprocessing or for -save-temps.
402 const std::string &getMainFileName() const { return MainFileName; }
404 /// \brief Set the main file name and override the default.
405 void setMainFileName(StringRef S) { MainFileName = S; }
407 /// Creates an entry in the dwarf file and directory tables.
408 unsigned getDwarfFile(StringRef Directory, StringRef FileName,
409 unsigned FileNumber, unsigned CUID);
411 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
413 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
414 return MCDwarfLineTablesCUMap;
417 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
418 return MCDwarfLineTablesCUMap[CUID];
421 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
422 auto I = MCDwarfLineTablesCUMap.find(CUID);
423 assert(I != MCDwarfLineTablesCUMap.end());
427 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
428 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
430 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
431 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
434 bool hasMCLineSections() const {
435 for (const auto &Table : MCDwarfLineTablesCUMap)
436 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
440 unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
441 void setDwarfCompileUnitID(unsigned CUIndex) {
442 DwarfCompileUnitID = CUIndex;
444 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
445 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
448 /// Saves the information from the currently parsed dwarf .loc directive
449 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
450 /// in the line number table with this information and the address of the
451 /// instruction will be created.
452 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
453 unsigned Flags, unsigned Isa,
454 unsigned Discriminator) {
455 CurrentDwarfLoc.setFileNum(FileNum);
456 CurrentDwarfLoc.setLine(Line);
457 CurrentDwarfLoc.setColumn(Column);
458 CurrentDwarfLoc.setFlags(Flags);
459 CurrentDwarfLoc.setIsa(Isa);
460 CurrentDwarfLoc.setDiscriminator(Discriminator);
463 void clearDwarfLocSeen() { DwarfLocSeen = false; }
465 bool getDwarfLocSeen() { return DwarfLocSeen; }
466 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
468 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
469 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
470 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
471 void setGenDwarfFileNumber(unsigned FileNumber) {
472 GenDwarfFileNumber = FileNumber;
474 const SetVector<MCSection *> &getGenDwarfSectionSyms() {
475 return SectionsForRanges;
477 bool addGenDwarfSection(MCSection *Sec) {
478 return SectionsForRanges.insert(Sec);
481 void finalizeDwarfSections(MCStreamer &MCOS);
482 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
483 return MCGenDwarfLabelEntries;
485 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
486 MCGenDwarfLabelEntries.push_back(E);
489 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
490 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
492 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
493 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
495 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
496 uint16_t getDwarfVersion() const { return DwarfVersion; }
500 char *getSecureLogFile() { return SecureLogFile; }
501 raw_ostream *getSecureLog() { return SecureLog; }
502 bool getSecureLogUsed() { return SecureLogUsed; }
503 void setSecureLog(raw_ostream *Value) { SecureLog = Value; }
504 void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
506 void *allocate(unsigned Size, unsigned Align = 8) {
507 return Allocator.Allocate(Size, Align);
509 void deallocate(void *Ptr) {}
511 // Unrecoverable error has occurred. Display the best diagnostic we can
512 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
513 // FIXME: We should really do something about that.
514 LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
515 const Twine &Msg) const;
518 } // end namespace llvm
520 // operator new and delete aren't allowed inside namespaces.
521 // The throw specifications are mandated by the standard.
522 /// \brief Placement new for using the MCContext's allocator.
524 /// This placement form of operator new uses the MCContext's allocator for
525 /// obtaining memory. It is a non-throwing new, which means that it returns
526 /// null on error. (If that is what the allocator does. The current does, so if
527 /// this ever changes, this operator will have to be changed, too.)
528 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
530 /// // Default alignment (8)
531 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
532 /// // Specific alignment
533 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
535 /// Please note that you cannot use delete on the pointer; it must be
536 /// deallocated using an explicit destructor call followed by
537 /// \c Context.Deallocate(Ptr).
539 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
540 /// \param C The MCContext that provides the allocator.
541 /// \param Alignment The alignment of the allocated memory (if the underlying
542 /// allocator supports it).
543 /// \return The allocated memory. Could be NULL.
544 inline void *operator new(size_t Bytes, llvm::MCContext &C,
545 size_t Alignment = 8) LLVM_NOEXCEPT {
546 return C.allocate(Bytes, Alignment);
548 /// \brief Placement delete companion to the new above.
550 /// This operator is just a companion to the new above. There is no way of
551 /// invoking it directly; see the new operator for more details. This operator
552 /// is called implicitly by the compiler if a placement new expression using
553 /// the MCContext throws in the object constructor.
554 inline void operator delete(void *Ptr, llvm::MCContext &C,
555 size_t) LLVM_NOEXCEPT {
559 /// This placement form of operator new[] uses the MCContext's allocator for
560 /// obtaining memory. It is a non-throwing new[], which means that it returns
562 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
564 /// // Default alignment (8)
565 /// char *data = new (Context) char[10];
566 /// // Specific alignment
567 /// char *data = new (Context, 4) char[10];
569 /// Please note that you cannot use delete on the pointer; it must be
570 /// deallocated using an explicit destructor call followed by
571 /// \c Context.Deallocate(Ptr).
573 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
574 /// \param C The MCContext that provides the allocator.
575 /// \param Alignment The alignment of the allocated memory (if the underlying
576 /// allocator supports it).
577 /// \return The allocated memory. Could be NULL.
578 inline void *operator new[](size_t Bytes, llvm::MCContext &C,
579 size_t Alignment = 8) LLVM_NOEXCEPT {
580 return C.allocate(Bytes, Alignment);
583 /// \brief Placement delete[] companion to the new[] above.
585 /// This operator is just a companion to the new[] above. There is no way of
586 /// invoking it directly; see the new[] operator for more details. This operator
587 /// is called implicitly by the compiler if a placement new[] expression using
588 /// the MCContext throws in the object constructor.
589 inline void operator delete[](void *Ptr, llvm::MCContext &C) LLVM_NOEXCEPT {