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