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/GVMaterializer.h"
21 #include "llvm/IR/Attributes.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/Support/ValueHandle.h"
31 //===----------------------------------------------------------------------===//
32 // BitcodeReaderValueList Class
33 //===----------------------------------------------------------------------===//
35 class BitcodeReaderValueList {
36 std::vector<WeakVH> ValuePtrs;
38 /// ResolveConstants - As we resolve forward-referenced constants, we add
39 /// information about them to this vector. This allows us to resolve them in
40 /// bulk instead of resolving each reference at a time. See the code in
41 /// ResolveConstantForwardRefs for more information about this.
43 /// The key of this vector is the placeholder constant, the value is the slot
44 /// number that holds the resolved value.
45 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
46 ResolveConstantsTy ResolveConstants;
49 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
50 ~BitcodeReaderValueList() {
51 assert(ResolveConstants.empty() && "Constants not resolved?");
54 // vector compatibility methods
55 unsigned size() const { return ValuePtrs.size(); }
56 void resize(unsigned N) { ValuePtrs.resize(N); }
57 void push_back(Value *V) {
58 ValuePtrs.push_back(V);
62 assert(ResolveConstants.empty() && "Constants not resolved?");
66 Value *operator[](unsigned i) const {
67 assert(i < ValuePtrs.size());
71 Value *back() const { return ValuePtrs.back(); }
72 void pop_back() { ValuePtrs.pop_back(); }
73 bool empty() const { return ValuePtrs.empty(); }
74 void shrinkTo(unsigned N) {
75 assert(N <= size() && "Invalid shrinkTo request!");
79 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
80 Value *getValueFwdRef(unsigned Idx, Type *Ty);
82 void AssignValue(Value *V, unsigned Idx);
84 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
85 /// resolves any forward references.
86 void ResolveConstantForwardRefs();
90 //===----------------------------------------------------------------------===//
91 // BitcodeReaderMDValueList Class
92 //===----------------------------------------------------------------------===//
94 class BitcodeReaderMDValueList {
95 std::vector<WeakVH> MDValuePtrs;
99 BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
101 // vector compatibility methods
102 unsigned size() const { return MDValuePtrs.size(); }
103 void resize(unsigned N) { MDValuePtrs.resize(N); }
104 void push_back(Value *V) { MDValuePtrs.push_back(V); }
105 void clear() { MDValuePtrs.clear(); }
106 Value *back() const { return MDValuePtrs.back(); }
107 void pop_back() { MDValuePtrs.pop_back(); }
108 bool empty() const { return MDValuePtrs.empty(); }
110 Value *operator[](unsigned i) const {
111 assert(i < MDValuePtrs.size());
112 return MDValuePtrs[i];
115 void shrinkTo(unsigned N) {
116 assert(N <= size() && "Invalid shrinkTo request!");
117 MDValuePtrs.resize(N);
120 Value *getValueFwdRef(unsigned Idx);
121 void AssignValue(Value *V, unsigned Idx);
124 class BitcodeReader : public GVMaterializer {
125 LLVMContext &Context;
127 MemoryBuffer *Buffer;
129 OwningPtr<BitstreamReader> StreamFile;
130 BitstreamCursor Stream;
131 DataStreamer *LazyStreamer;
132 uint64_t NextUnreadBit;
133 bool SeenValueSymbolTable;
135 const char *ErrorString;
137 std::vector<Type*> TypeList;
138 BitcodeReaderValueList ValueList;
139 BitcodeReaderMDValueList MDValueList;
140 SmallVector<Instruction *, 64> InstructionList;
141 SmallVector<SmallVector<uint64_t, 64>, 64> UseListRecords;
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 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
184 /// are resolved lazily when functions are loaded.
185 typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
186 DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
188 /// UseRelativeIDs - Indicates that we are using a new encoding for
189 /// instruction operands where most operands in the current
190 /// FUNCTION_BLOCK are encoded relative to the instruction number,
191 /// for a more compact encoding. Some instruction operands are not
192 /// relative to the instruction ID: basic block numbers, and types.
193 /// Once the old style function blocks have been phased out, we would
194 /// not need this flag.
198 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
199 : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
200 LazyStreamer(0), NextUnreadBit(0), SeenValueSymbolTable(false),
201 ErrorString(0), ValueList(C), MDValueList(C),
202 SeenFirstFunctionBody(false), UseRelativeIDs(false) {
204 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
205 : Context(C), TheModule(0), Buffer(0), BufferOwned(false),
206 LazyStreamer(streamer), NextUnreadBit(0), SeenValueSymbolTable(false),
207 ErrorString(0), ValueList(C), MDValueList(C),
208 SeenFirstFunctionBody(false), UseRelativeIDs(false) {
214 void materializeForwardReferencedFunctions();
218 /// setBufferOwned - If this is true, the reader will destroy the MemoryBuffer
219 /// when the reader is destroyed.
220 void setBufferOwned(bool Owned) { BufferOwned = Owned; }
222 virtual bool isMaterializable(const GlobalValue *GV) const;
223 virtual bool isDematerializable(const GlobalValue *GV) const;
224 virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
225 virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0);
226 virtual void Dematerialize(GlobalValue *GV);
228 bool Error(const char *Str) {
232 const char *getErrorString() const { return ErrorString; }
234 /// @brief Main interface to parsing a bitcode buffer.
235 /// @returns true if an error occurred.
236 bool ParseBitcodeInto(Module *M);
238 /// @brief Cheap mechanism to just extract module triple
239 /// @returns true if an error occurred.
240 bool ParseTriple(std::string &Triple);
242 static uint64_t decodeSignRotatedValue(uint64_t V);
245 Type *getTypeByID(unsigned ID);
246 Value *getFnValueByID(unsigned ID, Type *Ty) {
247 if (Ty && Ty->isMetadataTy())
248 return MDValueList.getValueFwdRef(ID);
249 return ValueList.getValueFwdRef(ID, Ty);
251 BasicBlock *getBasicBlock(unsigned ID) const {
252 if (ID >= FunctionBBs.size()) return 0; // Invalid ID
253 return FunctionBBs[ID];
255 AttributeSet getAttributes(unsigned i) const {
256 if (i-1 < MAttributes.size())
257 return MAttributes[i-1];
258 return AttributeSet();
261 /// getValueTypePair - Read a value/type pair out of the specified record from
262 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
263 /// Return true on failure.
264 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
265 unsigned InstNum, Value *&ResVal) {
266 if (Slot == Record.size()) return true;
267 unsigned ValNo = (unsigned)Record[Slot++];
268 // Adjust the ValNo, if it was encoded relative to the InstNum.
270 ValNo = InstNum - ValNo;
271 if (ValNo < InstNum) {
272 // If this is not a forward reference, just return the value we already
274 ResVal = getFnValueByID(ValNo, 0);
276 } else if (Slot == Record.size()) {
280 unsigned TypeNo = (unsigned)Record[Slot++];
281 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
285 /// popValue - Read a value out of the specified record from slot 'Slot'.
286 /// Increment Slot past the number of slots used by the value in the record.
287 /// Return true if there is an error.
288 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
289 unsigned InstNum, Type *Ty, Value *&ResVal) {
290 if (getValue(Record, Slot, InstNum, Ty, ResVal))
292 // All values currently take a single record slot.
297 /// getValue -- Like popValue, but does not increment the Slot number.
298 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
299 unsigned InstNum, Type *Ty, Value *&ResVal) {
300 ResVal = getValue(Record, Slot, InstNum, Ty);
304 /// getValue -- Version of getValue that returns ResVal directly,
305 /// or 0 if there is an error.
306 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
307 unsigned InstNum, Type *Ty) {
308 if (Slot == Record.size()) return 0;
309 unsigned ValNo = (unsigned)Record[Slot];
310 // Adjust the ValNo, if it was encoded relative to the InstNum.
312 ValNo = InstNum - ValNo;
313 return getFnValueByID(ValNo, Ty);
316 /// getValueSigned -- Like getValue, but decodes signed VBRs.
317 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
318 unsigned InstNum, Type *Ty) {
319 if (Slot == Record.size()) return 0;
320 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
321 // Adjust the ValNo, if it was encoded relative to the InstNum.
323 ValNo = InstNum - ValNo;
324 return getFnValueByID(ValNo, Ty);
327 bool ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
328 bool ParseModule(bool Resume);
329 bool ParseAttributeBlock();
330 bool ParseAttributeGroupBlock();
331 bool ParseTypeTable();
332 bool ParseTypeTableBody();
334 bool ParseValueSymbolTable();
335 bool ParseConstants();
336 bool RememberAndSkipFunctionBody();
337 bool ParseFunctionBody(Function *F);
338 bool GlobalCleanup();
339 bool ResolveGlobalAndAliasInits();
340 bool ParseMetadata();
341 bool ParseMetadataAttachment();
342 bool ParseModuleTriple(std::string &Triple);
343 bool ParseUseLists();
345 bool InitStreamFromBuffer();
346 bool InitLazyStream();
347 bool FindFunctionInStream(Function *F,
348 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator);
351 } // End llvm namespace