81103b82582115b6c20ce893f1fd705f07bf5ec7
[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/IR/DiagnosticInfo.h"
18 #include "llvm/Support/ErrorOr.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include <memory>
21 #include <string>
22
23 namespace llvm {
24   class BitstreamWriter;
25   class DataStreamer;
26   class LLVMContext;
27   class Module;
28   class ModulePass;
29   class raw_ostream;
30
31   /// Read the header of the specified bitcode buffer and prepare for lazy
32   /// deserialization of function bodies. If ShouldLazyLoadMetadata is true,
33   /// lazily load metadata as well. If successful, this moves Buffer. On
34   /// error, this *does not* move Buffer.
35   ErrorOr<std::unique_ptr<Module>>
36   getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
37                        LLVMContext &Context,
38                        DiagnosticHandlerFunction DiagnosticHandler = nullptr,
39                        bool ShouldLazyLoadMetadata = false);
40
41   /// Read the header of the specified stream and prepare for lazy
42   /// deserialization and streaming of function bodies.
43   ErrorOr<std::unique_ptr<Module>> getStreamedBitcodeModule(
44       StringRef Name, std::unique_ptr<DataStreamer> Streamer,
45       LLVMContext &Context,
46       DiagnosticHandlerFunction DiagnosticHandler = nullptr);
47
48   /// Read the header of the specified bitcode buffer and extract just the
49   /// triple information. If successful, this returns a string. On error, this
50   /// returns "".
51   std::string
52   getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
53                          DiagnosticHandlerFunction DiagnosticHandler = nullptr);
54
55   /// Read the specified bitcode file, returning the module.
56   ErrorOr<std::unique_ptr<Module>>
57   parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
58                    DiagnosticHandlerFunction DiagnosticHandler = nullptr);
59
60   /// \brief Write the specified module to the specified raw output stream.
61   ///
62   /// For streams where it matters, the given stream should be in "binary"
63   /// mode.
64   ///
65   /// If \c ShouldPreserveUseListOrder, encode the use-list order for each \a
66   /// Value in \c M.  These will be reconstructed exactly when \a M is
67   /// deserialized.
68   void WriteBitcodeToFile(const Module *M, raw_ostream &Out,
69                           bool ShouldPreserveUseListOrder = false);
70
71   /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
72   /// for an LLVM IR bitcode wrapper.
73   ///
74   inline bool isBitcodeWrapper(const unsigned char *BufPtr,
75                                const unsigned char *BufEnd) {
76     // See if you can find the hidden message in the magic bytes :-).
77     // (Hint: it's a little-endian encoding.)
78     return BufPtr != BufEnd &&
79            BufPtr[0] == 0xDE &&
80            BufPtr[1] == 0xC0 &&
81            BufPtr[2] == 0x17 &&
82            BufPtr[3] == 0x0B;
83   }
84
85   /// isRawBitcode - Return true if the given bytes are the magic bytes for
86   /// raw LLVM IR bitcode (without a wrapper).
87   ///
88   inline bool isRawBitcode(const unsigned char *BufPtr,
89                            const unsigned char *BufEnd) {
90     // These bytes sort of have a hidden message, but it's not in
91     // little-endian this time, and it's a little redundant.
92     return BufPtr != BufEnd &&
93            BufPtr[0] == 'B' &&
94            BufPtr[1] == 'C' &&
95            BufPtr[2] == 0xc0 &&
96            BufPtr[3] == 0xde;
97   }
98
99   /// isBitcode - Return true if the given bytes are the magic bytes for
100   /// LLVM IR bitcode, either with or without a wrapper.
101   ///
102   inline bool isBitcode(const unsigned char *BufPtr,
103                         const unsigned char *BufEnd) {
104     return isBitcodeWrapper(BufPtr, BufEnd) ||
105            isRawBitcode(BufPtr, BufEnd);
106   }
107
108   /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
109   /// header for padding or other reasons.  The format of this header is:
110   ///
111   /// struct bc_header {
112   ///   uint32_t Magic;         // 0x0B17C0DE
113   ///   uint32_t Version;       // Version, currently always 0.
114   ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
115   ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
116   ///   ... potentially other gunk ...
117   /// };
118   ///
119   /// This function is called when we find a file with a matching magic number.
120   /// In this case, skip down to the subsection of the file that is actually a
121   /// BC file.
122   /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
123   /// contain the whole bitcode file.
124   inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
125                                        const unsigned char *&BufEnd,
126                                        bool VerifyBufferSize) {
127     enum {
128       KnownHeaderSize = 4*4,  // Size of header we read.
129       OffsetField = 2*4,      // Offset in bytes to Offset field.
130       SizeField = 3*4         // Offset in bytes to Size field.
131     };
132
133     // Must contain the header!
134     if (BufEnd-BufPtr < KnownHeaderSize) return true;
135
136     unsigned Offset = ( BufPtr[OffsetField  ]        |
137                        (BufPtr[OffsetField+1] << 8)  |
138                        (BufPtr[OffsetField+2] << 16) |
139                        (BufPtr[OffsetField+3] << 24));
140     unsigned Size   = ( BufPtr[SizeField    ]        |
141                        (BufPtr[SizeField  +1] << 8)  |
142                        (BufPtr[SizeField  +2] << 16) |
143                        (BufPtr[SizeField  +3] << 24));
144
145     // Verify that Offset+Size fits in the file.
146     if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr))
147       return true;
148     BufPtr += Offset;
149     BufEnd = BufPtr+Size;
150     return false;
151   }
152
153   const std::error_category &BitcodeErrorCategory();
154   enum class BitcodeError { InvalidBitcodeSignature, CorruptedBitcode };
155   inline std::error_code make_error_code(BitcodeError E) {
156     return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
157   }
158
159   class BitcodeDiagnosticInfo : public DiagnosticInfo {
160     const Twine &Msg;
161     std::error_code EC;
162
163   public:
164     BitcodeDiagnosticInfo(std::error_code EC, DiagnosticSeverity Severity,
165                           const Twine &Msg);
166     void print(DiagnosticPrinter &DP) const override;
167     std::error_code getError() const { return EC; };
168
169     static bool classof(const DiagnosticInfo *DI) {
170       return DI->getKind() == DK_Bitcode;
171     }
172   };
173
174 } // End llvm namespace
175
176 namespace std {
177 template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
178 }
179
180 #endif