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