LLVM  5.0.0
BitcodeReader.h
Go to the documentation of this file.
1 //===-- llvm/Bitcode/BitcodeReader.h - Bitcode reader ----*- 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 LLVM bitcode files/streams.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_BITCODE_BITCODEREADER_H
15 #define LLVM_BITCODE_BITCODEREADER_H
16 
17 #include "llvm/Bitcode/BitCodes.h"
18 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/Error.h"
22 #include "llvm/Support/ErrorOr.h"
24 #include <memory>
25 
26 namespace llvm {
27  class LLVMContext;
28  class Module;
29 
30  // These functions are for converting Expected/Error values to
31  // ErrorOr/std::error_code for compatibility with legacy clients. FIXME:
32  // Remove these functions once no longer needed by the C and libLTO APIs.
33 
34  std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err);
35 
36  template <typename T>
38  if (!Val)
39  return errorToErrorCodeAndEmitErrors(Ctx, Val.takeError());
40  return std::move(*Val);
41  }
42 
43  struct BitcodeFileContents;
44 
45  /// Basic information extracted from a bitcode module to be used for LTO.
46  struct BitcodeLTOInfo {
47  bool IsThinLTO;
48  bool HasSummary;
49  };
50 
51  /// Represents a module in a bitcode file.
52  class BitcodeModule {
53  // This covers the identification (if present) and module blocks.
54  ArrayRef<uint8_t> Buffer;
55  StringRef ModuleIdentifier;
56 
57  // The string table used to interpret this module.
58  StringRef Strtab;
59 
60  // The bitstream location of the IDENTIFICATION_BLOCK.
61  uint64_t IdentificationBit;
62 
63  // The bitstream location of this module's MODULE_BLOCK.
64  uint64_t ModuleBit;
65 
66  BitcodeModule(ArrayRef<uint8_t> Buffer, StringRef ModuleIdentifier,
67  uint64_t IdentificationBit, uint64_t ModuleBit)
68  : Buffer(Buffer), ModuleIdentifier(ModuleIdentifier),
69  IdentificationBit(IdentificationBit), ModuleBit(ModuleBit) {}
70 
71  // Calls the ctor.
74 
76  bool MaterializeAll,
77  bool ShouldLazyLoadMetadata,
78  bool IsImporting);
79 
80  public:
81  StringRef getBuffer() const {
82  return StringRef((const char *)Buffer.begin(), Buffer.size());
83  }
84  StringRef getStrtab() const { return Strtab; }
85 
86  StringRef getModuleIdentifier() const { return ModuleIdentifier; }
87 
88  /// Read the bitcode module and prepare for lazy deserialization of function
89  /// bodies. If ShouldLazyLoadMetadata is true, lazily load metadata as well.
90  /// If IsImporting is true, this module is being parsed for ThinLTO
91  /// importing into another module.
93  bool ShouldLazyLoadMetadata,
94  bool IsImporting);
95 
96  /// Read the entire bitcode module and return it.
98 
99  /// Returns information about the module to be used for LTO: whether to
100  /// compile with ThinLTO, and whether it has a summary.
102 
103  /// Parse the specified bitcode buffer, returning the module summary index.
105 
106  /// Parse the specified bitcode buffer and merge its module summary index
107  /// into CombinedIndex.
108  Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
109  uint64_t ModuleId);
110  };
111 
113  std::vector<BitcodeModule> Mods;
115  };
116 
117  /// Returns the contents of a bitcode file. This includes the raw contents of
118  /// the symbol table embedded in the bitcode file. Clients which require a
119  /// symbol table should prefer to use irsymtab::read instead of this function
120  /// because it creates a reader for the irsymtab and handles upgrading bitcode
121  /// files without a symbol table or with an old symbol table.
123 
124  /// Returns a list of modules in the specified bitcode buffer.
127 
128  /// Read the header of the specified bitcode buffer and prepare for lazy
129  /// deserialization of function bodies. If ShouldLazyLoadMetadata is true,
130  /// lazily load metadata as well. If IsImporting is true, this module is
131  /// being parsed for ThinLTO importing into another module.
134  bool ShouldLazyLoadMetadata = false,
135  bool IsImporting = false);
136 
137  /// Like getLazyBitcodeModule, except that the module takes ownership of
138  /// the memory buffer if successful. If successful, this moves Buffer. On
139  /// error, this *does not* move Buffer. If IsImporting is true, this module is
140  /// being parsed for ThinLTO importing into another module.
142  std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
143  bool ShouldLazyLoadMetadata = false, bool IsImporting = false);
144 
145  /// Read the header of the specified bitcode buffer and extract just the
146  /// triple information. If successful, this returns a string. On error, this
147  /// returns "".
149 
150  /// Return true if \p Buffer contains a bitcode file with ObjC code (category
151  /// or class) in it.
153 
154  /// Read the header of the specified bitcode buffer and extract just the
155  /// producer string information. If successful, this returns a string. On
156  /// error, this returns "".
158 
159  /// Read the specified bitcode file, returning the module.
162 
163  /// Returns LTO information for the specified bitcode file.
165 
166  /// Parse the specified bitcode buffer, returning the module summary index.
169 
170  /// Parse the specified bitcode buffer and merge the index into CombinedIndex.
172  ModuleSummaryIndex &CombinedIndex,
173  uint64_t ModuleId);
174 
175  /// Parse the module summary index out of an IR file and return the module
176  /// summary index object if found, or an empty summary if not. If Path refers
177  /// to an empty file and IgnoreEmptyThinLTOIndexFile is true, then
178  /// this function will return nullptr.
181  bool IgnoreEmptyThinLTOIndexFile = false);
182 
183  /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
184  /// for an LLVM IR bitcode wrapper.
185  ///
186  inline bool isBitcodeWrapper(const unsigned char *BufPtr,
187  const unsigned char *BufEnd) {
188  // See if you can find the hidden message in the magic bytes :-).
189  // (Hint: it's a little-endian encoding.)
190  return BufPtr != BufEnd &&
191  BufPtr[0] == 0xDE &&
192  BufPtr[1] == 0xC0 &&
193  BufPtr[2] == 0x17 &&
194  BufPtr[3] == 0x0B;
195  }
196 
197  /// isRawBitcode - Return true if the given bytes are the magic bytes for
198  /// raw LLVM IR bitcode (without a wrapper).
199  ///
200  inline bool isRawBitcode(const unsigned char *BufPtr,
201  const unsigned char *BufEnd) {
202  // These bytes sort of have a hidden message, but it's not in
203  // little-endian this time, and it's a little redundant.
204  return BufPtr != BufEnd &&
205  BufPtr[0] == 'B' &&
206  BufPtr[1] == 'C' &&
207  BufPtr[2] == 0xc0 &&
208  BufPtr[3] == 0xde;
209  }
210 
211  /// isBitcode - Return true if the given bytes are the magic bytes for
212  /// LLVM IR bitcode, either with or without a wrapper.
213  ///
214  inline bool isBitcode(const unsigned char *BufPtr,
215  const unsigned char *BufEnd) {
216  return isBitcodeWrapper(BufPtr, BufEnd) ||
217  isRawBitcode(BufPtr, BufEnd);
218  }
219 
220  /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
221  /// header for padding or other reasons. The format of this header is:
222  ///
223  /// struct bc_header {
224  /// uint32_t Magic; // 0x0B17C0DE
225  /// uint32_t Version; // Version, currently always 0.
226  /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
227  /// uint32_t BitcodeSize; // Size of traditional bitcode file.
228  /// ... potentially other gunk ...
229  /// };
230  ///
231  /// This function is called when we find a file with a matching magic number.
232  /// In this case, skip down to the subsection of the file that is actually a
233  /// BC file.
234  /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
235  /// contain the whole bitcode file.
236  inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
237  const unsigned char *&BufEnd,
238  bool VerifyBufferSize) {
239  // Must contain the offset and size field!
240  if (unsigned(BufEnd - BufPtr) < BWH_SizeField + 4)
241  return true;
242 
243  unsigned Offset = support::endian::read32le(&BufPtr[BWH_OffsetField]);
244  unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
245  uint64_t BitcodeOffsetEnd = (uint64_t)Offset + (uint64_t)Size;
246 
247  // Verify that Offset+Size fits in the file.
248  if (VerifyBufferSize && BitcodeOffsetEnd > uint64_t(BufEnd-BufPtr))
249  return true;
250  BufPtr += Offset;
251  BufEnd = BufPtr+Size;
252  return false;
253  }
254 
256  enum class BitcodeError { CorruptedBitcode = 1 };
257  inline std::error_code make_error_code(BitcodeError E) {
258  return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
259  }
260 
261 } // End llvm namespace
262 
263 namespace std {
264 template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
265 }
266 
267 #endif
Represents either an error or a value T.
Definition: ErrorOr.h:69
LLVMContext & Context
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
StringRef getStrtab() const
Definition: BitcodeReader.h:84
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper...
Error takeError()
Take ownership of the stored error.
Definition: Error.h:764
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
Represents a module in a bitcode file.
Definition: BitcodeReader.h:52
Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO, and whether it has a summary.
std::error_code make_error_code(BitcodeError E)
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
static const unsigned BWH_OffsetField
Definition: BitCodes.h:30
Basic information extracted from a bitcode module to be used for LTO.
Definition: BitcodeReader.h:46
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static const unsigned BWH_SizeField
Definition: BitCodes.h:31
const std::error_category & BitcodeErrorCategory()
Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information...
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
static ManagedStatic< _object_error_category > error_category
Definition: Error.cpp:74
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex, uint64_t ModuleId)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
StringRef getBuffer() const
Definition: BitcodeReader.h:81
Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it...
#define E
Definition: LargeTest.cpp:27
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode, either with or without a wrapper.
bool isRawBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isRawBitcode - Return true if the given bytes are the magic bytes for raw LLVM IR bitcode (without a ...
StringRef getModuleIdentifier() const
Definition: BitcodeReader.h:86
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
Definition: BitcodeReader.h:37
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
uint32_t read32le(const void *P)
Definition: Endian.h:369
friend Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
Provides ErrorOr<T> smart pointer.
Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful...
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
std::vector< BitcodeModule > Mods