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.
36 class MCObjectFileInfo;
44 /// Context object for machine code objects. This class owns all of the
45 /// sections that it creates.
48 MCContext(const MCContext &) = delete;
49 MCContext &operator=(const MCContext &) = delete;
52 typedef StringMap<MCSymbol *, BumpPtrAllocator &> SymbolTable;
55 /// The SourceMgr for this object, if any.
56 const SourceMgr *SrcMgr;
58 /// The MCAsmInfo for this target.
61 /// The MCRegisterInfo for this target.
62 const MCRegisterInfo *MRI;
64 /// The MCObjectFileInfo for this target.
65 const MCObjectFileInfo *MOFI;
67 /// Allocator object used for creating machine code objects.
69 /// We use a bump pointer allocator to avoid the need to track all allocated
71 BumpPtrAllocator Allocator;
73 /// Bindings of names to symbols.
76 /// ELF sections can have a corresponding symbol. This maps one to the
78 DenseMap<const MCSectionELF *, MCSymbol *> SectionSymbols;
80 /// A mapping from a local label number and an instance count to a symbol.
81 /// For example, in the assembly
85 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
86 DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
88 /// Keeps tracks of names that were used both for used declared and
89 /// artificial symbols.
90 StringMap<bool, BumpPtrAllocator &> UsedNames;
92 /// The next ID to dole out to an unnamed assembler temporary symbol with
94 StringMap<unsigned> NextID;
96 /// Instances of directional local labels.
97 DenseMap<unsigned, MCLabel *> Instances;
98 /// NextInstance() creates the next instance of the directional local label
99 /// for the LocalLabelVal and adds it to the map if needed.
100 unsigned NextInstance(unsigned LocalLabelVal);
101 /// GetInstance() gets the current instance of the directional local label
102 /// for the LocalLabelVal and adds it to the map if needed.
103 unsigned GetInstance(unsigned LocalLabelVal);
105 /// The file name of the log file from the environment variable
106 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
107 /// directive is used or it is an error.
109 /// The stream that gets written to for the .secure_log_unique directive.
110 raw_ostream *SecureLog;
111 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
112 /// catch errors if .secure_log_unique appears twice without
113 /// .secure_log_reset appearing between them.
116 /// The compilation directory to use for DW_AT_comp_dir.
117 SmallString<128> CompilationDir;
119 /// The main file name if passed in explicitly.
120 std::string MainFileName;
122 /// The dwarf file and directory tables from the dwarf .file directive.
123 /// We now emit a line table for each compile unit. To reduce the prologue
124 /// size of each line table, the files and directories used by each compile
125 /// unit are separated.
126 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
128 /// The current dwarf line information from the last dwarf .loc directive.
129 MCDwarfLoc CurrentDwarfLoc;
132 /// Generate dwarf debugging info for assembly source files.
133 bool GenDwarfForAssembly;
135 /// The current dwarf file number when generate dwarf debugging info for
136 /// assembly source files.
137 unsigned GenDwarfFileNumber;
139 /// Sections for generating the .debug_ranges and .debug_aranges sections.
140 SetVector<MCSection *> SectionsForRanges;
142 /// The information gathered from labels that will have dwarf label
143 /// entries when generating dwarf assembly source files.
144 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
146 /// The string to embed in the debug information for the compile unit, if
148 StringRef DwarfDebugFlags;
150 /// The string to embed in as the dwarf AT_producer for the compile unit, if
152 StringRef DwarfDebugProducer;
154 /// The maximum version of dwarf that we should emit.
155 uint16_t DwarfVersion;
157 /// Honor temporary labels, this is useful for debugging semantic
158 /// differences between temporary and non-temporary labels (primarily on
160 bool AllowTemporaryLabels;
161 bool UseNamesOnTempLabels = true;
163 /// The Compile Unit ID that we are currently processing.
164 unsigned DwarfCompileUnitID;
166 struct ELFSectionKey {
167 std::string SectionName;
170 ELFSectionKey(StringRef SectionName, StringRef GroupName,
172 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
174 bool operator<(const ELFSectionKey &Other) const {
175 if (SectionName != Other.SectionName)
176 return SectionName < Other.SectionName;
177 if (GroupName != Other.GroupName)
178 return GroupName < Other.GroupName;
179 return UniqueID < Other.UniqueID;
183 struct COFFSectionKey {
184 std::string SectionName;
187 COFFSectionKey(StringRef SectionName, StringRef GroupName,
189 : SectionName(SectionName), GroupName(GroupName),
190 SelectionKey(SelectionKey) {}
191 bool operator<(const COFFSectionKey &Other) const {
192 if (SectionName != Other.SectionName)
193 return SectionName < Other.SectionName;
194 if (GroupName != Other.GroupName)
195 return GroupName < Other.GroupName;
196 return SelectionKey < Other.SelectionKey;
200 StringMap<MCSectionMachO *> MachOUniquingMap;
201 std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
202 std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
203 StringMap<bool> ELFRelSecNames;
205 /// Do automatic reset in destructor
208 MCSymbol *CreateSymbol(StringRef Name, bool AlwaysAddSuffix);
210 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
214 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
215 const MCObjectFileInfo *MOFI,
216 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
219 const SourceMgr *getSourceManager() const { return SrcMgr; }
221 const MCAsmInfo *getAsmInfo() const { return MAI; }
223 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
225 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
227 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
228 void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
230 /// \name Module Lifetime Management
233 /// reset - return object to right after construction state to prepare
234 /// to process a new module
239 /// \name Symbol Management
242 /// Create and return a new linker temporary symbol with a unique but
243 /// unspecified name.
244 MCSymbol *createLinkerPrivateTempSymbol();
246 /// Create and return a new assembler temporary symbol with a unique but
247 /// unspecified name.
248 MCSymbol *createTempSymbol();
250 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix);
252 /// Create the definition of a directional local symbol for numbered label
253 /// (used for "1:" definitions).
254 MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
256 /// Create and return a directional local symbol for numbered label (used
257 /// for "1b" or 1f" references).
258 MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
260 /// Lookup the symbol inside with the specified \p Name. If it exists,
261 /// return it. If not, create a forward reference and return it.
263 /// \param Name - The symbol name, which must be unique across all symbols.
264 MCSymbol *getOrCreateSymbol(const Twine &Name);
266 MCSymbol *getOrCreateSectionSymbol(const MCSectionELF &Section);
268 /// Gets a symbol that will be defined to the final stack offset of a local
269 /// variable after codegen.
271 /// \param Idx - The index of a local variable passed to @llvm.frameescape.
272 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
274 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
276 MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
278 /// Get the symbol for \p Name, or null.
279 MCSymbol *lookupSymbol(const Twine &Name) const;
281 /// getSymbols - Get a reference for the symbol table for clients that
282 /// want to, for example, iterate over all symbols. 'const' because we
283 /// still want any modifications to the table itself to use the MCContext
285 const SymbolTable &getSymbols() const { return Symbols; }
289 /// \name Section Management
292 /// Return the MCSection for the specified mach-o section. This requires
293 /// the operands to be valid.
294 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
295 unsigned TypeAndAttributes,
296 unsigned Reserved2, SectionKind K,
297 const char *BeginSymName = nullptr);
299 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
300 unsigned TypeAndAttributes, SectionKind K,
301 const char *BeginSymName = nullptr) {
302 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
306 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
308 return getELFSection(Section, Type, Flags, nullptr);
311 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
312 unsigned Flags, const char *BeginSymName) {
313 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
316 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
317 unsigned Flags, unsigned EntrySize,
319 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
322 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
323 unsigned Flags, unsigned EntrySize,
324 StringRef Group, const char *BeginSymName) {
325 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
329 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
330 unsigned Flags, unsigned EntrySize,
331 StringRef Group, unsigned UniqueID) {
332 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
336 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
337 unsigned Flags, unsigned EntrySize,
338 StringRef Group, unsigned UniqueID,
339 const char *BeginSymName);
341 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
342 unsigned Flags, unsigned EntrySize,
343 const MCSymbol *Group, unsigned UniqueID,
344 const char *BeginSymName,
345 const MCSectionELF *Associated);
347 MCSectionELF *createELFRelSection(StringRef Name, unsigned Type,
348 unsigned Flags, unsigned EntrySize,
349 const MCSymbol *Group,
350 const MCSectionELF *Associated);
352 void renameELFSection(MCSectionELF *Section, StringRef Name);
354 MCSectionELF *createELFGroupSection(const MCSymbol *Group);
356 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
357 SectionKind Kind, StringRef COMDATSymName,
359 const char *BeginSymName = nullptr);
361 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
363 const char *BeginSymName = nullptr);
365 MCSectionCOFF *getCOFFSection(StringRef Section);
367 /// Gets or creates a section equivalent to Sec that is associated with the
368 /// section containing KeySym. For example, to create a debug info section
369 /// associated with an inline function, pass the normal debug info section
370 /// as Sec and the function symbol as KeySym.
371 MCSectionCOFF *getAssociativeCOFFSection(MCSectionCOFF *Sec,
372 const MCSymbol *KeySym);
376 /// \name Dwarf Management
379 /// \brief Get the compilation directory for DW_AT_comp_dir
380 /// This can be overridden by clients which want to control the reported
381 /// compilation directory and have it be something other than the current
382 /// working directory.
383 /// Returns an empty string if the current directory cannot be determined.
384 StringRef getCompilationDir() const { return CompilationDir; }
386 /// \brief Set the compilation directory for DW_AT_comp_dir
387 /// Override the default (CWD) compilation directory.
388 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
390 /// \brief Get the main file name for use in error messages and debug
391 /// info. This can be set to ensure we've got the correct file name
392 /// after preprocessing or for -save-temps.
393 const std::string &getMainFileName() const { return MainFileName; }
395 /// \brief Set the main file name and override the default.
396 void setMainFileName(StringRef S) { MainFileName = S; }
398 /// Creates an entry in the dwarf file and directory tables.
399 unsigned getDwarfFile(StringRef Directory, StringRef FileName,
400 unsigned FileNumber, unsigned CUID);
402 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
404 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
405 return MCDwarfLineTablesCUMap;
408 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
409 return MCDwarfLineTablesCUMap[CUID];
412 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
413 auto I = MCDwarfLineTablesCUMap.find(CUID);
414 assert(I != MCDwarfLineTablesCUMap.end());
418 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
419 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
421 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
422 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
425 bool hasMCLineSections() const {
426 for (const auto &Table : MCDwarfLineTablesCUMap)
427 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
431 unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
432 void setDwarfCompileUnitID(unsigned CUIndex) {
433 DwarfCompileUnitID = CUIndex;
435 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
436 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
439 /// Saves the information from the currently parsed dwarf .loc directive
440 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
441 /// in the line number table with this information and the address of the
442 /// instruction will be created.
443 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
444 unsigned Flags, unsigned Isa,
445 unsigned Discriminator) {
446 CurrentDwarfLoc.setFileNum(FileNum);
447 CurrentDwarfLoc.setLine(Line);
448 CurrentDwarfLoc.setColumn(Column);
449 CurrentDwarfLoc.setFlags(Flags);
450 CurrentDwarfLoc.setIsa(Isa);
451 CurrentDwarfLoc.setDiscriminator(Discriminator);
454 void clearDwarfLocSeen() { DwarfLocSeen = false; }
456 bool getDwarfLocSeen() { return DwarfLocSeen; }
457 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
459 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
460 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
461 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
462 void setGenDwarfFileNumber(unsigned FileNumber) {
463 GenDwarfFileNumber = FileNumber;
465 const SetVector<MCSection *> &getGenDwarfSectionSyms() {
466 return SectionsForRanges;
468 bool addGenDwarfSection(MCSection *Sec) {
469 return SectionsForRanges.insert(Sec);
472 void finalizeDwarfSections(MCStreamer &MCOS);
473 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
474 return MCGenDwarfLabelEntries;
476 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
477 MCGenDwarfLabelEntries.push_back(E);
480 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
481 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
483 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
484 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
486 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
487 uint16_t getDwarfVersion() const { return DwarfVersion; }
491 char *getSecureLogFile() { return SecureLogFile; }
492 raw_ostream *getSecureLog() { return SecureLog; }
493 bool getSecureLogUsed() { return SecureLogUsed; }
494 void setSecureLog(raw_ostream *Value) { SecureLog = Value; }
495 void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
497 void *allocate(unsigned Size, unsigned Align = 8) {
498 return Allocator.Allocate(Size, Align);
500 void deallocate(void *Ptr) {}
502 // Unrecoverable error has occurred. Display the best diagnostic we can
503 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
504 // FIXME: We should really do something about that.
505 LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
506 const Twine &Msg) const;
509 } // end namespace llvm
511 // operator new and delete aren't allowed inside namespaces.
512 // The throw specifications are mandated by the standard.
513 /// \brief Placement new for using the MCContext's allocator.
515 /// This placement form of operator new uses the MCContext's allocator for
516 /// obtaining memory. It is a non-throwing new, which means that it returns
517 /// null on error. (If that is what the allocator does. The current does, so if
518 /// this ever changes, this operator will have to be changed, too.)
519 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
521 /// // Default alignment (8)
522 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
523 /// // Specific alignment
524 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
526 /// Please note that you cannot use delete on the pointer; it must be
527 /// deallocated using an explicit destructor call followed by
528 /// \c Context.Deallocate(Ptr).
530 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
531 /// \param C The MCContext that provides the allocator.
532 /// \param Alignment The alignment of the allocated memory (if the underlying
533 /// allocator supports it).
534 /// \return The allocated memory. Could be NULL.
535 inline void *operator new(size_t Bytes, llvm::MCContext &C,
536 size_t Alignment = 8) throw() {
537 return C.allocate(Bytes, Alignment);
539 /// \brief Placement delete companion to the new above.
541 /// This operator is just a companion to the new above. There is no way of
542 /// invoking it directly; see the new operator for more details. This operator
543 /// is called implicitly by the compiler if a placement new expression using
544 /// the MCContext throws in the object constructor.
545 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
550 /// This placement form of operator new[] uses the MCContext's allocator for
551 /// obtaining memory. It is a non-throwing new[], which means that it returns
553 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
555 /// // Default alignment (8)
556 /// char *data = new (Context) char[10];
557 /// // Specific alignment
558 /// char *data = new (Context, 4) char[10];
560 /// Please note that you cannot use delete on the pointer; it must be
561 /// deallocated using an explicit destructor call followed by
562 /// \c Context.Deallocate(Ptr).
564 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
565 /// \param C The MCContext that provides the allocator.
566 /// \param Alignment The alignment of the allocated memory (if the underlying
567 /// allocator supports it).
568 /// \return The allocated memory. Could be NULL.
569 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
570 size_t Alignment = 8) throw() {
571 return C.allocate(Bytes, Alignment);
574 /// \brief Placement delete[] companion to the new[] above.
576 /// This operator is just a companion to the new[] above. There is no way of
577 /// invoking it directly; see the new[] operator for more details. This operator
578 /// is called implicitly by the compiler if a placement new[] expression using
579 /// the MCContext throws in the object constructor.
580 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {