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