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