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;
51 typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
53 /// The SourceMgr for this object, if any.
54 const SourceMgr *SrcMgr;
56 /// The MCAsmInfo for this target.
59 /// The MCRegisterInfo for this target.
60 const MCRegisterInfo *MRI;
62 /// The MCObjectFileInfo for this target.
63 const MCObjectFileInfo *MOFI;
65 /// Allocator object used for creating machine code objects.
67 /// We use a bump pointer allocator to avoid the need to track all allocated
69 BumpPtrAllocator Allocator;
71 /// Bindings of names to symbols.
74 /// ELF sections can have a corresponding symbol. This maps one to the
76 DenseMap<const MCSectionELF*, MCSymbol*> SectionSymbols;
78 /// A maping from a local label number and an instance count to a symbol.
79 /// For example, in the assembly
83 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
84 DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols;
86 /// Keeps tracks of names that were used both for used declared and
87 /// artificial symbols.
88 StringMap<bool, BumpPtrAllocator&> UsedNames;
90 /// The next ID to dole out to an unnamed assembler temporary symbol with
92 StringMap<unsigned> NextID;
94 /// Instances of directional local labels.
95 DenseMap<unsigned, MCLabel *> Instances;
96 /// NextInstance() creates the next instance of the directional local label
97 /// for the LocalLabelVal and adds it to the map if needed.
98 unsigned NextInstance(unsigned LocalLabelVal);
99 /// GetInstance() gets the current instance of the directional local label
100 /// for the LocalLabelVal and adds it to the map if needed.
101 unsigned GetInstance(unsigned LocalLabelVal);
103 /// The file name of the log file from the environment variable
104 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
105 /// directive is used or it is an error.
107 /// The stream that gets written to for the .secure_log_unique directive.
108 raw_ostream *SecureLog;
109 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
110 /// catch errors if .secure_log_unique appears twice without
111 /// .secure_log_reset appearing between them.
114 /// The compilation directory to use for DW_AT_comp_dir.
115 SmallString<128> CompilationDir;
117 /// The main file name if passed in explicitly.
118 std::string MainFileName;
120 /// The dwarf file and directory tables from the dwarf .file directive.
121 /// We now emit a line table for each compile unit. To reduce the prologue
122 /// size of each line table, the files and directories used by each compile
123 /// unit are separated.
124 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
126 /// The current dwarf line information from the last dwarf .loc directive.
127 MCDwarfLoc CurrentDwarfLoc;
130 /// Generate dwarf debugging info for assembly source files.
131 bool GenDwarfForAssembly;
133 /// The current dwarf file number when generate dwarf debugging info for
134 /// assembly source files.
135 unsigned GenDwarfFileNumber;
137 /// Symbols created for the start and end of each section, used for
138 /// generating the .debug_ranges and .debug_aranges sections.
139 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >
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;
162 /// The Compile Unit ID that we are currently processing.
163 unsigned DwarfCompileUnitID;
165 struct ELFSectionKey {
166 std::string SectionName;
169 ELFSectionKey(StringRef SectionName, StringRef GroupName,
171 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
173 bool operator<(const ELFSectionKey &Other) const {
174 if (SectionName != Other.SectionName)
175 return SectionName < Other.SectionName;
176 if (GroupName != Other.GroupName)
177 return GroupName < Other.GroupName;
178 return UniqueID < Other.UniqueID;
182 struct COFFSectionKey {
183 std::string SectionName;
186 COFFSectionKey(StringRef SectionName, StringRef GroupName,
188 : SectionName(SectionName), GroupName(GroupName),
189 SelectionKey(SelectionKey) {}
190 bool operator<(const COFFSectionKey &Other) const {
191 if (SectionName != Other.SectionName)
192 return SectionName < Other.SectionName;
193 if (GroupName != Other.GroupName)
194 return GroupName < Other.GroupName;
195 return SelectionKey < Other.SelectionKey;
199 StringMap<const MCSectionMachO*> MachOUniquingMap;
200 std::map<ELFSectionKey, const MCSectionELF *> ELFUniquingMap;
201 std::map<COFFSectionKey, const MCSectionCOFF *> COFFUniquingMap;
202 StringMap<bool> ELFRelSecNames;
204 /// Do automatic reset in destructor
207 MCSymbol *CreateSymbol(StringRef Name, bool AlwaysAddSuffix);
209 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
213 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
214 const MCObjectFileInfo *MOFI,
215 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
218 const SourceMgr *getSourceManager() const { return SrcMgr; }
220 const MCAsmInfo *getAsmInfo() const { return MAI; }
222 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
224 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
226 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
228 /// @name Module Lifetime Management
231 /// reset - return object to right after construction state to prepare
232 /// to process a new module
237 /// @name Symbol Management
240 /// Create and return a new linker temporary symbol with a unique but
241 /// unspecified name.
242 MCSymbol *CreateLinkerPrivateTempSymbol();
244 /// Create and return a new assembler temporary symbol with a unique but
245 /// unspecified name.
246 MCSymbol *CreateTempSymbol();
248 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix);
250 /// Create the definition of a directional local symbol for numbered label
251 /// (used for "1:" definitions).
252 MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal);
254 /// Create and return a directional local symbol for numbered label (used
255 /// for "1b" or 1f" references).
256 MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
258 /// Lookup the symbol inside with the specified @p Name. If it exists,
259 /// return it. If not, create a forward reference and return it.
261 /// @param Name - The symbol name, which must be unique across all symbols.
262 MCSymbol *GetOrCreateSymbol(const Twine &Name);
264 MCSymbol *getOrCreateSectionSymbol(const MCSectionELF &Section);
266 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
267 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
269 /// Get the symbol for \p Name, or null.
270 MCSymbol *LookupSymbol(const Twine &Name) const;
272 /// getSymbols - Get a reference for the symbol table for clients that
273 /// want to, for example, iterate over all symbols. 'const' because we
274 /// still want any modifications to the table itself to use the MCContext
276 const SymbolTable &getSymbols() const {
282 /// @name Section Management
285 /// Return the MCSection for the specified mach-o section. This requires
286 /// the operands to be valid.
287 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
288 unsigned TypeAndAttributes,
289 unsigned Reserved2, SectionKind K,
290 const char *BeginSymName = nullptr);
292 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
293 unsigned TypeAndAttributes,
295 const char *BeginSymName = nullptr) {
296 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
300 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
302 return getELFSection(Section, Type, Flags, nullptr);
305 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
307 const char *BeginSymName) {
308 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
311 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
312 unsigned Flags, unsigned EntrySize,
314 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
317 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
318 unsigned Flags, unsigned EntrySize,
320 const char *BeginSymName) {
321 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
325 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
326 unsigned Flags, unsigned EntrySize,
327 StringRef Group, unsigned UniqueID) {
328 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
332 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
333 unsigned Flags, unsigned EntrySize,
334 StringRef Group, unsigned UniqueID,
335 const char *BeginSymName);
337 const MCSectionELF *createELFRelSection(StringRef Name, unsigned Type,
338 unsigned Flags, unsigned EntrySize,
339 const MCSymbol *Group,
340 const MCSectionELF *Associated);
342 void renameELFSection(const MCSectionELF *Section, StringRef Name);
344 const MCSectionELF *CreateELFGroupSection();
346 const MCSectionCOFF *getCOFFSection(StringRef Section,
347 unsigned Characteristics,
349 StringRef COMDATSymName, int Selection,
350 const char *BeginSymName = nullptr);
352 const MCSectionCOFF *getCOFFSection(StringRef Section,
353 unsigned Characteristics,
355 const char *BeginSymName = nullptr);
357 const MCSectionCOFF *getCOFFSection(StringRef Section);
359 /// Gets or creates a section equivalent to Sec that is associated with the
360 /// section containing KeySym. For example, to create a debug info section
361 /// associated with an inline function, pass the normal debug info section
362 /// as Sec and the function symbol as KeySym.
363 const MCSectionCOFF *getAssociativeCOFFSection(const MCSectionCOFF *Sec,
364 const MCSymbol *KeySym);
368 /// @name Dwarf Management
371 /// \brief Get the compilation directory for DW_AT_comp_dir
372 /// This can be overridden by clients which want to control the reported
373 /// compilation directory and have it be something other than the current
374 /// working directory.
375 /// Returns an empty string if the current directory cannot be determined.
376 StringRef getCompilationDir() const { return CompilationDir; }
378 /// \brief Set the compilation directory for DW_AT_comp_dir
379 /// Override the default (CWD) compilation directory.
380 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
382 /// \brief Get the main file name for use in error messages and debug
383 /// info. This can be set to ensure we've got the correct file name
384 /// after preprocessing or for -save-temps.
385 const std::string &getMainFileName() const { return MainFileName; }
387 /// \brief Set the main file name and override the default.
388 void setMainFileName(StringRef S) { MainFileName = S; }
390 /// Creates an entry in the dwarf file and directory tables.
391 unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
392 unsigned FileNumber, unsigned CUID);
394 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
396 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
397 return MCDwarfLineTablesCUMap;
400 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
401 return MCDwarfLineTablesCUMap[CUID];
404 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
405 auto I = MCDwarfLineTablesCUMap.find(CUID);
406 assert(I != MCDwarfLineTablesCUMap.end());
410 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
411 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
413 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
414 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
417 bool hasMCLineSections() const {
418 for (const auto &Table : MCDwarfLineTablesCUMap)
419 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
423 unsigned getDwarfCompileUnitID() {
424 return DwarfCompileUnitID;
426 void setDwarfCompileUnitID(unsigned CUIndex) {
427 DwarfCompileUnitID = CUIndex;
429 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
430 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
433 /// Saves the information from the currently parsed dwarf .loc directive
434 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
435 /// in the line number table with this information and the address of the
436 /// instruction will be created.
437 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
438 unsigned Flags, unsigned Isa,
439 unsigned Discriminator) {
440 CurrentDwarfLoc.setFileNum(FileNum);
441 CurrentDwarfLoc.setLine(Line);
442 CurrentDwarfLoc.setColumn(Column);
443 CurrentDwarfLoc.setFlags(Flags);
444 CurrentDwarfLoc.setIsa(Isa);
445 CurrentDwarfLoc.setDiscriminator(Discriminator);
448 void ClearDwarfLocSeen() { DwarfLocSeen = false; }
450 bool getDwarfLocSeen() { return DwarfLocSeen; }
451 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
453 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
454 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
455 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
456 void setGenDwarfFileNumber(unsigned FileNumber) {
457 GenDwarfFileNumber = FileNumber;
459 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> > &
460 getGenDwarfSectionSyms() {
461 return SectionStartEndSyms;
463 std::pair<MapVector<const MCSection *,
464 std::pair<MCSymbol *, MCSymbol *> >::iterator,
466 addGenDwarfSection(const MCSection *Sec) {
467 return SectionStartEndSyms.insert(
468 std::make_pair(Sec, std::make_pair(nullptr, nullptr)));
470 void finalizeDwarfSections(MCStreamer &MCOS);
471 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
472 return MCGenDwarfLabelEntries;
474 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
475 MCGenDwarfLabelEntries.push_back(E);
478 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
479 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
481 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
482 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
484 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
485 uint16_t getDwarfVersion() const { return DwarfVersion; }
489 char *getSecureLogFile() { return SecureLogFile; }
490 raw_ostream *getSecureLog() { return SecureLog; }
491 bool getSecureLogUsed() { return SecureLogUsed; }
492 void setSecureLog(raw_ostream *Value) {
495 void setSecureLogUsed(bool Value) {
496 SecureLogUsed = Value;
499 void *Allocate(unsigned Size, unsigned Align = 8) {
500 return Allocator.Allocate(Size, Align);
502 void Deallocate(void *Ptr) {
505 // Unrecoverable error has occurred. Display the best diagnostic we can
506 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
507 // FIXME: We should really do something about that.
508 LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const;
511 } // end namespace llvm
513 // operator new and delete aren't allowed inside namespaces.
514 // The throw specifications are mandated by the standard.
515 /// @brief Placement new for using the MCContext's allocator.
517 /// This placement form of operator new uses the MCContext's allocator for
518 /// obtaining memory. It is a non-throwing new, which means that it returns
519 /// null on error. (If that is what the allocator does. The current does, so if
520 /// this ever changes, this operator will have to be changed, too.)
521 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
523 /// // Default alignment (16)
524 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
525 /// // Specific alignment
526 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
528 /// Please note that you cannot use delete on the pointer; it must be
529 /// deallocated using an explicit destructor call followed by
530 /// @c Context.Deallocate(Ptr).
532 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
533 /// @param C The MCContext that provides the allocator.
534 /// @param Alignment The alignment of the allocated memory (if the underlying
535 /// allocator supports it).
536 /// @return The allocated memory. Could be NULL.
537 inline void *operator new(size_t Bytes, llvm::MCContext &C,
538 size_t Alignment = 16) throw () {
539 return C.Allocate(Bytes, Alignment);
541 /// @brief Placement delete companion to the new above.
543 /// This operator is just a companion to the new above. There is no way of
544 /// invoking it directly; see the new operator for more details. This operator
545 /// is called implicitly by the compiler if a placement new expression using
546 /// the MCContext throws in the object constructor.
547 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
552 /// This placement form of operator new[] uses the MCContext's allocator for
553 /// obtaining memory. It is a non-throwing new[], which means that it returns
555 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
557 /// // Default alignment (16)
558 /// char *data = new (Context) char[10];
559 /// // Specific alignment
560 /// char *data = new (Context, 8) char[10];
562 /// Please note that you cannot use delete on the pointer; it must be
563 /// deallocated using an explicit destructor call followed by
564 /// @c Context.Deallocate(Ptr).
566 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
567 /// @param C The MCContext that provides the allocator.
568 /// @param Alignment The alignment of the allocated memory (if the underlying
569 /// allocator supports it).
570 /// @return The allocated memory. Could be NULL.
571 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
572 size_t Alignment = 16) throw () {
573 return C.Allocate(Bytes, Alignment);
576 /// @brief Placement delete[] companion to the new[] above.
578 /// This operator is just a companion to the new[] above. There is no way of
579 /// invoking it directly; see the new[] operator for more details. This operator
580 /// is called implicitly by the compiler if a placement new[] expression using
581 /// the MCContext throws in the object constructor.
582 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {