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 LLVM_LIB_BITCODE_READER_BITCODEREADER_H
15 #define LLVM_LIB_BITCODE_READER_BITCODEREADER_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"
26 #include <system_error>
34 //===----------------------------------------------------------------------===//
35 // BitcodeReaderValueList Class
36 //===----------------------------------------------------------------------===//
38 class BitcodeReaderValueList {
39 std::vector<WeakVH> ValuePtrs;
41 /// ResolveConstants - As we resolve forward-referenced constants, we add
42 /// information about them to this vector. This allows us to resolve them in
43 /// bulk instead of resolving each reference at a time. See the code in
44 /// ResolveConstantForwardRefs for more information about this.
46 /// The key of this vector is the placeholder constant, the value is the slot
47 /// number that holds the resolved value.
48 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
49 ResolveConstantsTy ResolveConstants;
52 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
53 ~BitcodeReaderValueList() {
54 assert(ResolveConstants.empty() && "Constants not resolved?");
57 // vector compatibility methods
58 unsigned size() const { return ValuePtrs.size(); }
59 void resize(unsigned N) { ValuePtrs.resize(N); }
60 void push_back(Value *V) {
61 ValuePtrs.push_back(V);
65 assert(ResolveConstants.empty() && "Constants not resolved?");
69 Value *operator[](unsigned i) const {
70 assert(i < ValuePtrs.size());
74 Value *back() const { return ValuePtrs.back(); }
75 void pop_back() { ValuePtrs.pop_back(); }
76 bool empty() const { return ValuePtrs.empty(); }
77 void shrinkTo(unsigned N) {
78 assert(N <= size() && "Invalid shrinkTo request!");
82 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
83 Value *getValueFwdRef(unsigned Idx, Type *Ty);
85 void AssignValue(Value *V, unsigned Idx);
87 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
88 /// resolves any forward references.
89 void ResolveConstantForwardRefs();
93 //===----------------------------------------------------------------------===//
94 // BitcodeReaderMDValueList Class
95 //===----------------------------------------------------------------------===//
97 class BitcodeReaderMDValueList {
98 std::vector<WeakVH> MDValuePtrs;
100 LLVMContext &Context;
102 BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
104 // vector compatibility methods
105 unsigned size() const { return MDValuePtrs.size(); }
106 void resize(unsigned N) { MDValuePtrs.resize(N); }
107 void push_back(Value *V) { MDValuePtrs.push_back(V); }
108 void clear() { MDValuePtrs.clear(); }
109 Value *back() const { return MDValuePtrs.back(); }
110 void pop_back() { MDValuePtrs.pop_back(); }
111 bool empty() const { return MDValuePtrs.empty(); }
113 Value *operator[](unsigned i) const {
114 assert(i < MDValuePtrs.size());
115 return MDValuePtrs[i];
118 void shrinkTo(unsigned N) {
119 assert(N <= size() && "Invalid shrinkTo request!");
120 MDValuePtrs.resize(N);
123 Value *getValueFwdRef(unsigned Idx);
124 void AssignValue(Value *V, unsigned Idx);
127 class BitcodeReader : public GVMaterializer {
128 LLVMContext &Context;
130 std::unique_ptr<MemoryBuffer> Buffer;
131 std::unique_ptr<BitstreamReader> StreamFile;
132 BitstreamCursor Stream;
133 DataStreamer *LazyStreamer;
134 uint64_t NextUnreadBit;
135 bool SeenValueSymbolTable;
137 std::vector<Type*> TypeList;
138 BitcodeReaderValueList ValueList;
139 BitcodeReaderMDValueList MDValueList;
140 std::vector<Comdat *> ComdatList;
141 SmallVector<Instruction *, 64> InstructionList;
143 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
144 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
145 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
147 SmallVector<Instruction*, 64> InstsWithTBAATag;
149 /// MAttributes - The set of attributes by index. Index zero in the
150 /// file is for null, and is thus not represented here. As such all indices
152 std::vector<AttributeSet> MAttributes;
154 /// \brief The set of attribute groups.
155 std::map<unsigned, AttributeSet> MAttributeGroups;
157 /// FunctionBBs - While parsing a function body, this is a list of the basic
158 /// blocks for the function.
159 std::vector<BasicBlock*> FunctionBBs;
161 // When reading the module header, this list is populated with functions that
162 // have bodies later in the file.
163 std::vector<Function*> FunctionsWithBodies;
165 // When intrinsic functions are encountered which require upgrading they are
166 // stored here with their replacement function.
167 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
168 UpgradedIntrinsicMap UpgradedIntrinsics;
170 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
171 DenseMap<unsigned, unsigned> MDKindMap;
173 // Several operations happen after the module header has been read, but
174 // before function bodies are processed. This keeps track of whether
175 // we've done this yet.
176 bool SeenFirstFunctionBody;
178 /// DeferredFunctionInfo - When function bodies are initially scanned, this
179 /// map contains info about where to find deferred function body in the
181 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
183 /// These are basic blocks forward-referenced by block addresses. They are
184 /// inserted lazily into functions when they're loaded. The basic block ID is
185 /// its index into the vector.
186 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
187 std::deque<Function *> BasicBlockFwdRefQueue;
189 /// UseRelativeIDs - Indicates that we are using a new encoding for
190 /// instruction operands where most operands in the current
191 /// FUNCTION_BLOCK are encoded relative to the instruction number,
192 /// for a more compact encoding. Some instruction operands are not
193 /// relative to the instruction ID: basic block numbers, and types.
194 /// Once the old style function blocks have been phased out, we would
195 /// not need this flag.
198 /// True if all functions will be materialized, negating the need to process
199 /// (e.g.) blockaddress forward references.
200 bool WillMaterializeAllForwardRefs;
202 /// Functions that have block addresses taken. This is usually empty.
203 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
206 std::error_code Error(BitcodeError E) { return make_error_code(E); }
208 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
209 : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
210 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
211 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
212 WillMaterializeAllForwardRefs(false) {}
213 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
214 : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
215 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
216 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
217 WillMaterializeAllForwardRefs(false) {}
218 ~BitcodeReader() { FreeState(); }
220 std::error_code materializeForwardReferencedFunctions();
224 void releaseBuffer();
226 bool isDematerializable(const GlobalValue *GV) const override;
227 std::error_code materialize(GlobalValue *GV) override;
228 std::error_code MaterializeModule(Module *M) override;
229 void Dematerialize(GlobalValue *GV) override;
231 /// @brief Main interface to parsing a bitcode buffer.
232 /// @returns true if an error occurred.
233 std::error_code ParseBitcodeInto(Module *M);
235 /// @brief Cheap mechanism to just extract module triple
236 /// @returns true if an error occurred.
237 ErrorOr<std::string> parseTriple();
239 static uint64_t decodeSignRotatedValue(uint64_t V);
242 Type *getTypeByID(unsigned ID);
243 Value *getFnValueByID(unsigned ID, Type *Ty) {
244 if (Ty && Ty->isMetadataTy())
245 return MDValueList.getValueFwdRef(ID);
246 return ValueList.getValueFwdRef(ID, Ty);
248 BasicBlock *getBasicBlock(unsigned ID) const {
249 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
250 return FunctionBBs[ID];
252 AttributeSet getAttributes(unsigned i) const {
253 if (i-1 < MAttributes.size())
254 return MAttributes[i-1];
255 return AttributeSet();
258 /// getValueTypePair - Read a value/type pair out of the specified record from
259 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
260 /// Return true on failure.
261 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
262 unsigned InstNum, Value *&ResVal) {
263 if (Slot == Record.size()) return true;
264 unsigned ValNo = (unsigned)Record[Slot++];
265 // Adjust the ValNo, if it was encoded relative to the InstNum.
267 ValNo = InstNum - ValNo;
268 if (ValNo < InstNum) {
269 // If this is not a forward reference, just return the value we already
271 ResVal = getFnValueByID(ValNo, nullptr);
272 return ResVal == nullptr;
273 } else if (Slot == Record.size()) {
277 unsigned TypeNo = (unsigned)Record[Slot++];
278 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
279 return ResVal == nullptr;
282 /// popValue - Read a value out of the specified record from slot 'Slot'.
283 /// Increment Slot past the number of slots used by the value in the record.
284 /// Return true if there is an error.
285 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
286 unsigned InstNum, Type *Ty, Value *&ResVal) {
287 if (getValue(Record, Slot, InstNum, Ty, ResVal))
289 // All values currently take a single record slot.
294 /// getValue -- Like popValue, but does not increment the Slot number.
295 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
296 unsigned InstNum, Type *Ty, Value *&ResVal) {
297 ResVal = getValue(Record, Slot, InstNum, Ty);
298 return ResVal == nullptr;
301 /// getValue -- Version of getValue that returns ResVal directly,
302 /// or 0 if there is an error.
303 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
304 unsigned InstNum, Type *Ty) {
305 if (Slot == Record.size()) return nullptr;
306 unsigned ValNo = (unsigned)Record[Slot];
307 // Adjust the ValNo, if it was encoded relative to the InstNum.
309 ValNo = InstNum - ValNo;
310 return getFnValueByID(ValNo, Ty);
313 /// getValueSigned -- Like getValue, but decodes signed VBRs.
314 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
315 unsigned InstNum, Type *Ty) {
316 if (Slot == Record.size()) return nullptr;
317 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
318 // Adjust the ValNo, if it was encoded relative to the InstNum.
320 ValNo = InstNum - ValNo;
321 return getFnValueByID(ValNo, Ty);
324 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
325 std::error_code ParseModule(bool Resume);
326 std::error_code ParseAttributeBlock();
327 std::error_code ParseAttributeGroupBlock();
328 std::error_code ParseTypeTable();
329 std::error_code ParseTypeTableBody();
331 std::error_code ParseValueSymbolTable();
332 std::error_code ParseConstants();
333 std::error_code RememberAndSkipFunctionBody();
334 std::error_code ParseFunctionBody(Function *F);
335 std::error_code GlobalCleanup();
336 std::error_code ResolveGlobalAndAliasInits();
337 std::error_code ParseMetadata();
338 std::error_code ParseMetadataAttachment();
339 ErrorOr<std::string> parseModuleTriple();
340 std::error_code ParseUseLists();
341 std::error_code InitStream();
342 std::error_code InitStreamFromBuffer();
343 std::error_code InitLazyStream();
344 std::error_code FindFunctionInStream(
346 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
349 } // End llvm namespace