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