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