287311032f22bf4bdc85fd6ed2110da97bea23f6
[oota-llvm.git] / include / llvm / Bitcode / ReaderWriter.h
1 //===-- llvm/Bitcode/ReaderWriter.h - Bitcode reader/writers ----*- 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 // This header defines interfaces to read and write LLVM bitcode files/streams.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_BITCODE_READERWRITER_H
15 #define LLVM_BITCODE_READERWRITER_H
16
17 #include "llvm/Support/ErrorOr.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include <memory>
20 #include <string>
21
22 namespace llvm {
23   class BitstreamWriter;
24   class DataStreamer;
25   class LLVMContext;
26   class Module;
27   class ModulePass;
28   class raw_ostream;
29
30   /// Read the header of the specified bitcode buffer and prepare for lazy
31   /// deserialization of function bodies.  If successful, this takes ownership
32   /// of 'buffer. On error, this *does not* take ownership of Buffer.
33   ErrorOr<Module *> getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &Buffer,
34                                          LLVMContext &Context);
35
36   /// getStreamedBitcodeModule - Read the header of the specified stream
37   /// and prepare for lazy deserialization and streaming of function bodies.
38   /// On error, this returns null, and fills in *ErrMsg with an error
39   /// description if ErrMsg is non-null.
40   Module *getStreamedBitcodeModule(const std::string &name,
41                                    DataStreamer *streamer,
42                                    LLVMContext &Context,
43                                    std::string *ErrMsg = nullptr);
44
45   /// Read the header of the specified bitcode buffer and extract just the
46   /// triple information. If successful, this returns a string. On error, this
47   /// returns "".
48   std::string getBitcodeTargetTriple(MemoryBufferRef Buffer,
49                                      LLVMContext &Context);
50
51   /// Read the specified bitcode file, returning the module.
52   ErrorOr<Module *> parseBitcodeFile(MemoryBufferRef Buffer,
53                                      LLVMContext &Context);
54
55   /// WriteBitcodeToFile - Write the specified module to the specified
56   /// raw output stream.  For streams where it matters, the given stream
57   /// should be in "binary" mode.
58   void WriteBitcodeToFile(const Module *M, raw_ostream &Out);
59
60
61   /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
62   /// for an LLVM IR bitcode wrapper.
63   ///
64   inline bool isBitcodeWrapper(const unsigned char *BufPtr,
65                                const unsigned char *BufEnd) {
66     // See if you can find the hidden message in the magic bytes :-).
67     // (Hint: it's a little-endian encoding.)
68     return BufPtr != BufEnd &&
69            BufPtr[0] == 0xDE &&
70            BufPtr[1] == 0xC0 &&
71            BufPtr[2] == 0x17 &&
72            BufPtr[3] == 0x0B;
73   }
74
75   /// isRawBitcode - Return true if the given bytes are the magic bytes for
76   /// raw LLVM IR bitcode (without a wrapper).
77   ///
78   inline bool isRawBitcode(const unsigned char *BufPtr,
79                            const unsigned char *BufEnd) {
80     // These bytes sort of have a hidden message, but it's not in
81     // little-endian this time, and it's a little redundant.
82     return BufPtr != BufEnd &&
83            BufPtr[0] == 'B' &&
84            BufPtr[1] == 'C' &&
85            BufPtr[2] == 0xc0 &&
86            BufPtr[3] == 0xde;
87   }
88
89   /// isBitcode - Return true if the given bytes are the magic bytes for
90   /// LLVM IR bitcode, either with or without a wrapper.
91   ///
92   inline bool isBitcode(const unsigned char *BufPtr,
93                         const unsigned char *BufEnd) {
94     return isBitcodeWrapper(BufPtr, BufEnd) ||
95            isRawBitcode(BufPtr, BufEnd);
96   }
97
98   /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
99   /// header for padding or other reasons.  The format of this header is:
100   ///
101   /// struct bc_header {
102   ///   uint32_t Magic;         // 0x0B17C0DE
103   ///   uint32_t Version;       // Version, currently always 0.
104   ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
105   ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
106   ///   ... potentially other gunk ...
107   /// };
108   ///
109   /// This function is called when we find a file with a matching magic number.
110   /// In this case, skip down to the subsection of the file that is actually a
111   /// BC file.
112   /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
113   /// contain the whole bitcode file.
114   inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
115                                        const unsigned char *&BufEnd,
116                                        bool VerifyBufferSize) {
117     enum {
118       KnownHeaderSize = 4*4,  // Size of header we read.
119       OffsetField = 2*4,      // Offset in bytes to Offset field.
120       SizeField = 3*4         // Offset in bytes to Size field.
121     };
122
123     // Must contain the header!
124     if (BufEnd-BufPtr < KnownHeaderSize) return true;
125
126     unsigned Offset = ( BufPtr[OffsetField  ]        |
127                        (BufPtr[OffsetField+1] << 8)  |
128                        (BufPtr[OffsetField+2] << 16) |
129                        (BufPtr[OffsetField+3] << 24));
130     unsigned Size   = ( BufPtr[SizeField    ]        |
131                        (BufPtr[SizeField  +1] << 8)  |
132                        (BufPtr[SizeField  +2] << 16) |
133                        (BufPtr[SizeField  +3] << 24));
134
135     // Verify that Offset+Size fits in the file.
136     if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr))
137       return true;
138     BufPtr += Offset;
139     BufEnd = BufPtr+Size;
140     return false;
141   }
142
143   const std::error_category &BitcodeErrorCategory();
144   enum class BitcodeError {
145     ConflictingMETADATA_KINDRecords,
146     CouldNotFindFunctionInStream,
147     ExpectedConstant,
148     InsufficientFunctionProtos,
149     InvalidBitcodeSignature,
150     InvalidBitcodeWrapperHeader,
151     InvalidConstantReference,
152     InvalidID, // A read identifier is not found in the table it should be in.
153     InvalidInstructionWithNoBB,
154     InvalidRecord, // A read record doesn't have the expected size or structure
155     InvalidTypeForValue, // Type read OK, but is invalid for its use
156     InvalidTYPETable,
157     InvalidType,    // We were unable to read a type
158     MalformedBlock, // We are unable to advance in the stream.
159     MalformedGlobalInitializerSet,
160     InvalidMultipleBlocks, // We found multiple blocks of a kind that should
161                            // have only one
162     NeverResolvedValueFoundInFunction,
163     NeverResolvedFunctionFromBlockAddress,
164     InvalidValue // Invalid version, inst number, attr number, etc
165   };
166   inline std::error_code make_error_code(BitcodeError E) {
167     return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
168   }
169
170 } // End llvm namespace
171
172 namespace std {
173 template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
174 }
175
176 #endif