LLVM API Documentation

MCContext.h
Go to the documentation of this file.
00001 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #ifndef LLVM_MC_MCCONTEXT_H
00011 #define LLVM_MC_MCCONTEXT_H
00012 
00013 #include "llvm/ADT/DenseMap.h"
00014 #include "llvm/ADT/SetVector.h"
00015 #include "llvm/ADT/SmallString.h"
00016 #include "llvm/ADT/SmallVector.h"
00017 #include "llvm/ADT/StringMap.h"
00018 #include "llvm/MC/MCDwarf.h"
00019 #include "llvm/MC/MCStreamer.h"
00020 #include "llvm/MC/SectionKind.h"
00021 #include "llvm/Support/Allocator.h"
00022 #include "llvm/Support/Compiler.h"
00023 #include "llvm/Support/raw_ostream.h"
00024 #include <map>
00025 #include <tuple>
00026 #include <vector> // FIXME: Shouldn't be needed.
00027 
00028 namespace llvm {
00029   class MCAsmInfo;
00030   class MCExpr;
00031   class MCSection;
00032   class MCSymbol;
00033   class MCLabel;
00034   struct MCDwarfFile;
00035   class MCDwarfLoc;
00036   class MCObjectFileInfo;
00037   class MCRegisterInfo;
00038   class MCLineSection;
00039   class SMLoc;
00040   class StringRef;
00041   class Twine;
00042   class MCSectionMachO;
00043   class MCSectionELF;
00044   class MCSectionCOFF;
00045 
00046   /// MCContext - Context object for machine code objects.  This class owns all
00047   /// of the sections that it creates.
00048   ///
00049   class MCContext {
00050     MCContext(const MCContext&) LLVM_DELETED_FUNCTION;
00051     MCContext &operator=(const MCContext&) LLVM_DELETED_FUNCTION;
00052   public:
00053     typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
00054   private:
00055     /// The SourceMgr for this object, if any.
00056     const SourceMgr *SrcMgr;
00057 
00058     /// The MCAsmInfo for this target.
00059     const MCAsmInfo *MAI;
00060 
00061     /// The MCRegisterInfo for this target.
00062     const MCRegisterInfo *MRI;
00063 
00064     /// The MCObjectFileInfo for this target.
00065     const MCObjectFileInfo *MOFI;
00066 
00067     /// Allocator - Allocator object used for creating machine code objects.
00068     ///
00069     /// We use a bump pointer allocator to avoid the need to track all allocated
00070     /// objects.
00071     BumpPtrAllocator Allocator;
00072 
00073     /// Symbols - Bindings of names to symbols.
00074     SymbolTable Symbols;
00075 
00076     /// A maping from a local label number and an instance count to a symbol.
00077     /// For example, in the assembly
00078     ///     1:
00079     ///     2:
00080     ///     1:
00081     /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
00082     DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols;
00083 
00084     /// UsedNames - Keeps tracks of names that were used both for used declared
00085     /// and artificial symbols.
00086     StringMap<bool, BumpPtrAllocator&> UsedNames;
00087 
00088     /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
00089     /// symbol.
00090     unsigned NextUniqueID;
00091 
00092     /// Instances of directional local labels.
00093     DenseMap<unsigned, MCLabel *> Instances;
00094     /// NextInstance() creates the next instance of the directional local label
00095     /// for the LocalLabelVal and adds it to the map if needed.
00096     unsigned NextInstance(unsigned LocalLabelVal);
00097     /// GetInstance() gets the current instance of the directional local label
00098     /// for the LocalLabelVal and adds it to the map if needed.
00099     unsigned GetInstance(unsigned LocalLabelVal);
00100 
00101     /// The file name of the log file from the environment variable
00102     /// AS_SECURE_LOG_FILE.  Which must be set before the .secure_log_unique
00103     /// directive is used or it is an error.
00104     char *SecureLogFile;
00105     /// The stream that gets written to for the .secure_log_unique directive.
00106     raw_ostream *SecureLog;
00107     /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
00108     /// catch errors if .secure_log_unique appears twice without
00109     /// .secure_log_reset appearing between them.
00110     bool SecureLogUsed;
00111 
00112     /// The compilation directory to use for DW_AT_comp_dir.
00113     SmallString<128> CompilationDir;
00114 
00115     /// The main file name if passed in explicitly.
00116     std::string MainFileName;
00117 
00118     /// The dwarf file and directory tables from the dwarf .file directive.
00119     /// We now emit a line table for each compile unit. To reduce the prologue
00120     /// size of each line table, the files and directories used by each compile
00121     /// unit are separated.
00122     std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
00123 
00124     /// The current dwarf line information from the last dwarf .loc directive.
00125     MCDwarfLoc CurrentDwarfLoc;
00126     bool DwarfLocSeen;
00127 
00128     /// Generate dwarf debugging info for assembly source files.
00129     bool GenDwarfForAssembly;
00130 
00131     /// The current dwarf file number when generate dwarf debugging info for
00132     /// assembly source files.
00133     unsigned GenDwarfFileNumber;
00134 
00135     /// Symbols created for the start and end of each section, used for
00136     /// generating the .debug_ranges and .debug_aranges sections.
00137     MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >
00138     SectionStartEndSyms;
00139 
00140     /// The information gathered from labels that will have dwarf label
00141     /// entries when generating dwarf assembly source files.
00142     std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
00143 
00144     /// The string to embed in the debug information for the compile unit, if
00145     /// non-empty.
00146     StringRef DwarfDebugFlags;
00147 
00148     /// The string to embed in as the dwarf AT_producer for the compile unit, if
00149     /// non-empty.
00150     StringRef DwarfDebugProducer;
00151 
00152     /// The maximum version of dwarf that we should emit.
00153     uint16_t DwarfVersion;
00154 
00155     /// Honor temporary labels, this is useful for debugging semantic
00156     /// differences between temporary and non-temporary labels (primarily on
00157     /// Darwin).
00158     bool AllowTemporaryLabels;
00159 
00160     /// The Compile Unit ID that we are currently processing.
00161     unsigned DwarfCompileUnitID;
00162 
00163     typedef std::pair<std::string, std::string> SectionGroupPair;
00164     typedef std::tuple<std::string, std::string, int> SectionGroupTriple;
00165 
00166     StringMap<const MCSectionMachO*> MachOUniquingMap;
00167     std::map<SectionGroupPair, const MCSectionELF *> ELFUniquingMap;
00168     std::map<SectionGroupTriple, const MCSectionCOFF *> COFFUniquingMap;
00169 
00170     /// Do automatic reset in destructor
00171     bool AutoReset;
00172 
00173     MCSymbol *CreateSymbol(StringRef Name);
00174 
00175     MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
00176                                                 unsigned Instance);
00177 
00178   public:
00179     explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
00180                        const MCObjectFileInfo *MOFI,
00181                        const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
00182     ~MCContext();
00183 
00184     const SourceMgr *getSourceManager() const { return SrcMgr; }
00185 
00186     const MCAsmInfo *getAsmInfo() const { return MAI; }
00187 
00188     const MCRegisterInfo *getRegisterInfo() const { return MRI; }
00189 
00190     const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
00191 
00192     void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
00193 
00194     /// @name Module Lifetime Management
00195     /// @{
00196 
00197     /// reset - return object to right after construction state to prepare
00198     /// to process a new module
00199     void reset();
00200 
00201     /// @}
00202 
00203     /// @name Symbol Management
00204     /// @{
00205 
00206     /// CreateLinkerPrivateTempSymbol - Create and return a new linker temporary
00207     /// symbol with a unique but unspecified name.
00208     MCSymbol *CreateLinkerPrivateTempSymbol();
00209 
00210     /// CreateTempSymbol - Create and return a new assembler temporary symbol
00211     /// with a unique but unspecified name.
00212     MCSymbol *CreateTempSymbol();
00213 
00214     /// getUniqueSymbolID() - Return a unique identifier for use in constructing
00215     /// symbol names.
00216     unsigned getUniqueSymbolID() { return NextUniqueID++; }
00217 
00218     /// Create the definition of a directional local symbol for numbered label
00219     /// (used for "1:" definitions).
00220     MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal);
00221 
00222     /// Create and return a directional local symbol for numbered label (used
00223     /// for "1b" or 1f" references).
00224     MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
00225 
00226     /// GetOrCreateSymbol - Lookup the symbol inside with the specified
00227     /// @p Name.  If it exists, return it.  If not, create a forward
00228     /// reference and return it.
00229     ///
00230     /// @param Name - The symbol name, which must be unique across all symbols.
00231     MCSymbol *GetOrCreateSymbol(StringRef Name);
00232     MCSymbol *GetOrCreateSymbol(const Twine &Name);
00233 
00234     /// LookupSymbol - Get the symbol for \p Name, or null.
00235     MCSymbol *LookupSymbol(StringRef Name) const;
00236     MCSymbol *LookupSymbol(const Twine &Name) const;
00237 
00238     /// getSymbols - Get a reference for the symbol table for clients that
00239     /// want to, for example, iterate over all symbols. 'const' because we
00240     /// still want any modifications to the table itself to use the MCContext
00241     /// APIs.
00242     const SymbolTable &getSymbols() const {
00243       return Symbols;
00244     }
00245 
00246     /// @}
00247 
00248     /// @name Section Management
00249     /// @{
00250 
00251     /// getMachOSection - Return the MCSection for the specified mach-o section.
00252     /// This requires the operands to be valid.
00253     const MCSectionMachO *getMachOSection(StringRef Segment,
00254                                           StringRef Section,
00255                                           unsigned TypeAndAttributes,
00256                                           unsigned Reserved2,
00257                                           SectionKind K);
00258     const MCSectionMachO *getMachOSection(StringRef Segment,
00259                                           StringRef Section,
00260                                           unsigned TypeAndAttributes,
00261                                           SectionKind K) {
00262       return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
00263     }
00264 
00265     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
00266                                       unsigned Flags, SectionKind Kind);
00267 
00268     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
00269                                       unsigned Flags, SectionKind Kind,
00270                                       unsigned EntrySize, StringRef Group);
00271 
00272     void renameELFSection(const MCSectionELF *Section, StringRef Name);
00273 
00274     const MCSectionELF *CreateELFGroupSection();
00275 
00276     const MCSectionCOFF *getCOFFSection(StringRef Section,
00277                                         unsigned Characteristics,
00278                                         SectionKind Kind,
00279                                         StringRef COMDATSymName, int Selection);
00280 
00281     const MCSectionCOFF *getCOFFSection(StringRef Section,
00282                                         unsigned Characteristics,
00283                                         SectionKind Kind);
00284 
00285     const MCSectionCOFF *getCOFFSection(StringRef Section);
00286 
00287     /// Gets or creates a section equivalent to Sec that is associated with the
00288     /// section containing KeySym. For example, to create a debug info section
00289     /// associated with an inline function, pass the normal debug info section
00290     /// as Sec and the function symbol as KeySym.
00291     const MCSectionCOFF *getAssociativeCOFFSection(const MCSectionCOFF *Sec,
00292                                                    const MCSymbol *KeySym);
00293 
00294     /// @}
00295 
00296     /// @name Dwarf Management
00297     /// @{
00298 
00299     /// \brief Get the compilation directory for DW_AT_comp_dir
00300     /// This can be overridden by clients which want to control the reported
00301     /// compilation directory and have it be something other than the current
00302     /// working directory.
00303     /// Returns an empty string if the current directory cannot be determined.
00304     StringRef getCompilationDir() const { return CompilationDir; }
00305 
00306     /// \brief Set the compilation directory for DW_AT_comp_dir
00307     /// Override the default (CWD) compilation directory.
00308     void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
00309 
00310     /// \brief Get the main file name for use in error messages and debug
00311     /// info. This can be set to ensure we've got the correct file name
00312     /// after preprocessing or for -save-temps.
00313     const std::string &getMainFileName() const { return MainFileName; }
00314 
00315     /// \brief Set the main file name and override the default.
00316     void setMainFileName(StringRef S) { MainFileName = S; }
00317 
00318     /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
00319     unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
00320                           unsigned FileNumber, unsigned CUID);
00321 
00322     bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
00323 
00324     const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
00325       return MCDwarfLineTablesCUMap;
00326     }
00327 
00328     MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
00329       return MCDwarfLineTablesCUMap[CUID];
00330     }
00331 
00332     const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
00333       auto I = MCDwarfLineTablesCUMap.find(CUID);
00334       assert(I != MCDwarfLineTablesCUMap.end());
00335       return I->second;
00336     }
00337 
00338     const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
00339       return getMCDwarfLineTable(CUID).getMCDwarfFiles();
00340     }
00341     const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
00342       return getMCDwarfLineTable(CUID).getMCDwarfDirs();
00343     }
00344 
00345     bool hasMCLineSections() const {
00346       for (const auto &Table : MCDwarfLineTablesCUMap)
00347         if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
00348           return true;
00349       return false;
00350     }
00351     unsigned getDwarfCompileUnitID() {
00352       return DwarfCompileUnitID;
00353     }
00354     void setDwarfCompileUnitID(unsigned CUIndex) {
00355       DwarfCompileUnitID = CUIndex;
00356     }
00357     void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
00358       getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
00359     }
00360 
00361     /// setCurrentDwarfLoc - saves the information from the currently parsed
00362     /// dwarf .loc directive and sets DwarfLocSeen.  When the next instruction
00363     /// is assembled an entry in the line number table with this information and
00364     /// the address of the instruction will be created.
00365     void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
00366                             unsigned Flags, unsigned Isa,
00367                             unsigned Discriminator) {
00368       CurrentDwarfLoc.setFileNum(FileNum);
00369       CurrentDwarfLoc.setLine(Line);
00370       CurrentDwarfLoc.setColumn(Column);
00371       CurrentDwarfLoc.setFlags(Flags);
00372       CurrentDwarfLoc.setIsa(Isa);
00373       CurrentDwarfLoc.setDiscriminator(Discriminator);
00374       DwarfLocSeen = true;
00375     }
00376     void ClearDwarfLocSeen() { DwarfLocSeen = false; }
00377 
00378     bool getDwarfLocSeen() { return DwarfLocSeen; }
00379     const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
00380 
00381     bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
00382     void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
00383     unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
00384     void setGenDwarfFileNumber(unsigned FileNumber) {
00385       GenDwarfFileNumber = FileNumber;
00386     }
00387     MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> > &
00388     getGenDwarfSectionSyms() {
00389       return SectionStartEndSyms;
00390     }
00391     std::pair<MapVector<const MCSection *,
00392                         std::pair<MCSymbol *, MCSymbol *> >::iterator,
00393               bool>
00394     addGenDwarfSection(const MCSection *Sec) {
00395       return SectionStartEndSyms.insert(
00396           std::make_pair(Sec, std::make_pair(nullptr, nullptr)));
00397     }
00398     void finalizeDwarfSections(MCStreamer &MCOS);
00399     const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
00400       return MCGenDwarfLabelEntries;
00401     }
00402     void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
00403       MCGenDwarfLabelEntries.push_back(E);
00404     }
00405 
00406     void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
00407     StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
00408 
00409     void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
00410     StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
00411 
00412     void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
00413     uint16_t getDwarfVersion() const { return DwarfVersion; }
00414 
00415     /// @}
00416 
00417     char *getSecureLogFile() { return SecureLogFile; }
00418     raw_ostream *getSecureLog() { return SecureLog; }
00419     bool getSecureLogUsed() { return SecureLogUsed; }
00420     void setSecureLog(raw_ostream *Value) {
00421       SecureLog = Value;
00422     }
00423     void setSecureLogUsed(bool Value) {
00424       SecureLogUsed = Value;
00425     }
00426 
00427     void *Allocate(unsigned Size, unsigned Align = 8) {
00428       return Allocator.Allocate(Size, Align);
00429     }
00430     void Deallocate(void *Ptr) {
00431     }
00432 
00433     // Unrecoverable error has occurred. Display the best diagnostic we can
00434     // and bail via exit(1). For now, most MC backend errors are unrecoverable.
00435     // FIXME: We should really do something about that.
00436     LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const;
00437   };
00438 
00439 } // end namespace llvm
00440 
00441 // operator new and delete aren't allowed inside namespaces.
00442 // The throw specifications are mandated by the standard.
00443 /// @brief Placement new for using the MCContext's allocator.
00444 ///
00445 /// This placement form of operator new uses the MCContext's allocator for
00446 /// obtaining memory. It is a non-throwing new, which means that it returns
00447 /// null on error. (If that is what the allocator does. The current does, so if
00448 /// this ever changes, this operator will have to be changed, too.)
00449 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
00450 /// @code
00451 /// // Default alignment (16)
00452 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
00453 /// // Specific alignment
00454 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
00455 /// @endcode
00456 /// Please note that you cannot use delete on the pointer; it must be
00457 /// deallocated using an explicit destructor call followed by
00458 /// @c Context.Deallocate(Ptr).
00459 ///
00460 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
00461 /// @param C The MCContext that provides the allocator.
00462 /// @param Alignment The alignment of the allocated memory (if the underlying
00463 ///                  allocator supports it).
00464 /// @return The allocated memory. Could be NULL.
00465 inline void *operator new(size_t Bytes, llvm::MCContext &C,
00466                           size_t Alignment = 16) throw () {
00467   return C.Allocate(Bytes, Alignment);
00468 }
00469 /// @brief Placement delete companion to the new above.
00470 ///
00471 /// This operator is just a companion to the new above. There is no way of
00472 /// invoking it directly; see the new operator for more details. This operator
00473 /// is called implicitly by the compiler if a placement new expression using
00474 /// the MCContext throws in the object constructor.
00475 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
00476               throw () {
00477   C.Deallocate(Ptr);
00478 }
00479 
00480 /// This placement form of operator new[] uses the MCContext's allocator for
00481 /// obtaining memory. It is a non-throwing new[], which means that it returns
00482 /// null on error.
00483 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
00484 /// @code
00485 /// // Default alignment (16)
00486 /// char *data = new (Context) char[10];
00487 /// // Specific alignment
00488 /// char *data = new (Context, 8) char[10];
00489 /// @endcode
00490 /// Please note that you cannot use delete on the pointer; it must be
00491 /// deallocated using an explicit destructor call followed by
00492 /// @c Context.Deallocate(Ptr).
00493 ///
00494 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
00495 /// @param C The MCContext that provides the allocator.
00496 /// @param Alignment The alignment of the allocated memory (if the underlying
00497 ///                  allocator supports it).
00498 /// @return The allocated memory. Could be NULL.
00499 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
00500                             size_t Alignment = 16) throw () {
00501   return C.Allocate(Bytes, Alignment);
00502 }
00503 
00504 /// @brief Placement delete[] companion to the new[] above.
00505 ///
00506 /// This operator is just a companion to the new[] above. There is no way of
00507 /// invoking it directly; see the new[] operator for more details. This operator
00508 /// is called implicitly by the compiler if a placement new[] expression using
00509 /// the MCContext throws in the object constructor.
00510 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {
00511   C.Deallocate(Ptr);
00512 }
00513 
00514 #endif