Don't ask for a mode when we are not keeping the file.
[oota-llvm.git] / include / llvm / MC / MCContext.h
1 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_MC_MCCONTEXT_H
11 #define LLVM_MC_MCCONTEXT_H
12
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"
22 #include <map>
23 #include <vector> // FIXME: Shouldn't be needed.
24
25 namespace llvm {
26   class MCAsmInfo;
27   class MCExpr;
28   class MCSection;
29   class MCSymbol;
30   class MCLabel;
31   class MCDwarfFile;
32   class MCDwarfLoc;
33   class MCObjectFileInfo;
34   class MCRegisterInfo;
35   class MCLineSection;
36   class SMLoc;
37   class StringRef;
38   class Twine;
39   class MCSectionMachO;
40   class MCSectionELF;
41
42   /// MCContext - Context object for machine code objects.  This class owns all
43   /// of the sections that it creates.
44   ///
45   class MCContext {
46     MCContext(const MCContext&) LLVM_DELETED_FUNCTION;
47     MCContext &operator=(const MCContext&) LLVM_DELETED_FUNCTION;
48   public:
49     typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
50   private:
51     /// The SourceMgr for this object, if any.
52     const SourceMgr *SrcMgr;
53
54     /// The MCAsmInfo for this target.
55     const MCAsmInfo *MAI;
56
57     /// The MCRegisterInfo for this target.
58     const MCRegisterInfo *MRI;
59
60     /// The MCObjectFileInfo for this target.
61     const MCObjectFileInfo *MOFI;
62
63     /// Allocator - Allocator object used for creating machine code objects.
64     ///
65     /// We use a bump pointer allocator to avoid the need to track all allocated
66     /// objects.
67     BumpPtrAllocator Allocator;
68
69     /// Symbols - Bindings of names to symbols.
70     SymbolTable Symbols;
71
72     /// UsedNames - Keeps tracks of names that were used both for used declared
73     /// and artificial symbols.
74     StringMap<bool, BumpPtrAllocator&> UsedNames;
75
76     /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
77     /// symbol.
78     unsigned NextUniqueID;
79
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);
88
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.
92     char *SecureLogFile;
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.
98     bool SecureLogUsed;
99
100     /// The compilation directory to use for DW_AT_comp_dir.
101     SmallString<128> CompilationDir;
102
103     /// The main file name if passed in explicitly.
104     std::string MainFileName;
105
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;
113
114     /// The current dwarf line information from the last dwarf .loc directive.
115     MCDwarfLoc CurrentDwarfLoc;
116     bool DwarfLocSeen;
117
118     /// Generate dwarf debugging info for assembly source files.
119     bool GenDwarfForAssembly;
120
121     /// The current dwarf file number when generate dwarf debugging info for
122     /// assembly source files.
123     unsigned GenDwarfFileNumber;
124
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;
130
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;
134
135     /// The string to embed in the debug information for the compile unit, if
136     /// non-empty.
137     StringRef DwarfDebugFlags;
138
139     /// The string to embed in as the dwarf AT_producer for the compile unit, if
140     /// non-empty.
141     StringRef DwarfDebugProducer;
142
143     /// Honor temporary labels, this is useful for debugging semantic
144     /// differences between temporary and non-temporary labels (primarily on
145     /// Darwin).
146     bool AllowTemporaryLabels;
147
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;
158
159     void *MachOUniquingMap, *ELFUniquingMap, *COFFUniquingMap;
160
161     /// Do automatic reset in destructor
162     bool AutoReset;
163
164     MCSymbol *CreateSymbol(StringRef Name);
165
166   public:
167     explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
168                        const MCObjectFileInfo *MOFI, const SourceMgr *Mgr = 0,
169                        bool DoAutoReset = true);
170     ~MCContext();
171
172     const SourceMgr *getSourceManager() const { return SrcMgr; }
173
174     const MCAsmInfo *getAsmInfo() const { return MAI; }
175
176     const MCRegisterInfo *getRegisterInfo() const { return MRI; }
177
178     const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
179
180     void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
181
182     /// @name Module Lifetime Management
183     /// @{
184
185     /// reset - return object to right after construction state to prepare
186     /// to process a new module
187     void reset();
188
189     /// @}
190
191     /// @name Symbol Management
192     /// @{
193
194     /// CreateTempSymbol - Create and return a new assembler temporary symbol
195     /// with a unique but unspecified name.
196     MCSymbol *CreateTempSymbol();
197
198     /// getUniqueSymbolID() - Return a unique identifier for use in constructing
199     /// symbol names.
200     unsigned getUniqueSymbolID() { return NextUniqueID++; }
201
202     /// CreateDirectionalLocalSymbol - Create the definition of a directional
203     /// local symbol for numbered label (used for "1:" definitions).
204     MCSymbol *CreateDirectionalLocalSymbol(int64_t LocalLabelVal);
205
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);
209
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.
213     ///
214     /// @param Name - The symbol name, which must be unique across all symbols.
215     MCSymbol *GetOrCreateSymbol(StringRef Name);
216     MCSymbol *GetOrCreateSymbol(const Twine &Name);
217
218     /// LookupSymbol - Get the symbol for \p Name, or null.
219     MCSymbol *LookupSymbol(StringRef Name) const;
220     MCSymbol *LookupSymbol(const Twine &Name) const;
221
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
225     /// APIs.
226     const SymbolTable &getSymbols() const {
227       return Symbols;
228     }
229
230     /// @}
231
232     /// @name Section Management
233     /// @{
234
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,
238                                           StringRef Section,
239                                           unsigned TypeAndAttributes,
240                                           unsigned Reserved2,
241                                           SectionKind K);
242     const MCSectionMachO *getMachOSection(StringRef Segment,
243                                           StringRef Section,
244                                           unsigned TypeAndAttributes,
245                                           SectionKind K) {
246       return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
247     }
248
249     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
250                                       unsigned Flags, SectionKind Kind);
251
252     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
253                                       unsigned Flags, SectionKind Kind,
254                                       unsigned EntrySize, StringRef Group);
255
256     const MCSectionELF *CreateELFGroupSection();
257
258     const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
259                                     int Selection, SectionKind Kind);
260
261     const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
262                                     SectionKind Kind) {
263       return getCOFFSection (Section, Characteristics, 0, Kind);
264     }
265
266
267     /// @}
268
269     /// @name Dwarf Management
270     /// @{
271
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; }
277
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(); }
281
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; }
286
287     /// \brief Set the main file name and override the default.
288     void setMainFileName(StringRef S) { MainFileName = S.str(); }
289
290     /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
291     unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
292                           unsigned FileNumber, unsigned CUID);
293
294     bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
295
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())
302            return true;
303       return false;
304     }
305
306     const SmallVectorImpl<MCDwarfFile *> &getMCDwarfFiles(unsigned CUID = 0) {
307       return MCDwarfFilesCUMap[CUID];
308     }
309     const SmallVectorImpl<StringRef> &getMCDwarfDirs(unsigned CUID = 0) {
310       return MCDwarfDirsCUMap[CUID];
311     }
312
313     const DenseMap<const MCSection *, MCLineSection *>
314     &getMCLineSections() const {
315       return MCLineSections;
316     }
317     const std::vector<const MCSection *> &getMCLineSectionOrder() const {
318       return MCLineSectionOrder;
319     }
320     void addMCLineSection(const MCSection *Sec, MCLineSection *Line) {
321       MCLineSections[Sec] = Line;
322       MCLineSectionOrder.push_back(Sec);
323     }
324     unsigned getDwarfCompileUnitID() {
325       return DwarfCompileUnitID;
326     }
327     void setDwarfCompileUnitID(unsigned CUIndex) {
328       DwarfCompileUnitID = CUIndex;
329     }
330     const DenseMap<unsigned, MCSymbol *> &getMCLineTableSymbols() const {
331       return MCLineTableSymbols;
332     }
333     MCSymbol *getMCLineTableSymbol(unsigned ID) const {
334       DenseMap<unsigned, MCSymbol *>::const_iterator CIter =
335         MCLineTableSymbols.find(ID);
336       if (CIter == MCLineTableSymbols.end())
337         return NULL;
338       return CIter->second;
339     }
340     void setMCLineTableSymbol(MCSymbol *Sym, unsigned ID) {
341       MCLineTableSymbols[ID] = Sym;
342     }
343
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);
357       DwarfLocSeen = true;
358     }
359     void ClearDwarfLocSeen() { DwarfLocSeen = false; }
360
361     bool getDwarfLocSeen() { return DwarfLocSeen; }
362     const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
363
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;
373     }
374     MCSymbol *getGenDwarfSectionEndSym() { return GenDwarfSectionEndSym; }
375     void setGenDwarfSectionEndSym(MCSymbol *Sym) {
376       GenDwarfSectionEndSym = Sym;
377     }
378     const std::vector<const MCGenDwarfLabelEntry *>
379       &getMCGenDwarfLabelEntries() const {
380       return MCGenDwarfLabelEntries;
381     }
382     void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry *E) {
383       MCGenDwarfLabelEntries.push_back(E);
384     }
385
386     void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
387     StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
388
389     void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
390     StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
391
392     /// @}
393
394     char *getSecureLogFile() { return SecureLogFile; }
395     raw_ostream *getSecureLog() { return SecureLog; }
396     bool getSecureLogUsed() { return SecureLogUsed; }
397     void setSecureLog(raw_ostream *Value) {
398       SecureLog = Value;
399     }
400     void setSecureLogUsed(bool Value) {
401       SecureLogUsed = Value;
402     }
403
404     void *Allocate(unsigned Size, unsigned Align = 8) {
405       return Allocator.Allocate(Size, Align);
406     }
407     void Deallocate(void *Ptr) {
408     }
409
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);
414   };
415
416 } // end namespace llvm
417
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.
421 ///
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):
427 /// @code
428 /// // Default alignment (16)
429 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
430 /// // Specific alignment
431 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
432 /// @endcode
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).
436 ///
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);
445 }
446 /// @brief Placement delete companion to the new above.
447 ///
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)
453               throw () {
454   C.Deallocate(Ptr);
455 }
456
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
459 /// null on error.
460 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
461 /// @code
462 /// // Default alignment (16)
463 /// char *data = new (Context) char[10];
464 /// // Specific alignment
465 /// char *data = new (Context, 8) char[10];
466 /// @endcode
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).
470 ///
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);
479 }
480
481 /// @brief Placement delete[] companion to the new[] above.
482 ///
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 () {
488   C.Deallocate(Ptr);
489 }
490
491 #endif