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/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/MC/MCDwarf.h"
18 #include "llvm/MC/SectionKind.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/raw_ostream.h"
23 #include <vector> // FIXME: Shouldn't be needed.
33 class MCObjectFileInfo;
42 /// MCContext - Context object for machine code objects. This class owns all
43 /// of the sections that it creates.
46 MCContext(const MCContext&) LLVM_DELETED_FUNCTION;
47 MCContext &operator=(const MCContext&) LLVM_DELETED_FUNCTION;
49 typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
51 /// The SourceMgr for this object, if any.
52 const SourceMgr *SrcMgr;
54 /// The MCAsmInfo for this target.
57 /// The MCRegisterInfo for this target.
58 const MCRegisterInfo *MRI;
60 /// The MCObjectFileInfo for this target.
61 const MCObjectFileInfo *MOFI;
63 /// Allocator - Allocator object used for creating machine code objects.
65 /// We use a bump pointer allocator to avoid the need to track all allocated
67 BumpPtrAllocator Allocator;
69 /// Symbols - Bindings of names to symbols.
72 /// UsedNames - Keeps tracks of names that were used both for used declared
73 /// and artificial symbols.
74 StringMap<bool, BumpPtrAllocator&> UsedNames;
76 /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
78 unsigned NextUniqueID;
80 /// Instances of directional local labels.
81 DenseMap<unsigned, MCLabel *> Instances;
82 /// NextInstance() creates the next instance of the directional local label
83 /// for the LocalLabelVal and adds it to the map if needed.
84 unsigned NextInstance(int64_t LocalLabelVal);
85 /// GetInstance() gets the current instance of the directional local label
86 /// for the LocalLabelVal and adds it to the map if needed.
87 unsigned GetInstance(int64_t LocalLabelVal);
89 /// The file name of the log file from the environment variable
90 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
91 /// directive is used or it is an error.
93 /// The stream that gets written to for the .secure_log_unique directive.
94 raw_ostream *SecureLog;
95 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
96 /// catch errors if .secure_log_unique appears twice without
97 /// .secure_log_reset appearing between them.
100 /// The compilation directory to use for DW_AT_comp_dir.
101 SmallString<128> CompilationDir;
103 /// The main file name if passed in explicitly.
104 std::string MainFileName;
106 /// The dwarf file and directory tables from the dwarf .file directive.
107 /// We now emit a line table for each compile unit. To reduce the prologue
108 /// size of each line table, the files and directories used by each compile
109 /// unit are separated.
110 typedef std::map<unsigned, SmallVector<MCDwarfFile *, 4> > MCDwarfFilesMap;
111 MCDwarfFilesMap MCDwarfFilesCUMap;
112 std::map<unsigned, SmallVector<StringRef, 4> > MCDwarfDirsCUMap;
114 /// The current dwarf line information from the last dwarf .loc directive.
115 MCDwarfLoc CurrentDwarfLoc;
118 /// Generate dwarf debugging info for assembly source files.
119 bool GenDwarfForAssembly;
121 /// The current dwarf file number when generate dwarf debugging info for
122 /// assembly source files.
123 unsigned GenDwarfFileNumber;
125 /// The default initial text section that we generate dwarf debugging line
126 /// info for when generating dwarf assembly source files.
127 const MCSection *GenDwarfSection;
128 /// Symbols created for the start and end of this section.
129 MCSymbol *GenDwarfSectionStartSym, *GenDwarfSectionEndSym;
131 /// The information gathered from labels that will have dwarf label
132 /// entries when generating dwarf assembly source files.
133 std::vector<const MCGenDwarfLabelEntry *> MCGenDwarfLabelEntries;
135 /// The string to embed in the debug information for the compile unit, if
137 StringRef DwarfDebugFlags;
139 /// The string to embed in as the dwarf AT_producer for the compile unit, if
141 StringRef DwarfDebugProducer;
143 /// Honor temporary labels, this is useful for debugging semantic
144 /// differences between temporary and non-temporary labels (primarily on
146 bool AllowTemporaryLabels;
148 /// The dwarf line information from the .loc directives for the sections
149 /// with assembled machine instructions have after seeing .loc directives.
150 DenseMap<const MCSection *, MCLineSection *> MCLineSections;
151 /// We need a deterministic iteration order, so we remember the order
152 /// the elements were added.
153 std::vector<const MCSection *> MCLineSectionOrder;
154 /// The Compile Unit ID that we are currently processing.
155 unsigned DwarfCompileUnitID;
156 /// The line table start symbol for each Compile Unit.
157 DenseMap<unsigned, MCSymbol *> MCLineTableSymbols;
159 void *MachOUniquingMap, *ELFUniquingMap, *COFFUniquingMap;
161 /// Do automatic reset in destructor
164 MCSymbol *CreateSymbol(StringRef Name);
167 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
168 const MCObjectFileInfo *MOFI, const SourceMgr *Mgr = 0,
169 bool DoAutoReset = true);
172 const SourceMgr *getSourceManager() const { return SrcMgr; }
174 const MCAsmInfo *getAsmInfo() const { return MAI; }
176 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
178 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
180 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
182 /// @name Module Lifetime Management
185 /// reset - return object to right after construction state to prepare
186 /// to process a new module
191 /// @name Symbol Management
194 /// CreateTempSymbol - Create and return a new assembler temporary symbol
195 /// with a unique but unspecified name.
196 MCSymbol *CreateTempSymbol();
198 /// getUniqueSymbolID() - Return a unique identifier for use in constructing
200 unsigned getUniqueSymbolID() { return NextUniqueID++; }
202 /// CreateDirectionalLocalSymbol - Create the definition of a directional
203 /// local symbol for numbered label (used for "1:" definitions).
204 MCSymbol *CreateDirectionalLocalSymbol(int64_t LocalLabelVal);
206 /// GetDirectionalLocalSymbol - Create and return a directional local
207 /// symbol for numbered label (used for "1b" or 1f" references).
208 MCSymbol *GetDirectionalLocalSymbol(int64_t LocalLabelVal, int bORf);
210 /// GetOrCreateSymbol - Lookup the symbol inside with the specified
211 /// @p Name. If it exists, return it. If not, create a forward
212 /// reference and return it.
214 /// @param Name - The symbol name, which must be unique across all symbols.
215 MCSymbol *GetOrCreateSymbol(StringRef Name);
216 MCSymbol *GetOrCreateSymbol(const Twine &Name);
218 /// LookupSymbol - Get the symbol for \p Name, or null.
219 MCSymbol *LookupSymbol(StringRef Name) const;
220 MCSymbol *LookupSymbol(const Twine &Name) const;
222 /// getSymbols - Get a reference for the symbol table for clients that
223 /// want to, for example, iterate over all symbols. 'const' because we
224 /// still want any modifications to the table itself to use the MCContext
226 const SymbolTable &getSymbols() const {
232 /// @name Section Management
235 /// getMachOSection - Return the MCSection for the specified mach-o section.
236 /// This requires the operands to be valid.
237 const MCSectionMachO *getMachOSection(StringRef Segment,
239 unsigned TypeAndAttributes,
242 const MCSectionMachO *getMachOSection(StringRef Segment,
244 unsigned TypeAndAttributes,
246 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
249 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
250 unsigned Flags, SectionKind Kind);
252 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
253 unsigned Flags, SectionKind Kind,
254 unsigned EntrySize, StringRef Group);
256 const MCSectionELF *CreateELFGroupSection();
258 const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
259 int Selection, SectionKind Kind);
261 const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
263 return getCOFFSection (Section, Characteristics, 0, Kind);
269 /// @name Dwarf Management
272 /// \brief Get the compilation directory for DW_AT_comp_dir
273 /// This can be overridden by clients which want to control the reported
274 /// compilation directory and have it be something other than the current
275 /// working directory.
276 StringRef getCompilationDir() const { return CompilationDir; }
278 /// \brief Set the compilation directory for DW_AT_comp_dir
279 /// Override the default (CWD) compilation directory.
280 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
282 /// \brief Get the main file name for use in error messages and debug
283 /// info. This can be set to ensure we've got the correct file name
284 /// after preprocessing or for -save-temps.
285 const std::string &getMainFileName() const { return MainFileName; }
287 /// \brief Set the main file name and override the default.
288 void setMainFileName(StringRef S) { MainFileName = S.str(); }
290 /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
291 unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
292 unsigned FileNumber, unsigned CUID);
294 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
296 bool hasDwarfFiles() const {
297 // Traverse MCDwarfFilesCUMap and check whether each entry is empty.
298 MCDwarfFilesMap::const_iterator MapB, MapE;
299 for (MapB = MCDwarfFilesCUMap.begin(), MapE = MCDwarfFilesCUMap.end();
300 MapB != MapE; MapB++)
301 if (!MapB->second.empty())
306 const SmallVectorImpl<MCDwarfFile *> &getMCDwarfFiles(unsigned CUID = 0) {
307 return MCDwarfFilesCUMap[CUID];
309 const SmallVectorImpl<StringRef> &getMCDwarfDirs(unsigned CUID = 0) {
310 return MCDwarfDirsCUMap[CUID];
313 const DenseMap<const MCSection *, MCLineSection *>
314 &getMCLineSections() const {
315 return MCLineSections;
317 const std::vector<const MCSection *> &getMCLineSectionOrder() const {
318 return MCLineSectionOrder;
320 void addMCLineSection(const MCSection *Sec, MCLineSection *Line) {
321 MCLineSections[Sec] = Line;
322 MCLineSectionOrder.push_back(Sec);
324 unsigned getDwarfCompileUnitID() {
325 return DwarfCompileUnitID;
327 void setDwarfCompileUnitID(unsigned CUIndex) {
328 DwarfCompileUnitID = CUIndex;
330 const DenseMap<unsigned, MCSymbol *> &getMCLineTableSymbols() const {
331 return MCLineTableSymbols;
333 MCSymbol *getMCLineTableSymbol(unsigned ID) const {
334 DenseMap<unsigned, MCSymbol *>::const_iterator CIter =
335 MCLineTableSymbols.find(ID);
336 if (CIter == MCLineTableSymbols.end())
338 return CIter->second;
340 void setMCLineTableSymbol(MCSymbol *Sym, unsigned ID) {
341 MCLineTableSymbols[ID] = Sym;
344 /// setCurrentDwarfLoc - saves the information from the currently parsed
345 /// dwarf .loc directive and sets DwarfLocSeen. When the next instruction
346 /// is assembled an entry in the line number table with this information and
347 /// the address of the instruction will be created.
348 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
349 unsigned Flags, unsigned Isa,
350 unsigned Discriminator) {
351 CurrentDwarfLoc.setFileNum(FileNum);
352 CurrentDwarfLoc.setLine(Line);
353 CurrentDwarfLoc.setColumn(Column);
354 CurrentDwarfLoc.setFlags(Flags);
355 CurrentDwarfLoc.setIsa(Isa);
356 CurrentDwarfLoc.setDiscriminator(Discriminator);
359 void ClearDwarfLocSeen() { DwarfLocSeen = false; }
361 bool getDwarfLocSeen() { return DwarfLocSeen; }
362 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
364 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
365 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
366 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
367 unsigned nextGenDwarfFileNumber() { return ++GenDwarfFileNumber; }
368 const MCSection *getGenDwarfSection() { return GenDwarfSection; }
369 void setGenDwarfSection(const MCSection *Sec) { GenDwarfSection = Sec; }
370 MCSymbol *getGenDwarfSectionStartSym() { return GenDwarfSectionStartSym; }
371 void setGenDwarfSectionStartSym(MCSymbol *Sym) {
372 GenDwarfSectionStartSym = Sym;
374 MCSymbol *getGenDwarfSectionEndSym() { return GenDwarfSectionEndSym; }
375 void setGenDwarfSectionEndSym(MCSymbol *Sym) {
376 GenDwarfSectionEndSym = Sym;
378 const std::vector<const MCGenDwarfLabelEntry *>
379 &getMCGenDwarfLabelEntries() const {
380 return MCGenDwarfLabelEntries;
382 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry *E) {
383 MCGenDwarfLabelEntries.push_back(E);
386 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
387 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
389 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
390 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
394 char *getSecureLogFile() { return SecureLogFile; }
395 raw_ostream *getSecureLog() { return SecureLog; }
396 bool getSecureLogUsed() { return SecureLogUsed; }
397 void setSecureLog(raw_ostream *Value) {
400 void setSecureLogUsed(bool Value) {
401 SecureLogUsed = Value;
404 void *Allocate(unsigned Size, unsigned Align = 8) {
405 return Allocator.Allocate(Size, Align);
407 void Deallocate(void *Ptr) {
410 // Unrecoverable error has occured. Display the best diagnostic we can
411 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
412 // FIXME: We should really do something about that.
413 LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg);
416 } // end namespace llvm
418 // operator new and delete aren't allowed inside namespaces.
419 // The throw specifications are mandated by the standard.
420 /// @brief Placement new for using the MCContext's allocator.
422 /// This placement form of operator new uses the MCContext's allocator for
423 /// obtaining memory. It is a non-throwing new, which means that it returns
424 /// null on error. (If that is what the allocator does. The current does, so if
425 /// this ever changes, this operator will have to be changed, too.)
426 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
428 /// // Default alignment (16)
429 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
430 /// // Specific alignment
431 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
433 /// Please note that you cannot use delete on the pointer; it must be
434 /// deallocated using an explicit destructor call followed by
435 /// @c Context.Deallocate(Ptr).
437 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
438 /// @param C The MCContext that provides the allocator.
439 /// @param Alignment The alignment of the allocated memory (if the underlying
440 /// allocator supports it).
441 /// @return The allocated memory. Could be NULL.
442 inline void *operator new(size_t Bytes, llvm::MCContext &C,
443 size_t Alignment = 16) throw () {
444 return C.Allocate(Bytes, Alignment);
446 /// @brief Placement delete companion to the new above.
448 /// This operator is just a companion to the new above. There is no way of
449 /// invoking it directly; see the new operator for more details. This operator
450 /// is called implicitly by the compiler if a placement new expression using
451 /// the MCContext throws in the object constructor.
452 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
457 /// This placement form of operator new[] uses the MCContext's allocator for
458 /// obtaining memory. It is a non-throwing new[], which means that it returns
460 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
462 /// // Default alignment (16)
463 /// char *data = new (Context) char[10];
464 /// // Specific alignment
465 /// char *data = new (Context, 8) char[10];
467 /// Please note that you cannot use delete on the pointer; it must be
468 /// deallocated using an explicit destructor call followed by
469 /// @c Context.Deallocate(Ptr).
471 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
472 /// @param C The MCContext that provides the allocator.
473 /// @param Alignment The alignment of the allocated memory (if the underlying
474 /// allocator supports it).
475 /// @return The allocated memory. Could be NULL.
476 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
477 size_t Alignment = 16) throw () {
478 return C.Allocate(Bytes, Alignment);
481 /// @brief Placement delete[] companion to the new[] above.
483 /// This operator is just a companion to the new[] above. There is no way of
484 /// invoking it directly; see the new[] operator for more details. This operator
485 /// is called implicitly by the compiler if a placement new[] expression using
486 /// the MCContext throws in the object constructor.
487 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {