LLVM 23.0.0git
BitcodeReader.h
Go to the documentation of this file.
1//===- llvm/Bitcode/BitcodeReader.h - Bitcode reader ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header defines interfaces to read LLVM bitcode files/streams.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_BITCODE_BITCODEREADER_H
14#define LLVM_BITCODE_BITCODEREADER_H
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/StringRef.h"
19#include "llvm/IR/GlobalValue.h"
21#include "llvm/Support/Endian.h"
22#include "llvm/Support/Error.h"
25#include <cstdint>
26#include <memory>
27#include <optional>
28#include <string>
29#include <system_error>
30#include <vector>
31namespace llvm {
32
33class LLVMContext;
34class Module;
35class MemoryBuffer;
36class Metadata;
38class Type;
39class Value;
40struct ValueInfo;
41
42// Callback to override the data layout string of an imported bitcode module.
43// The first argument is the target triple, the second argument the data layout
44// string from the input, or a default string. It will be used if the callback
45// returns std::nullopt.
46typedef std::function<std::optional<std::string>(StringRef, StringRef)>
48
49typedef std::function<Type *(unsigned)> GetTypeByIDTy;
50
51typedef std::function<unsigned(unsigned, unsigned)> GetContainedTypeIDTy;
52
53typedef std::function<void(Value *, unsigned, GetTypeByIDTy,
56
57typedef std::function<void(Metadata **, unsigned, GetTypeByIDTy,
60
61// These functions are for converting Expected/Error values to
62// ErrorOr/std::error_code for compatibility with legacy clients. FIXME:
63// Remove these functions once no longer needed by the C and libLTO APIs.
64
66 Error Err);
67
68template <typename T>
70 if (!Val)
72 return std::move(*Val);
73}
74
76 std::optional<DataLayoutCallbackFuncTy> DataLayout;
77 /// The ValueType callback is called for every function definition or
78 /// declaration and allows accessing the type information, also behind
79 /// pointers. This can be useful, when the opaque pointer upgrade cleans all
80 /// type information behind pointers.
81 /// The second argument to ValueTypeCallback is the type ID of the
82 /// function, the two passed functions can be used to extract type
83 /// information.
84 std::optional<ValueTypeCallbackTy> ValueType;
85 /// The MDType callback is called for every value in metadata.
86 std::optional<MDTypeCallbackTy> MDType;
87
88 /// If true, do not auto-upgrade debug intrinsic calls (llvm.dbg.*) to
89 /// non-instruction debug records during bitcode read. This flag allows
90 /// direct manipulation of the old intrinsic-form debug info; beware that
91 /// LLVM does not support using these intrinsics any more. The caller is
92 /// responsible for performing the upgrade manually (e.g. via
93 /// Module::convertToNewDbgValues()).
95
96 ParserCallbacks() = default;
99};
100
101 struct BitcodeFileContents;
102
103 /// Basic information extracted from a bitcode module to be used for LTO.
110
111 /// Represents a module in a bitcode file.
112 class BitcodeModule {
113 // This covers the identification (if present) and module blocks.
114 ArrayRef<uint8_t> Buffer;
115 StringRef ModuleIdentifier;
116
117 // The string table used to interpret this module.
118 StringRef Strtab;
119
120 // The bitstream location of the IDENTIFICATION_BLOCK.
121 uint64_t IdentificationBit;
122
123 // The bitstream location of this module's MODULE_BLOCK.
124 uint64_t ModuleBit;
125
126 BitcodeModule(ArrayRef<uint8_t> Buffer, StringRef ModuleIdentifier,
127 uint64_t IdentificationBit, uint64_t ModuleBit)
128 : Buffer(Buffer), ModuleIdentifier(ModuleIdentifier),
129 IdentificationBit(IdentificationBit), ModuleBit(ModuleBit) {}
130
131 // Calls the ctor.
134
136 getModuleImpl(LLVMContext &Context, bool MaterializeAll,
137 bool ShouldLazyLoadMetadata, bool IsImporting,
138 ParserCallbacks Callbacks = {});
139
140 public:
142 return StringRef((const char *)Buffer.begin(), Buffer.size());
143 }
144
145 StringRef getStrtab() const { return Strtab; }
146
147 StringRef getModuleIdentifier() const { return ModuleIdentifier; }
148
149 // Assign a new module identifier to this bitcode module.
151 ModuleIdentifier = ModuleId;
152 }
153
154 /// Read the bitcode module and prepare for lazy deserialization of function
155 /// bodies. If ShouldLazyLoadMetadata is true, lazily load metadata as well.
156 /// If IsImporting is true, this module is being parsed for ThinLTO
157 /// importing into another module.
159 getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
160 bool IsImporting, ParserCallbacks Callbacks = {});
161
162 /// Read the entire bitcode module and return it.
163 LLVM_ABI Expected<std::unique_ptr<Module>>
164 parseModule(LLVMContext &Context, ParserCallbacks Callbacks = {});
165
166 /// Returns information about the module to be used for LTO: whether to
167 /// compile with ThinLTO, and whether it has a summary.
168 LLVM_ABI Expected<BitcodeLTOInfo> getLTOInfo();
169
170 /// Parse the specified bitcode buffer, returning the module summary index.
171 LLVM_ABI Expected<std::unique_ptr<ModuleSummaryIndex>> getSummary();
172
173 /// Parse the specified bitcode buffer and merge its module summary index
174 /// into CombinedIndex.
176 readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
177 std::function<bool(StringRef)> IsPrevailing = nullptr,
178 std::function<void(ValueInfo)> OnValueInfo = nullptr);
179 };
180
182 std::vector<BitcodeModule> Mods;
184 };
185
186 /// Returns the contents of a bitcode file. This includes the raw contents of
187 /// the symbol table embedded in the bitcode file. Clients which require a
188 /// symbol table should prefer to use irsymtab::read instead of this function
189 /// because it creates a reader for the irsymtab and handles upgrading bitcode
190 /// files without a symbol table or with an old symbol table.
193
194 /// Returns a list of modules in the specified bitcode buffer.
197
198 /// Read the header of the specified bitcode buffer and prepare for lazy
199 /// deserialization of function bodies. If ShouldLazyLoadMetadata is true,
200 /// lazily load metadata as well. If IsImporting is true, this module is
201 /// being parsed for ThinLTO importing into another module.
204 bool ShouldLazyLoadMetadata = false,
205 bool IsImporting = false,
206 ParserCallbacks Callbacks = {});
207
208 /// Like getLazyBitcodeModule, except that the module takes ownership of
209 /// the memory buffer if successful. If successful, this moves Buffer. On
210 /// error, this *does not* move Buffer. If IsImporting is true, this module is
211 /// being parsed for ThinLTO importing into another module.
212 LLVM_ABI Expected<std::unique_ptr<Module>> getOwningLazyBitcodeModule(
213 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
214 bool ShouldLazyLoadMetadata = false, bool IsImporting = false,
215 ParserCallbacks Callbacks = {});
216
217 /// Read the header of the specified bitcode buffer and extract just the
218 /// triple information. If successful, this returns a string. On error, this
219 /// returns "".
221
222 /// Return true if \p Buffer contains a bitcode file with ObjC code (category
223 /// or class) in it.
226
227 /// Read the header of the specified bitcode buffer and extract just the
228 /// producer string information. If successful, this returns a string. On
229 /// error, this returns "".
232
233 /// Read the specified bitcode file, returning the module.
236 ParserCallbacks Callbacks = {});
237
238 /// Returns LTO information for the specified bitcode file.
240
241 /// Parse the specified bitcode buffer, returning the module summary index.
244
245 /// Parse the specified bitcode buffer and merge the index into CombinedIndex.
247 ModuleSummaryIndex &CombinedIndex);
248
249 /// Parse the module summary index out of an IR file and return the module
250 /// summary index object if found, or an empty summary if not. If Path refers
251 /// to an empty file and IgnoreEmptyThinLTOIndexFile is true, then
252 /// this function will return nullptr.
255 bool IgnoreEmptyThinLTOIndexFile = false);
256
257 /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
258 /// for an LLVM IR bitcode wrapper.
259 inline bool isBitcodeWrapper(const unsigned char *BufPtr,
260 const unsigned char *BufEnd) {
261 // See if you can find the hidden message in the magic bytes :-).
262 // (Hint: it's a little-endian encoding.)
263 return BufPtr != BufEnd &&
264 BufPtr[0] == 0xDE &&
265 BufPtr[1] == 0xC0 &&
266 BufPtr[2] == 0x17 &&
267 BufPtr[3] == 0x0B;
268 }
269
270 /// isRawBitcode - Return true if the given bytes are the magic bytes for
271 /// raw LLVM IR bitcode (without a wrapper).
272 inline bool isRawBitcode(const unsigned char *BufPtr,
273 const unsigned char *BufEnd) {
274 // These bytes sort of have a hidden message, but it's not in
275 // little-endian this time, and it's a little redundant.
276 return BufPtr != BufEnd &&
277 BufPtr[0] == 'B' &&
278 BufPtr[1] == 'C' &&
279 BufPtr[2] == 0xc0 &&
280 BufPtr[3] == 0xde;
281 }
282
283 /// isBitcode - Return true if the given bytes are the magic bytes for
284 /// LLVM IR bitcode, either with or without a wrapper.
285 inline bool isBitcode(const unsigned char *BufPtr,
286 const unsigned char *BufEnd) {
287 return isBitcodeWrapper(BufPtr, BufEnd) ||
288 isRawBitcode(BufPtr, BufEnd);
289 }
290
291 /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
292 /// header for padding or other reasons. The format of this header is:
293 ///
294 /// struct bc_header {
295 /// uint32_t Magic; // 0x0B17C0DE
296 /// uint32_t Version; // Version, currently always 0.
297 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
298 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
299 /// ... potentially other gunk ...
300 /// };
301 ///
302 /// This function is called when we find a file with a matching magic number.
303 /// In this case, skip down to the subsection of the file that is actually a
304 /// BC file.
305 /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
306 /// contain the whole bitcode file.
307 inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
308 const unsigned char *&BufEnd,
309 bool VerifyBufferSize) {
310 // Must contain the offset and size field!
311 if (unsigned(BufEnd - BufPtr) < BWH_SizeField + 4)
312 return true;
313
315 unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
316 uint64_t BitcodeOffsetEnd = (uint64_t)Offset + (uint64_t)Size;
317
318 // Verify that Offset+Size fits in the file.
319 if (VerifyBufferSize && BitcodeOffsetEnd > uint64_t(BufEnd-BufPtr))
320 return true;
321 BufPtr += Offset;
322 BufEnd = BufPtr+Size;
323 return false;
324 }
325
326 LLVM_ABI APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits);
327
328 LLVM_ABI const std::error_category &BitcodeErrorCategory();
329 enum class BitcodeError { CorruptedBitcode = 1 };
330 inline std::error_code make_error_code(BitcodeError E) {
331 return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
332 }
333
334} // end namespace llvm
335
336namespace std {
337
338template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
339
340} // end namespace std
341
342#endif // LLVM_BITCODE_BITCODEREADER_H
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
Provides ErrorOr<T> smart pointer.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
void setModuleIdentifier(llvm::StringRef ModuleId)
LLVM_ABI friend Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
StringRef getModuleIdentifier() const
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
StringRef getBuffer() const
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
StringRef getStrtab() const
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(StringRef)> IsPrevailing=nullptr, std::function< void(ValueInfo)> OnValueInfo=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Represents either an error or a value T.
Definition ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Root of the metadata hierarchy.
Definition Metadata.h:64
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
uint32_t read32le(const void *P)
Definition Endian.h:432
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:573
LLVM_ABI const std::error_category & BitcodeErrorCategory()
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
std::error_code make_error_code(BitcodeError E)
std::function< Type *(unsigned)> GetTypeByIDTy
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
std::function< unsigned(unsigned, unsigned)> GetContainedTypeIDTy
@ BWH_OffsetField
@ BWH_SizeField
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
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 ...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
std::function< void(Metadata **, unsigned, GetTypeByIDTy, GetContainedTypeIDTy)> MDTypeCallbackTy
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
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...
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.
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
std::function< void(Value *, unsigned, GetTypeByIDTy, GetContainedTypeIDTy)> ValueTypeCallbackTy
std::function< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackFuncTy
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,...
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
LLVM_ABI 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,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:860
std::vector< BitcodeModule > Mods
Basic information extracted from a bitcode module to be used for LTO.
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
ParserCallbacks(DataLayoutCallbackFuncTy DataLayout)
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
bool SkipDebugIntrinsicUpgrade
If true, do not auto-upgrade debug intrinsic calls (llvm.dbg.
Struct that holds a reference to a particular GUID in a global value summary.