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