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