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/MC/MCDwarf.h"
19 #include "llvm/MC/MCStreamer.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"
25 #include <vector> // FIXME: Shouldn't be needed.
35 class MCObjectFileInfo;
45 /// MCContext - Context object for machine code objects. This class owns all
46 /// of the sections that it creates.
49 MCContext(const MCContext&) LLVM_DELETED_FUNCTION;
50 MCContext &operator=(const MCContext&) LLVM_DELETED_FUNCTION;
52 typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
54 /// The SourceMgr for this object, if any.
55 const SourceMgr *SrcMgr;
57 /// The MCAsmInfo for this target.
60 /// The MCRegisterInfo for this target.
61 const MCRegisterInfo *MRI;
63 /// The MCObjectFileInfo for this target.
64 const MCObjectFileInfo *MOFI;
66 /// Allocator - Allocator object used for creating machine code objects.
68 /// We use a bump pointer allocator to avoid the need to track all allocated
70 BumpPtrAllocator Allocator;
72 /// Symbols - Bindings of names to symbols.
75 /// A maping from a local label number and an instance count to a symbol.
76 /// For example, in the assembly
80 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
81 DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols;
83 /// UsedNames - Keeps tracks of names that were used both for used declared
84 /// and artificial symbols.
85 StringMap<bool, BumpPtrAllocator&> UsedNames;
87 /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
89 unsigned NextUniqueID;
91 /// Instances of directional local labels.
92 DenseMap<unsigned, MCLabel *> Instances;
93 /// NextInstance() creates the next instance of the directional local label
94 /// for the LocalLabelVal and adds it to the map if needed.
95 unsigned NextInstance(unsigned LocalLabelVal);
96 /// GetInstance() gets the current instance of the directional local label
97 /// for the LocalLabelVal and adds it to the map if needed.
98 unsigned GetInstance(unsigned LocalLabelVal);
100 /// The file name of the log file from the environment variable
101 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
102 /// directive is used or it is an error.
104 /// The stream that gets written to for the .secure_log_unique directive.
105 raw_ostream *SecureLog;
106 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
107 /// catch errors if .secure_log_unique appears twice without
108 /// .secure_log_reset appearing between them.
111 /// The compilation directory to use for DW_AT_comp_dir.
112 SmallString<128> CompilationDir;
114 /// The main file name if passed in explicitly.
115 std::string MainFileName;
117 /// The dwarf file and directory tables from the dwarf .file directive.
118 /// We now emit a line table for each compile unit. To reduce the prologue
119 /// size of each line table, the files and directories used by each compile
120 /// unit are separated.
121 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
123 /// The current dwarf line information from the last dwarf .loc directive.
124 MCDwarfLoc CurrentDwarfLoc;
127 /// Generate dwarf debugging info for assembly source files.
128 bool GenDwarfForAssembly;
130 /// The current dwarf file number when generate dwarf debugging info for
131 /// assembly source files.
132 unsigned GenDwarfFileNumber;
134 /// Symbols created for the start and end of each section, used for
135 /// generating the .debug_ranges and .debug_aranges sections.
136 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >
139 /// The information gathered from labels that will have dwarf label
140 /// entries when generating dwarf assembly source files.
141 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
143 /// The string to embed in the debug information for the compile unit, if
145 StringRef DwarfDebugFlags;
147 /// The string to embed in as the dwarf AT_producer for the compile unit, if
149 StringRef DwarfDebugProducer;
151 /// The maximum version of dwarf that we should emit.
152 uint16_t DwarfVersion;
154 /// Honor temporary labels, this is useful for debugging semantic
155 /// differences between temporary and non-temporary labels (primarily on
157 bool AllowTemporaryLabels;
159 /// The Compile Unit ID that we are currently processing.
160 unsigned DwarfCompileUnitID;
162 typedef std::pair<std::string, std::string> SectionGroupPair;
164 StringMap<const MCSectionMachO*> MachOUniquingMap;
165 std::map<SectionGroupPair, const MCSectionELF *> ELFUniquingMap;
166 std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniquingMap;
168 /// Do automatic reset in destructor
171 MCSymbol *CreateSymbol(StringRef Name);
173 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
177 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
178 const MCObjectFileInfo *MOFI,
179 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
182 const SourceMgr *getSourceManager() const { return SrcMgr; }
184 const MCAsmInfo *getAsmInfo() const { return MAI; }
186 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
188 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
190 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
192 /// @name Module Lifetime Management
195 /// reset - return object to right after construction state to prepare
196 /// to process a new module
201 /// @name Symbol Management
204 /// CreateLinkerPrivateTempSymbol - Create and return a new linker temporary
205 /// symbol with a unique but unspecified name.
206 MCSymbol *CreateLinkerPrivateTempSymbol();
208 /// CreateTempSymbol - Create and return a new assembler temporary symbol
209 /// with a unique but unspecified name.
210 MCSymbol *CreateTempSymbol();
212 /// getUniqueSymbolID() - Return a unique identifier for use in constructing
214 unsigned getUniqueSymbolID() { return NextUniqueID++; }
216 /// Create the definition of a directional local symbol for numbered label
217 /// (used for "1:" definitions).
218 MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal);
220 /// Create and return a directional local symbol for numbered label (used
221 /// for "1b" or 1f" references).
222 MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
224 /// GetOrCreateSymbol - Lookup the symbol inside with the specified
225 /// @p Name. If it exists, return it. If not, create a forward
226 /// reference and return it.
228 /// @param Name - The symbol name, which must be unique across all symbols.
229 MCSymbol *GetOrCreateSymbol(StringRef Name);
230 MCSymbol *GetOrCreateSymbol(const Twine &Name);
232 /// LookupSymbol - Get the symbol for \p Name, or null.
233 MCSymbol *LookupSymbol(StringRef Name) const;
234 MCSymbol *LookupSymbol(const Twine &Name) const;
236 /// getSymbols - Get a reference for the symbol table for clients that
237 /// want to, for example, iterate over all symbols. 'const' because we
238 /// still want any modifications to the table itself to use the MCContext
240 const SymbolTable &getSymbols() const {
246 /// @name Section Management
249 /// getMachOSection - Return the MCSection for the specified mach-o section.
250 /// This requires the operands to be valid.
251 const MCSectionMachO *getMachOSection(StringRef Segment,
253 unsigned TypeAndAttributes,
256 const MCSectionMachO *getMachOSection(StringRef Segment,
258 unsigned TypeAndAttributes,
260 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
263 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
264 unsigned Flags, SectionKind Kind);
266 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
267 unsigned Flags, SectionKind Kind,
268 unsigned EntrySize, StringRef Group);
270 void renameELFSection(const MCSectionELF *Section, StringRef Name);
272 const MCSectionELF *CreateELFGroupSection();
274 const MCSectionCOFF *getCOFFSection(StringRef Section,
275 unsigned Characteristics,
277 StringRef COMDATSymName, int Selection);
279 const MCSectionCOFF *getCOFFSection(StringRef Section,
280 unsigned Characteristics,
283 const MCSectionCOFF *getCOFFSection(StringRef Section);
287 /// @name Dwarf Management
290 /// \brief Get the compilation directory for DW_AT_comp_dir
291 /// This can be overridden by clients which want to control the reported
292 /// compilation directory and have it be something other than the current
293 /// working directory.
294 /// Returns an empty string if the current directory cannot be determined.
295 StringRef getCompilationDir() const { return CompilationDir; }
297 /// \brief Set the compilation directory for DW_AT_comp_dir
298 /// Override the default (CWD) compilation directory.
299 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
301 /// \brief Get the main file name for use in error messages and debug
302 /// info. This can be set to ensure we've got the correct file name
303 /// after preprocessing or for -save-temps.
304 const std::string &getMainFileName() const { return MainFileName; }
306 /// \brief Set the main file name and override the default.
307 void setMainFileName(StringRef S) { MainFileName = S; }
309 /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
310 unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
311 unsigned FileNumber, unsigned CUID);
313 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
315 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
316 return MCDwarfLineTablesCUMap;
319 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
320 return MCDwarfLineTablesCUMap[CUID];
323 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
324 auto I = MCDwarfLineTablesCUMap.find(CUID);
325 assert(I != MCDwarfLineTablesCUMap.end());
329 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
330 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
332 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
333 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
336 bool hasMCLineSections() const {
337 for (const auto &Table : MCDwarfLineTablesCUMap)
338 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
342 unsigned getDwarfCompileUnitID() {
343 return DwarfCompileUnitID;
345 void setDwarfCompileUnitID(unsigned CUIndex) {
346 DwarfCompileUnitID = CUIndex;
348 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
349 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
352 /// setCurrentDwarfLoc - saves the information from the currently parsed
353 /// dwarf .loc directive and sets DwarfLocSeen. When the next instruction
354 /// is assembled an entry in the line number table with this information and
355 /// the address of the instruction will be created.
356 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
357 unsigned Flags, unsigned Isa,
358 unsigned Discriminator) {
359 CurrentDwarfLoc.setFileNum(FileNum);
360 CurrentDwarfLoc.setLine(Line);
361 CurrentDwarfLoc.setColumn(Column);
362 CurrentDwarfLoc.setFlags(Flags);
363 CurrentDwarfLoc.setIsa(Isa);
364 CurrentDwarfLoc.setDiscriminator(Discriminator);
367 void ClearDwarfLocSeen() { DwarfLocSeen = false; }
369 bool getDwarfLocSeen() { return DwarfLocSeen; }
370 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
372 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
373 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
374 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
375 void setGenDwarfFileNumber(unsigned FileNumber) {
376 GenDwarfFileNumber = FileNumber;
378 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> > &
379 getGenDwarfSectionSyms() {
380 return SectionStartEndSyms;
382 std::pair<MapVector<const MCSection *,
383 std::pair<MCSymbol *, MCSymbol *> >::iterator,
385 addGenDwarfSection(const MCSection *Sec) {
386 return SectionStartEndSyms.insert(
387 std::make_pair(Sec, std::make_pair(nullptr, nullptr)));
389 void finalizeDwarfSections(MCStreamer &MCOS);
390 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
391 return MCGenDwarfLabelEntries;
393 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
394 MCGenDwarfLabelEntries.push_back(E);
397 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
398 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
400 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
401 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
403 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
404 uint16_t getDwarfVersion() const { return DwarfVersion; }
408 char *getSecureLogFile() { return SecureLogFile; }
409 raw_ostream *getSecureLog() { return SecureLog; }
410 bool getSecureLogUsed() { return SecureLogUsed; }
411 void setSecureLog(raw_ostream *Value) {
414 void setSecureLogUsed(bool Value) {
415 SecureLogUsed = Value;
418 void *Allocate(unsigned Size, unsigned Align = 8) {
419 return Allocator.Allocate(Size, Align);
421 void Deallocate(void *Ptr) {
424 // Unrecoverable error has occurred. Display the best diagnostic we can
425 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
426 // FIXME: We should really do something about that.
427 LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const;
430 } // end namespace llvm
432 // operator new and delete aren't allowed inside namespaces.
433 // The throw specifications are mandated by the standard.
434 /// @brief Placement new for using the MCContext's allocator.
436 /// This placement form of operator new uses the MCContext's allocator for
437 /// obtaining memory. It is a non-throwing new, which means that it returns
438 /// null on error. (If that is what the allocator does. The current does, so if
439 /// this ever changes, this operator will have to be changed, too.)
440 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
442 /// // Default alignment (16)
443 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
444 /// // Specific alignment
445 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
447 /// Please note that you cannot use delete on the pointer; it must be
448 /// deallocated using an explicit destructor call followed by
449 /// @c Context.Deallocate(Ptr).
451 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
452 /// @param C The MCContext that provides the allocator.
453 /// @param Alignment The alignment of the allocated memory (if the underlying
454 /// allocator supports it).
455 /// @return The allocated memory. Could be NULL.
456 inline void *operator new(size_t Bytes, llvm::MCContext &C,
457 size_t Alignment = 16) throw () {
458 return C.Allocate(Bytes, Alignment);
460 /// @brief Placement delete companion to the new above.
462 /// This operator is just a companion to the new above. There is no way of
463 /// invoking it directly; see the new operator for more details. This operator
464 /// is called implicitly by the compiler if a placement new expression using
465 /// the MCContext throws in the object constructor.
466 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
471 /// This placement form of operator new[] uses the MCContext's allocator for
472 /// obtaining memory. It is a non-throwing new[], which means that it returns
474 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
476 /// // Default alignment (16)
477 /// char *data = new (Context) char[10];
478 /// // Specific alignment
479 /// char *data = new (Context, 8) char[10];
481 /// Please note that you cannot use delete on the pointer; it must be
482 /// deallocated using an explicit destructor call followed by
483 /// @c Context.Deallocate(Ptr).
485 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
486 /// @param C The MCContext that provides the allocator.
487 /// @param Alignment The alignment of the allocated memory (if the underlying
488 /// allocator supports it).
489 /// @return The allocated memory. Could be NULL.
490 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
491 size_t Alignment = 16) throw () {
492 return C.Allocate(Bytes, Alignment);
495 /// @brief Placement delete[] companion to the new[] above.
497 /// This operator is just a companion to the new[] above. There is no way of
498 /// invoking it directly; see the new[] operator for more details. This operator
499 /// is called implicitly by the compiler if a placement new[] expression using
500 /// the MCContext throws in the object constructor.
501 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {