LLVM API Documentation

ReaderWriter.h
Go to the documentation of this file.
00001 //===-- llvm/Bitcode/ReaderWriter.h - Bitcode reader/writers ----*- 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 // This header defines interfaces to read and write LLVM bitcode files/streams.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_BITCODE_READERWRITER_H
00015 #define LLVM_BITCODE_READERWRITER_H
00016 
00017 #include "llvm/Support/ErrorOr.h"
00018 #include "llvm/Support/MemoryBuffer.h"
00019 #include <memory>
00020 #include <string>
00021 
00022 namespace llvm {
00023   class BitstreamWriter;
00024   class DataStreamer;
00025   class LLVMContext;
00026   class Module;
00027   class ModulePass;
00028   class raw_ostream;
00029 
00030   /// Read the header of the specified bitcode buffer and prepare for lazy
00031   /// deserialization of function bodies.  If successful, this moves Buffer. On
00032   /// error, this *does not* move Buffer.
00033   ErrorOr<Module *> getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
00034                                          LLVMContext &Context);
00035 
00036   /// Read the header of the specified stream and prepare for lazy
00037   /// deserialization and streaming of function bodies.
00038   ErrorOr<std::unique_ptr<Module>>
00039   getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
00040                            LLVMContext &Context);
00041 
00042   /// Read the header of the specified bitcode buffer and extract just the
00043   /// triple information. If successful, this returns a string. On error, this
00044   /// returns "".
00045   std::string getBitcodeTargetTriple(MemoryBufferRef Buffer,
00046                                      LLVMContext &Context);
00047 
00048   /// Read the specified bitcode file, returning the module.
00049   ErrorOr<Module *> parseBitcodeFile(MemoryBufferRef Buffer,
00050                                      LLVMContext &Context);
00051 
00052   /// WriteBitcodeToFile - Write the specified module to the specified
00053   /// raw output stream.  For streams where it matters, the given stream
00054   /// should be in "binary" mode.
00055   void WriteBitcodeToFile(const Module *M, raw_ostream &Out);
00056 
00057 
00058   /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
00059   /// for an LLVM IR bitcode wrapper.
00060   ///
00061   inline bool isBitcodeWrapper(const unsigned char *BufPtr,
00062                                const unsigned char *BufEnd) {
00063     // See if you can find the hidden message in the magic bytes :-).
00064     // (Hint: it's a little-endian encoding.)
00065     return BufPtr != BufEnd &&
00066            BufPtr[0] == 0xDE &&
00067            BufPtr[1] == 0xC0 &&
00068            BufPtr[2] == 0x17 &&
00069            BufPtr[3] == 0x0B;
00070   }
00071 
00072   /// isRawBitcode - Return true if the given bytes are the magic bytes for
00073   /// raw LLVM IR bitcode (without a wrapper).
00074   ///
00075   inline bool isRawBitcode(const unsigned char *BufPtr,
00076                            const unsigned char *BufEnd) {
00077     // These bytes sort of have a hidden message, but it's not in
00078     // little-endian this time, and it's a little redundant.
00079     return BufPtr != BufEnd &&
00080            BufPtr[0] == 'B' &&
00081            BufPtr[1] == 'C' &&
00082            BufPtr[2] == 0xc0 &&
00083            BufPtr[3] == 0xde;
00084   }
00085 
00086   /// isBitcode - Return true if the given bytes are the magic bytes for
00087   /// LLVM IR bitcode, either with or without a wrapper.
00088   ///
00089   inline bool isBitcode(const unsigned char *BufPtr,
00090                         const unsigned char *BufEnd) {
00091     return isBitcodeWrapper(BufPtr, BufEnd) ||
00092            isRawBitcode(BufPtr, BufEnd);
00093   }
00094 
00095   /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
00096   /// header for padding or other reasons.  The format of this header is:
00097   ///
00098   /// struct bc_header {
00099   ///   uint32_t Magic;         // 0x0B17C0DE
00100   ///   uint32_t Version;       // Version, currently always 0.
00101   ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
00102   ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
00103   ///   ... potentially other gunk ...
00104   /// };
00105   ///
00106   /// This function is called when we find a file with a matching magic number.
00107   /// In this case, skip down to the subsection of the file that is actually a
00108   /// BC file.
00109   /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
00110   /// contain the whole bitcode file.
00111   inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
00112                                        const unsigned char *&BufEnd,
00113                                        bool VerifyBufferSize) {
00114     enum {
00115       KnownHeaderSize = 4*4,  // Size of header we read.
00116       OffsetField = 2*4,      // Offset in bytes to Offset field.
00117       SizeField = 3*4         // Offset in bytes to Size field.
00118     };
00119 
00120     // Must contain the header!
00121     if (BufEnd-BufPtr < KnownHeaderSize) return true;
00122 
00123     unsigned Offset = ( BufPtr[OffsetField  ]        |
00124                        (BufPtr[OffsetField+1] << 8)  |
00125                        (BufPtr[OffsetField+2] << 16) |
00126                        (BufPtr[OffsetField+3] << 24));
00127     unsigned Size   = ( BufPtr[SizeField    ]        |
00128                        (BufPtr[SizeField  +1] << 8)  |
00129                        (BufPtr[SizeField  +2] << 16) |
00130                        (BufPtr[SizeField  +3] << 24));
00131 
00132     // Verify that Offset+Size fits in the file.
00133     if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr))
00134       return true;
00135     BufPtr += Offset;
00136     BufEnd = BufPtr+Size;
00137     return false;
00138   }
00139 
00140   const std::error_category &BitcodeErrorCategory();
00141   enum class BitcodeError {
00142     ConflictingMETADATA_KINDRecords,
00143     CouldNotFindFunctionInStream,
00144     ExpectedConstant,
00145     InsufficientFunctionProtos,
00146     InvalidBitcodeSignature,
00147     InvalidBitcodeWrapperHeader,
00148     InvalidConstantReference,
00149     InvalidID, // A read identifier is not found in the table it should be in.
00150     InvalidInstructionWithNoBB,
00151     InvalidRecord, // A read record doesn't have the expected size or structure
00152     InvalidTypeForValue, // Type read OK, but is invalid for its use
00153     InvalidTYPETable,
00154     InvalidType,    // We were unable to read a type
00155     MalformedBlock, // We are unable to advance in the stream.
00156     MalformedGlobalInitializerSet,
00157     InvalidMultipleBlocks, // We found multiple blocks of a kind that should
00158                            // have only one
00159     NeverResolvedValueFoundInFunction,
00160     NeverResolvedFunctionFromBlockAddress,
00161     InvalidValue // Invalid version, inst number, attr number, etc
00162   };
00163   inline std::error_code make_error_code(BitcodeError E) {
00164     return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
00165   }
00166 
00167 } // End llvm namespace
00168 
00169 namespace std {
00170 template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
00171 }
00172 
00173 #endif