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/SectionKind.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/Compiler.h"
22 #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&) = delete;
50 MCContext &operator=(const MCContext&) = delete;
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 /// ELF sections can have a corresponding symbol. This maps one to the
77 DenseMap<const MCSectionELF*, MCSymbol*> SectionSymbols;
79 /// A maping from a local label number and an instance count to a symbol.
80 /// For example, in the assembly
84 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
85 DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols;
87 /// UsedNames - Keeps tracks of names that were used both for used declared
88 /// and artificial symbols.
89 StringMap<bool, BumpPtrAllocator&> UsedNames;
91 /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
93 unsigned NextUniqueID;
95 /// Instances of directional local labels.
96 DenseMap<unsigned, MCLabel *> Instances;
97 /// NextInstance() creates the next instance of the directional local label
98 /// for the LocalLabelVal and adds it to the map if needed.
99 unsigned NextInstance(unsigned LocalLabelVal);
100 /// GetInstance() gets the current instance of the directional local label
101 /// for the LocalLabelVal and adds it to the map if needed.
102 unsigned GetInstance(unsigned LocalLabelVal);
104 /// The file name of the log file from the environment variable
105 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
106 /// directive is used or it is an error.
108 /// The stream that gets written to for the .secure_log_unique directive.
109 raw_ostream *SecureLog;
110 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
111 /// catch errors if .secure_log_unique appears twice without
112 /// .secure_log_reset appearing between them.
115 /// The compilation directory to use for DW_AT_comp_dir.
116 SmallString<128> CompilationDir;
118 /// The main file name if passed in explicitly.
119 std::string MainFileName;
121 /// The dwarf file and directory tables from the dwarf .file directive.
122 /// We now emit a line table for each compile unit. To reduce the prologue
123 /// size of each line table, the files and directories used by each compile
124 /// unit are separated.
125 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
127 /// The current dwarf line information from the last dwarf .loc directive.
128 MCDwarfLoc CurrentDwarfLoc;
131 /// Generate dwarf debugging info for assembly source files.
132 bool GenDwarfForAssembly;
134 /// The current dwarf file number when generate dwarf debugging info for
135 /// assembly source files.
136 unsigned GenDwarfFileNumber;
138 /// Symbols created for the start and end of each section, used for
139 /// generating the .debug_ranges and .debug_aranges sections.
140 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >
143 /// The information gathered from labels that will have dwarf label
144 /// entries when generating dwarf assembly source files.
145 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
147 /// The string to embed in the debug information for the compile unit, if
149 StringRef DwarfDebugFlags;
151 /// The string to embed in as the dwarf AT_producer for the compile unit, if
153 StringRef DwarfDebugProducer;
155 /// The maximum version of dwarf that we should emit.
156 uint16_t DwarfVersion;
158 /// Honor temporary labels, this is useful for debugging semantic
159 /// differences between temporary and non-temporary labels (primarily on
161 bool AllowTemporaryLabels;
163 /// The Compile Unit ID that we are currently processing.
164 unsigned DwarfCompileUnitID;
166 typedef std::pair<std::string, std::string> SectionGroupPair;
167 typedef std::tuple<std::string, std::string, int> SectionGroupTriple;
169 StringMap<const MCSectionMachO*> MachOUniquingMap;
170 std::map<SectionGroupPair, const MCSectionELF *> ELFUniquingMap;
171 std::map<SectionGroupTriple, const MCSectionCOFF *> COFFUniquingMap;
173 /// Do automatic reset in destructor
176 MCSymbol *CreateSymbol(StringRef Name);
178 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
182 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
183 const MCObjectFileInfo *MOFI,
184 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
187 const SourceMgr *getSourceManager() const { return SrcMgr; }
189 const MCAsmInfo *getAsmInfo() const { return MAI; }
191 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
193 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
195 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
197 /// @name Module Lifetime Management
200 /// reset - return object to right after construction state to prepare
201 /// to process a new module
206 /// @name Symbol Management
209 /// CreateLinkerPrivateTempSymbol - Create and return a new linker temporary
210 /// symbol with a unique but unspecified name.
211 MCSymbol *CreateLinkerPrivateTempSymbol();
213 /// CreateTempSymbol - Create and return a new assembler temporary symbol
214 /// with a unique but unspecified name.
215 MCSymbol *CreateTempSymbol();
217 MCSymbol *createTempSymbol(const Twine &Name);
219 /// getUniqueSymbolID() - Return a unique identifier for use in constructing
221 unsigned getUniqueSymbolID() { return NextUniqueID++; }
223 /// Create the definition of a directional local symbol for numbered label
224 /// (used for "1:" definitions).
225 MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal);
227 /// Create and return a directional local symbol for numbered label (used
228 /// for "1b" or 1f" references).
229 MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
231 /// GetOrCreateSymbol - Lookup the symbol inside with the specified
232 /// @p Name. If it exists, return it. If not, create a forward
233 /// reference and return it.
235 /// @param Name - The symbol name, which must be unique across all symbols.
236 MCSymbol *GetOrCreateSymbol(StringRef Name);
237 MCSymbol *GetOrCreateSymbol(const Twine &Name);
239 MCSymbol *getOrCreateSectionSymbol(const MCSectionELF &Section);
241 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
243 /// LookupSymbol - Get the symbol for \p Name, or null.
244 MCSymbol *LookupSymbol(StringRef Name) const;
245 MCSymbol *LookupSymbol(const Twine &Name) const;
247 /// getSymbols - Get a reference for the symbol table for clients that
248 /// want to, for example, iterate over all symbols. 'const' because we
249 /// still want any modifications to the table itself to use the MCContext
251 const SymbolTable &getSymbols() const {
257 /// @name Section Management
260 /// getMachOSection - Return the MCSection for the specified mach-o section.
261 /// This requires the operands to be valid.
262 const MCSectionMachO *getMachOSection(StringRef Segment,
264 unsigned TypeAndAttributes,
267 const MCSectionMachO *getMachOSection(StringRef Segment,
269 unsigned TypeAndAttributes,
271 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
274 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
277 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
278 unsigned Flags, unsigned EntrySize,
281 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
282 unsigned Flags, unsigned EntrySize,
283 StringRef Group, bool Unique);
285 void renameELFSection(const MCSectionELF *Section, StringRef Name);
287 const MCSectionELF *CreateELFGroupSection();
289 const MCSectionCOFF *getCOFFSection(StringRef Section,
290 unsigned Characteristics,
292 StringRef COMDATSymName, int Selection);
294 const MCSectionCOFF *getCOFFSection(StringRef Section,
295 unsigned Characteristics,
298 const MCSectionCOFF *getCOFFSection(StringRef Section);
300 /// Gets or creates a section equivalent to Sec that is associated with the
301 /// section containing KeySym. For example, to create a debug info section
302 /// associated with an inline function, pass the normal debug info section
303 /// as Sec and the function symbol as KeySym.
304 const MCSectionCOFF *getAssociativeCOFFSection(const MCSectionCOFF *Sec,
305 const MCSymbol *KeySym);
309 /// @name Dwarf Management
312 /// \brief Get the compilation directory for DW_AT_comp_dir
313 /// This can be overridden by clients which want to control the reported
314 /// compilation directory and have it be something other than the current
315 /// working directory.
316 /// Returns an empty string if the current directory cannot be determined.
317 StringRef getCompilationDir() const { return CompilationDir; }
319 /// \brief Set the compilation directory for DW_AT_comp_dir
320 /// Override the default (CWD) compilation directory.
321 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
323 /// \brief Get the main file name for use in error messages and debug
324 /// info. This can be set to ensure we've got the correct file name
325 /// after preprocessing or for -save-temps.
326 const std::string &getMainFileName() const { return MainFileName; }
328 /// \brief Set the main file name and override the default.
329 void setMainFileName(StringRef S) { MainFileName = S; }
331 /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
332 unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
333 unsigned FileNumber, unsigned CUID);
335 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
337 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
338 return MCDwarfLineTablesCUMap;
341 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
342 return MCDwarfLineTablesCUMap[CUID];
345 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
346 auto I = MCDwarfLineTablesCUMap.find(CUID);
347 assert(I != MCDwarfLineTablesCUMap.end());
351 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
352 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
354 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
355 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
358 bool hasMCLineSections() const {
359 for (const auto &Table : MCDwarfLineTablesCUMap)
360 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
364 unsigned getDwarfCompileUnitID() {
365 return DwarfCompileUnitID;
367 void setDwarfCompileUnitID(unsigned CUIndex) {
368 DwarfCompileUnitID = CUIndex;
370 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
371 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
374 /// setCurrentDwarfLoc - saves the information from the currently parsed
375 /// dwarf .loc directive and sets DwarfLocSeen. When the next instruction
376 /// is assembled an entry in the line number table with this information and
377 /// the address of the instruction will be created.
378 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
379 unsigned Flags, unsigned Isa,
380 unsigned Discriminator) {
381 CurrentDwarfLoc.setFileNum(FileNum);
382 CurrentDwarfLoc.setLine(Line);
383 CurrentDwarfLoc.setColumn(Column);
384 CurrentDwarfLoc.setFlags(Flags);
385 CurrentDwarfLoc.setIsa(Isa);
386 CurrentDwarfLoc.setDiscriminator(Discriminator);
389 void ClearDwarfLocSeen() { DwarfLocSeen = false; }
391 bool getDwarfLocSeen() { return DwarfLocSeen; }
392 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
394 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
395 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
396 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
397 void setGenDwarfFileNumber(unsigned FileNumber) {
398 GenDwarfFileNumber = FileNumber;
400 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> > &
401 getGenDwarfSectionSyms() {
402 return SectionStartEndSyms;
404 std::pair<MapVector<const MCSection *,
405 std::pair<MCSymbol *, MCSymbol *> >::iterator,
407 addGenDwarfSection(const MCSection *Sec) {
408 return SectionStartEndSyms.insert(
409 std::make_pair(Sec, std::make_pair(nullptr, nullptr)));
411 void finalizeDwarfSections(MCStreamer &MCOS);
412 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
413 return MCGenDwarfLabelEntries;
415 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
416 MCGenDwarfLabelEntries.push_back(E);
419 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
420 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
422 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
423 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
425 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
426 uint16_t getDwarfVersion() const { return DwarfVersion; }
430 char *getSecureLogFile() { return SecureLogFile; }
431 raw_ostream *getSecureLog() { return SecureLog; }
432 bool getSecureLogUsed() { return SecureLogUsed; }
433 void setSecureLog(raw_ostream *Value) {
436 void setSecureLogUsed(bool Value) {
437 SecureLogUsed = Value;
440 void *Allocate(unsigned Size, unsigned Align = 8) {
441 return Allocator.Allocate(Size, Align);
443 void Deallocate(void *Ptr) {
446 // Unrecoverable error has occurred. Display the best diagnostic we can
447 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
448 // FIXME: We should really do something about that.
449 LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const;
452 } // end namespace llvm
454 // operator new and delete aren't allowed inside namespaces.
455 // The throw specifications are mandated by the standard.
456 /// @brief Placement new for using the MCContext's allocator.
458 /// This placement form of operator new uses the MCContext's allocator for
459 /// obtaining memory. It is a non-throwing new, which means that it returns
460 /// null on error. (If that is what the allocator does. The current does, so if
461 /// this ever changes, this operator will have to be changed, too.)
462 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
464 /// // Default alignment (16)
465 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
466 /// // Specific alignment
467 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
469 /// Please note that you cannot use delete on the pointer; it must be
470 /// deallocated using an explicit destructor call followed by
471 /// @c Context.Deallocate(Ptr).
473 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
474 /// @param C The MCContext that provides the allocator.
475 /// @param Alignment The alignment of the allocated memory (if the underlying
476 /// allocator supports it).
477 /// @return The allocated memory. Could be NULL.
478 inline void *operator new(size_t Bytes, llvm::MCContext &C,
479 size_t Alignment = 16) throw () {
480 return C.Allocate(Bytes, Alignment);
482 /// @brief Placement delete companion to the new above.
484 /// This operator is just a companion to the new above. There is no way of
485 /// invoking it directly; see the new operator for more details. This operator
486 /// is called implicitly by the compiler if a placement new expression using
487 /// the MCContext throws in the object constructor.
488 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
493 /// This placement form of operator new[] uses the MCContext's allocator for
494 /// obtaining memory. It is a non-throwing new[], which means that it returns
496 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
498 /// // Default alignment (16)
499 /// char *data = new (Context) char[10];
500 /// // Specific alignment
501 /// char *data = new (Context, 8) char[10];
503 /// Please note that you cannot use delete on the pointer; it must be
504 /// deallocated using an explicit destructor call followed by
505 /// @c Context.Deallocate(Ptr).
507 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
508 /// @param C The MCContext that provides the allocator.
509 /// @param Alignment The alignment of the allocated memory (if the underlying
510 /// allocator supports it).
511 /// @return The allocated memory. Could be NULL.
512 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
513 size_t Alignment = 16) throw () {
514 return C.Allocate(Bytes, Alignment);
517 /// @brief Placement delete[] companion to the new[] above.
519 /// This operator is just a companion to the new[] above. There is no way of
520 /// invoking it directly; see the new[] operator for more details. This operator
521 /// is called implicitly by the compiler if a placement new[] expression using
522 /// the MCContext throws in the object constructor.
523 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {