1 //===- BitcodeReader.h - Internal BitcodeReader impl ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #ifndef BITCODE_READER_H
15 #define BITCODE_READER_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/Bitcode/BitstreamReader.h"
19 #include "llvm/Bitcode/LLVMBitCodes.h"
20 #include "llvm/IR/Attributes.h"
21 #include "llvm/IR/GVMaterializer.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/IR/ValueHandle.h"
25 #include <system_error>
32 //===----------------------------------------------------------------------===//
33 // BitcodeReaderValueList Class
34 //===----------------------------------------------------------------------===//
36 class BitcodeReaderValueList {
37 std::vector<WeakVH> ValuePtrs;
39 /// ResolveConstants - As we resolve forward-referenced constants, we add
40 /// information about them to this vector. This allows us to resolve them in
41 /// bulk instead of resolving each reference at a time. See the code in
42 /// ResolveConstantForwardRefs for more information about this.
44 /// The key of this vector is the placeholder constant, the value is the slot
45 /// number that holds the resolved value.
46 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
47 ResolveConstantsTy ResolveConstants;
50 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
51 ~BitcodeReaderValueList() {
52 assert(ResolveConstants.empty() && "Constants not resolved?");
55 // vector compatibility methods
56 unsigned size() const { return ValuePtrs.size(); }
57 void resize(unsigned N) { ValuePtrs.resize(N); }
58 void push_back(Value *V) {
59 ValuePtrs.push_back(V);
63 assert(ResolveConstants.empty() && "Constants not resolved?");
67 Value *operator[](unsigned i) const {
68 assert(i < ValuePtrs.size());
72 Value *back() const { return ValuePtrs.back(); }
73 void pop_back() { ValuePtrs.pop_back(); }
74 bool empty() const { return ValuePtrs.empty(); }
75 void shrinkTo(unsigned N) {
76 assert(N <= size() && "Invalid shrinkTo request!");
80 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
81 Value *getValueFwdRef(unsigned Idx, Type *Ty);
83 void AssignValue(Value *V, unsigned Idx);
85 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
86 /// resolves any forward references.
87 void ResolveConstantForwardRefs();
91 //===----------------------------------------------------------------------===//
92 // BitcodeReaderMDValueList Class
93 //===----------------------------------------------------------------------===//
95 class BitcodeReaderMDValueList {
96 std::vector<WeakVH> MDValuePtrs;
100 BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
102 // vector compatibility methods
103 unsigned size() const { return MDValuePtrs.size(); }
104 void resize(unsigned N) { MDValuePtrs.resize(N); }
105 void push_back(Value *V) { MDValuePtrs.push_back(V); }
106 void clear() { MDValuePtrs.clear(); }
107 Value *back() const { return MDValuePtrs.back(); }
108 void pop_back() { MDValuePtrs.pop_back(); }
109 bool empty() const { return MDValuePtrs.empty(); }
111 Value *operator[](unsigned i) const {
112 assert(i < MDValuePtrs.size());
113 return MDValuePtrs[i];
116 void shrinkTo(unsigned N) {
117 assert(N <= size() && "Invalid shrinkTo request!");
118 MDValuePtrs.resize(N);
121 Value *getValueFwdRef(unsigned Idx);
122 void AssignValue(Value *V, unsigned Idx);
125 class BitcodeReader : public GVMaterializer {
126 LLVMContext &Context;
128 MemoryBuffer *Buffer;
130 std::unique_ptr<BitstreamReader> StreamFile;
131 BitstreamCursor Stream;
132 DataStreamer *LazyStreamer;
133 uint64_t NextUnreadBit;
134 bool SeenValueSymbolTable;
136 std::vector<Type*> TypeList;
137 BitcodeReaderValueList ValueList;
138 BitcodeReaderMDValueList MDValueList;
139 SmallVector<Instruction *, 64> InstructionList;
140 SmallVector<SmallVector<uint64_t, 64>, 64> UseListRecords;
142 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
143 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
144 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
146 SmallVector<Instruction*, 64> InstsWithTBAATag;
148 /// MAttributes - The set of attributes by index. Index zero in the
149 /// file is for null, and is thus not represented here. As such all indices
151 std::vector<AttributeSet> MAttributes;
153 /// \brief The set of attribute groups.
154 std::map<unsigned, AttributeSet> MAttributeGroups;
156 /// FunctionBBs - While parsing a function body, this is a list of the basic
157 /// blocks for the function.
158 std::vector<BasicBlock*> FunctionBBs;
160 // When reading the module header, this list is populated with functions that
161 // have bodies later in the file.
162 std::vector<Function*> FunctionsWithBodies;
164 // When intrinsic functions are encountered which require upgrading they are
165 // stored here with their replacement function.
166 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
167 UpgradedIntrinsicMap UpgradedIntrinsics;
169 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
170 DenseMap<unsigned, unsigned> MDKindMap;
172 // Several operations happen after the module header has been read, but
173 // before function bodies are processed. This keeps track of whether
174 // we've done this yet.
175 bool SeenFirstFunctionBody;
177 /// DeferredFunctionInfo - When function bodies are initially scanned, this
178 /// map contains info about where to find deferred function body in the
180 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
182 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
183 /// are resolved lazily when functions are loaded.
184 typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
185 DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
187 /// UseRelativeIDs - Indicates that we are using a new encoding for
188 /// instruction operands where most operands in the current
189 /// FUNCTION_BLOCK are encoded relative to the instruction number,
190 /// for a more compact encoding. Some instruction operands are not
191 /// relative to the instruction ID: basic block numbers, and types.
192 /// Once the old style function blocks have been phased out, we would
193 /// not need this flag.
196 static const std::error_category &BitcodeErrorCategory();
200 BitcodeStreamInvalidSize,
201 ConflictingMETADATA_KINDRecords,
202 CouldNotFindFunctionInStream,
204 InsufficientFunctionProtos,
205 InvalidBitcodeSignature,
206 InvalidBitcodeWrapperHeader,
207 InvalidConstantReference,
208 InvalidID, // A read identifier is not found in the table it should be in.
209 InvalidInstructionWithNoBB,
210 InvalidRecord, // A read record doesn't have the expected size or structure
211 InvalidTypeForValue, // Type read OK, but is invalid for its use
213 InvalidType, // We were unable to read a type
214 MalformedBlock, // We are unable to advance in the stream.
215 MalformedGlobalInitializerSet,
216 InvalidMultipleBlocks, // We found multiple blocks of a kind that should
218 NeverResolvedValueFoundInFunction,
219 InvalidValue // Invalid version, inst number, attr number, etc
222 std::error_code Error(ErrorType E) {
223 return std::error_code(E, BitcodeErrorCategory());
226 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C, bool BufferOwned)
227 : Context(C), TheModule(nullptr), Buffer(buffer),
228 BufferOwned(BufferOwned), LazyStreamer(nullptr), NextUnreadBit(0),
229 SeenValueSymbolTable(false), ValueList(C), MDValueList(C),
230 SeenFirstFunctionBody(false), UseRelativeIDs(false) {}
231 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
232 : Context(C), TheModule(nullptr), Buffer(nullptr), BufferOwned(false),
233 LazyStreamer(streamer), NextUnreadBit(0), SeenValueSymbolTable(false),
234 ValueList(C), MDValueList(C), SeenFirstFunctionBody(false),
235 UseRelativeIDs(false) {}
236 ~BitcodeReader() { FreeState(); }
238 void materializeForwardReferencedFunctions();
242 bool isMaterializable(const GlobalValue *GV) const override;
243 bool isDematerializable(const GlobalValue *GV) const override;
244 std::error_code Materialize(GlobalValue *GV) override;
245 std::error_code MaterializeModule(Module *M) override;
246 void Dematerialize(GlobalValue *GV) override;
248 /// @brief Main interface to parsing a bitcode buffer.
249 /// @returns true if an error occurred.
250 std::error_code ParseBitcodeInto(Module *M);
252 /// @brief Cheap mechanism to just extract module triple
253 /// @returns true if an error occurred.
254 std::error_code ParseTriple(std::string &Triple);
256 static uint64_t decodeSignRotatedValue(uint64_t V);
259 Type *getTypeByID(unsigned ID);
260 Value *getFnValueByID(unsigned ID, Type *Ty) {
261 if (Ty && Ty->isMetadataTy())
262 return MDValueList.getValueFwdRef(ID);
263 return ValueList.getValueFwdRef(ID, Ty);
265 BasicBlock *getBasicBlock(unsigned ID) const {
266 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
267 return FunctionBBs[ID];
269 AttributeSet getAttributes(unsigned i) const {
270 if (i-1 < MAttributes.size())
271 return MAttributes[i-1];
272 return AttributeSet();
275 /// getValueTypePair - Read a value/type pair out of the specified record from
276 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
277 /// Return true on failure.
278 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
279 unsigned InstNum, Value *&ResVal) {
280 if (Slot == Record.size()) return true;
281 unsigned ValNo = (unsigned)Record[Slot++];
282 // Adjust the ValNo, if it was encoded relative to the InstNum.
284 ValNo = InstNum - ValNo;
285 if (ValNo < InstNum) {
286 // If this is not a forward reference, just return the value we already
288 ResVal = getFnValueByID(ValNo, nullptr);
289 return ResVal == nullptr;
290 } else if (Slot == Record.size()) {
294 unsigned TypeNo = (unsigned)Record[Slot++];
295 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
296 return ResVal == nullptr;
299 /// popValue - Read a value out of the specified record from slot 'Slot'.
300 /// Increment Slot past the number of slots used by the value in the record.
301 /// Return true if there is an error.
302 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
303 unsigned InstNum, Type *Ty, Value *&ResVal) {
304 if (getValue(Record, Slot, InstNum, Ty, ResVal))
306 // All values currently take a single record slot.
311 /// getValue -- Like popValue, but does not increment the Slot number.
312 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
313 unsigned InstNum, Type *Ty, Value *&ResVal) {
314 ResVal = getValue(Record, Slot, InstNum, Ty);
315 return ResVal == nullptr;
318 /// getValue -- Version of getValue that returns ResVal directly,
319 /// or 0 if there is an error.
320 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
321 unsigned InstNum, Type *Ty) {
322 if (Slot == Record.size()) return nullptr;
323 unsigned ValNo = (unsigned)Record[Slot];
324 // Adjust the ValNo, if it was encoded relative to the InstNum.
326 ValNo = InstNum - ValNo;
327 return getFnValueByID(ValNo, Ty);
330 /// getValueSigned -- Like getValue, but decodes signed VBRs.
331 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
332 unsigned InstNum, Type *Ty) {
333 if (Slot == Record.size()) return nullptr;
334 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
335 // Adjust the ValNo, if it was encoded relative to the InstNum.
337 ValNo = InstNum - ValNo;
338 return getFnValueByID(ValNo, Ty);
341 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
342 std::error_code ParseModule(bool Resume);
343 std::error_code ParseAttributeBlock();
344 std::error_code ParseAttributeGroupBlock();
345 std::error_code ParseTypeTable();
346 std::error_code ParseTypeTableBody();
348 std::error_code ParseValueSymbolTable();
349 std::error_code ParseConstants();
350 std::error_code RememberAndSkipFunctionBody();
351 std::error_code ParseFunctionBody(Function *F);
352 std::error_code GlobalCleanup();
353 std::error_code ResolveGlobalAndAliasInits();
354 std::error_code ParseMetadata();
355 std::error_code ParseMetadataAttachment();
356 std::error_code ParseModuleTriple(std::string &Triple);
357 std::error_code ParseUseLists();
358 std::error_code InitStream();
359 std::error_code InitStreamFromBuffer();
360 std::error_code InitLazyStream();
361 std::error_code FindFunctionInStream(
363 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
366 } // End llvm namespace