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/Metadata.h"
23 #include "llvm/IR/OperandTraits.h"
24 #include "llvm/IR/TrackingMDRef.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/IR/ValueHandle.h"
28 #include <system_error>
36 //===----------------------------------------------------------------------===//
37 // BitcodeReaderValueList Class
38 //===----------------------------------------------------------------------===//
40 class BitcodeReaderValueList {
41 std::vector<WeakVH> ValuePtrs;
43 /// ResolveConstants - As we resolve forward-referenced constants, we add
44 /// information about them to this vector. This allows us to resolve them in
45 /// bulk instead of resolving each reference at a time. See the code in
46 /// ResolveConstantForwardRefs for more information about this.
48 /// The key of this vector is the placeholder constant, the value is the slot
49 /// number that holds the resolved value.
50 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
51 ResolveConstantsTy ResolveConstants;
54 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
55 ~BitcodeReaderValueList() {
56 assert(ResolveConstants.empty() && "Constants not resolved?");
59 // vector compatibility methods
60 unsigned size() const { return ValuePtrs.size(); }
61 void resize(unsigned N) { ValuePtrs.resize(N); }
62 void push_back(Value *V) {
63 ValuePtrs.push_back(V);
67 assert(ResolveConstants.empty() && "Constants not resolved?");
71 Value *operator[](unsigned i) const {
72 assert(i < ValuePtrs.size());
76 Value *back() const { return ValuePtrs.back(); }
77 void pop_back() { ValuePtrs.pop_back(); }
78 bool empty() const { return ValuePtrs.empty(); }
79 void shrinkTo(unsigned N) {
80 assert(N <= size() && "Invalid shrinkTo request!");
84 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
85 Value *getValueFwdRef(unsigned Idx, Type *Ty);
87 void AssignValue(Value *V, unsigned Idx);
89 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
90 /// resolves any forward references.
91 void ResolveConstantForwardRefs();
95 //===----------------------------------------------------------------------===//
96 // BitcodeReaderMDValueList Class
97 //===----------------------------------------------------------------------===//
99 class BitcodeReaderMDValueList {
102 std::vector<TrackingMDRef> MDValuePtrs;
104 LLVMContext &Context;
106 BitcodeReaderMDValueList(LLVMContext &C)
107 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
109 // vector compatibility methods
110 unsigned size() const { return MDValuePtrs.size(); }
111 void resize(unsigned N) { MDValuePtrs.resize(N); }
112 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
113 void clear() { MDValuePtrs.clear(); }
114 Metadata *back() const { return MDValuePtrs.back(); }
115 void pop_back() { MDValuePtrs.pop_back(); }
116 bool empty() const { return MDValuePtrs.empty(); }
118 Metadata *operator[](unsigned i) const {
119 assert(i < MDValuePtrs.size());
120 return MDValuePtrs[i];
123 void shrinkTo(unsigned N) {
124 assert(N <= size() && "Invalid shrinkTo request!");
125 MDValuePtrs.resize(N);
128 Metadata *getValueFwdRef(unsigned Idx);
129 void AssignValue(Metadata *MD, unsigned Idx);
130 void tryToResolveCycles();
133 class BitcodeReader : public GVMaterializer {
134 LLVMContext &Context;
136 std::unique_ptr<MemoryBuffer> Buffer;
137 std::unique_ptr<BitstreamReader> StreamFile;
138 BitstreamCursor Stream;
139 DataStreamer *LazyStreamer;
140 uint64_t NextUnreadBit;
141 bool SeenValueSymbolTable;
143 std::vector<Type*> TypeList;
144 BitcodeReaderValueList ValueList;
145 BitcodeReaderMDValueList MDValueList;
146 std::vector<Comdat *> ComdatList;
147 SmallVector<Instruction *, 64> InstructionList;
149 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
150 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
151 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
152 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
154 SmallVector<Instruction*, 64> InstsWithTBAATag;
156 /// MAttributes - The set of attributes by index. Index zero in the
157 /// file is for null, and is thus not represented here. As such all indices
159 std::vector<AttributeSet> MAttributes;
161 /// \brief The set of attribute groups.
162 std::map<unsigned, AttributeSet> MAttributeGroups;
164 /// FunctionBBs - While parsing a function body, this is a list of the basic
165 /// blocks for the function.
166 std::vector<BasicBlock*> FunctionBBs;
168 // When reading the module header, this list is populated with functions that
169 // have bodies later in the file.
170 std::vector<Function*> FunctionsWithBodies;
172 // When intrinsic functions are encountered which require upgrading they are
173 // stored here with their replacement function.
174 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
175 UpgradedIntrinsicMap UpgradedIntrinsics;
177 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
178 DenseMap<unsigned, unsigned> MDKindMap;
180 // Several operations happen after the module header has been read, but
181 // before function bodies are processed. This keeps track of whether
182 // we've done this yet.
183 bool SeenFirstFunctionBody;
185 /// DeferredFunctionInfo - When function bodies are initially scanned, this
186 /// map contains info about where to find deferred function body in the
188 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
190 /// These are basic blocks forward-referenced by block addresses. They are
191 /// inserted lazily into functions when they're loaded. The basic block ID is
192 /// its index into the vector.
193 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
194 std::deque<Function *> BasicBlockFwdRefQueue;
196 /// UseRelativeIDs - Indicates that we are using a new encoding for
197 /// instruction operands where most operands in the current
198 /// FUNCTION_BLOCK are encoded relative to the instruction number,
199 /// for a more compact encoding. Some instruction operands are not
200 /// relative to the instruction ID: basic block numbers, and types.
201 /// Once the old style function blocks have been phased out, we would
202 /// not need this flag.
205 /// True if all functions will be materialized, negating the need to process
206 /// (e.g.) blockaddress forward references.
207 bool WillMaterializeAllForwardRefs;
209 /// Functions that have block addresses taken. This is usually empty.
210 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
213 std::error_code Error(BitcodeError E) { return make_error_code(E); }
215 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
216 : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
217 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
218 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
219 WillMaterializeAllForwardRefs(false) {}
220 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
221 : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
222 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
223 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
224 WillMaterializeAllForwardRefs(false) {}
225 ~BitcodeReader() { FreeState(); }
227 std::error_code materializeForwardReferencedFunctions();
231 void releaseBuffer();
233 bool isDematerializable(const GlobalValue *GV) const override;
234 std::error_code materialize(GlobalValue *GV) override;
235 std::error_code MaterializeModule(Module *M) override;
236 std::vector<StructType *> getIdentifiedStructTypes() const override;
237 void Dematerialize(GlobalValue *GV) override;
239 /// @brief Main interface to parsing a bitcode buffer.
240 /// @returns true if an error occurred.
241 std::error_code ParseBitcodeInto(Module *M);
243 /// @brief Cheap mechanism to just extract module triple
244 /// @returns true if an error occurred.
245 ErrorOr<std::string> parseTriple();
247 static uint64_t decodeSignRotatedValue(uint64_t V);
250 std::vector<StructType *> IdentifiedStructTypes;
251 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
252 StructType *createIdentifiedStructType(LLVMContext &Context);
254 Type *getTypeByID(unsigned ID);
255 Value *getFnValueByID(unsigned ID, Type *Ty) {
256 if (Ty && Ty->isMetadataTy())
257 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
258 return ValueList.getValueFwdRef(ID, Ty);
260 Metadata *getFnMetadataByID(unsigned ID) {
261 return MDValueList.getValueFwdRef(ID);
263 BasicBlock *getBasicBlock(unsigned ID) const {
264 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
265 return FunctionBBs[ID];
267 AttributeSet getAttributes(unsigned i) const {
268 if (i-1 < MAttributes.size())
269 return MAttributes[i-1];
270 return AttributeSet();
273 /// getValueTypePair - Read a value/type pair out of the specified record from
274 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
275 /// Return true on failure.
276 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
277 unsigned InstNum, Value *&ResVal) {
278 if (Slot == Record.size()) return true;
279 unsigned ValNo = (unsigned)Record[Slot++];
280 // Adjust the ValNo, if it was encoded relative to the InstNum.
282 ValNo = InstNum - ValNo;
283 if (ValNo < InstNum) {
284 // If this is not a forward reference, just return the value we already
286 ResVal = getFnValueByID(ValNo, nullptr);
287 return ResVal == nullptr;
288 } else if (Slot == Record.size()) {
292 unsigned TypeNo = (unsigned)Record[Slot++];
293 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
294 return ResVal == nullptr;
297 /// popValue - Read a value out of the specified record from slot 'Slot'.
298 /// Increment Slot past the number of slots used by the value in the record.
299 /// Return true if there is an error.
300 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
301 unsigned InstNum, Type *Ty, Value *&ResVal) {
302 if (getValue(Record, Slot, InstNum, Ty, ResVal))
304 // All values currently take a single record slot.
309 /// getValue -- Like popValue, but does not increment the Slot number.
310 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
311 unsigned InstNum, Type *Ty, Value *&ResVal) {
312 ResVal = getValue(Record, Slot, InstNum, Ty);
313 return ResVal == nullptr;
316 /// getValue -- Version of getValue that returns ResVal directly,
317 /// or 0 if there is an error.
318 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
319 unsigned InstNum, Type *Ty) {
320 if (Slot == Record.size()) return nullptr;
321 unsigned ValNo = (unsigned)Record[Slot];
322 // Adjust the ValNo, if it was encoded relative to the InstNum.
324 ValNo = InstNum - ValNo;
325 return getFnValueByID(ValNo, Ty);
328 /// getValueSigned -- Like getValue, but decodes signed VBRs.
329 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
330 unsigned InstNum, Type *Ty) {
331 if (Slot == Record.size()) return nullptr;
332 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
333 // Adjust the ValNo, if it was encoded relative to the InstNum.
335 ValNo = InstNum - ValNo;
336 return getFnValueByID(ValNo, Ty);
339 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
340 std::error_code ParseModule(bool Resume);
341 std::error_code ParseAttributeBlock();
342 std::error_code ParseAttributeGroupBlock();
343 std::error_code ParseTypeTable();
344 std::error_code ParseTypeTableBody();
346 std::error_code ParseValueSymbolTable();
347 std::error_code ParseConstants();
348 std::error_code RememberAndSkipFunctionBody();
349 std::error_code ParseFunctionBody(Function *F);
350 std::error_code GlobalCleanup();
351 std::error_code ResolveGlobalAndAliasInits();
352 std::error_code ParseMetadata();
353 std::error_code ParseMetadataAttachment();
354 ErrorOr<std::string> parseModuleTriple();
355 std::error_code ParseUseLists();
356 std::error_code InitStream();
357 std::error_code InitStreamFromBuffer();
358 std::error_code InitLazyStream();
359 std::error_code FindFunctionInStream(
361 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
364 } // End llvm namespace