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