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