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 /// MAttributes - The set of attributes by index. Index zero in the
148 /// file is for null, and is thus not represented here. As such all indices
150 std::vector<AttributeSet> MAttributes;
152 /// \brief The set of attribute groups.
153 std::map<unsigned, AttributeSet> MAttributeGroups;
155 /// FunctionBBs - While parsing a function body, this is a list of the basic
156 /// blocks for the function.
157 std::vector<BasicBlock*> FunctionBBs;
159 // When reading the module header, this list is populated with functions that
160 // have bodies later in the file.
161 std::vector<Function*> FunctionsWithBodies;
163 // When intrinsic functions are encountered which require upgrading they are
164 // stored here with their replacement function.
165 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
166 UpgradedIntrinsicMap UpgradedIntrinsics;
168 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
169 DenseMap<unsigned, unsigned> MDKindMap;
171 // Several operations happen after the module header has been read, but
172 // before function bodies are processed. This keeps track of whether
173 // we've done this yet.
174 bool SeenFirstFunctionBody;
176 /// DeferredFunctionInfo - When function bodies are initially scanned, this
177 /// map contains info about where to find deferred function body in the
179 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
181 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
182 /// are resolved lazily when functions are loaded.
183 typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
184 DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
186 /// UseRelativeIDs - Indicates that we are using a new encoding for
187 /// instruction operands where most operands in the current
188 /// FUNCTION_BLOCK are encoded relative to the instruction number,
189 /// for a more compact encoding. Some instruction operands are not
190 /// relative to the instruction ID: basic block numbers, and types.
191 /// Once the old style function blocks have been phased out, we would
192 /// not need this flag.
196 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
197 : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
198 LazyStreamer(0), NextUnreadBit(0), SeenValueSymbolTable(false),
199 ErrorString(0), ValueList(C), MDValueList(C),
200 SeenFirstFunctionBody(false), UseRelativeIDs(false) {
202 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
203 : Context(C), TheModule(0), Buffer(0), BufferOwned(false),
204 LazyStreamer(streamer), NextUnreadBit(0), SeenValueSymbolTable(false),
205 ErrorString(0), ValueList(C), MDValueList(C),
206 SeenFirstFunctionBody(false), UseRelativeIDs(false) {
212 void materializeForwardReferencedFunctions();
216 /// setBufferOwned - If this is true, the reader will destroy the MemoryBuffer
217 /// when the reader is destroyed.
218 void setBufferOwned(bool Owned) { BufferOwned = Owned; }
220 virtual bool isMaterializable(const GlobalValue *GV) const;
221 virtual bool isDematerializable(const GlobalValue *GV) const;
222 virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
223 virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0);
224 virtual void Dematerialize(GlobalValue *GV);
226 bool Error(const char *Str) {
230 const char *getErrorString() const { return ErrorString; }
232 /// @brief Main interface to parsing a bitcode buffer.
233 /// @returns true if an error occurred.
234 bool ParseBitcodeInto(Module *M);
236 /// @brief Cheap mechanism to just extract module triple
237 /// @returns true if an error occurred.
238 bool ParseTriple(std::string &Triple);
240 static uint64_t decodeSignRotatedValue(uint64_t V);
243 Type *getTypeByID(unsigned ID);
244 Value *getFnValueByID(unsigned ID, Type *Ty) {
245 if (Ty && Ty->isMetadataTy())
246 return MDValueList.getValueFwdRef(ID);
247 return ValueList.getValueFwdRef(ID, Ty);
249 BasicBlock *getBasicBlock(unsigned ID) const {
250 if (ID >= FunctionBBs.size()) return 0; // Invalid ID
251 return FunctionBBs[ID];
253 AttributeSet getAttributes(unsigned i) const {
254 if (i-1 < MAttributes.size())
255 return MAttributes[i-1];
256 return AttributeSet();
259 /// getValueTypePair - Read a value/type pair out of the specified record from
260 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
261 /// Return true on failure.
262 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
263 unsigned InstNum, Value *&ResVal) {
264 if (Slot == Record.size()) return true;
265 unsigned ValNo = (unsigned)Record[Slot++];
266 // Adjust the ValNo, if it was encoded relative to the InstNum.
268 ValNo = InstNum - ValNo;
269 if (ValNo < InstNum) {
270 // If this is not a forward reference, just return the value we already
272 ResVal = getFnValueByID(ValNo, 0);
274 } else if (Slot == Record.size()) {
278 unsigned TypeNo = (unsigned)Record[Slot++];
279 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
283 /// popValue - Read a value out of the specified record from slot 'Slot'.
284 /// Increment Slot past the number of slots used by the value in the record.
285 /// Return true if there is an error.
286 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
287 unsigned InstNum, Type *Ty, Value *&ResVal) {
288 if (getValue(Record, Slot, InstNum, Ty, ResVal))
290 // All values currently take a single record slot.
295 /// getValue -- Like popValue, but does not increment the Slot number.
296 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
297 unsigned InstNum, Type *Ty, Value *&ResVal) {
298 ResVal = getValue(Record, Slot, InstNum, Ty);
302 /// getValue -- Version of getValue that returns ResVal directly,
303 /// or 0 if there is an error.
304 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
305 unsigned InstNum, Type *Ty) {
306 if (Slot == Record.size()) return 0;
307 unsigned ValNo = (unsigned)Record[Slot];
308 // Adjust the ValNo, if it was encoded relative to the InstNum.
310 ValNo = InstNum - ValNo;
311 return getFnValueByID(ValNo, Ty);
314 /// getValueSigned -- Like getValue, but decodes signed VBRs.
315 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
316 unsigned InstNum, Type *Ty) {
317 if (Slot == Record.size()) return 0;
318 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
319 // Adjust the ValNo, if it was encoded relative to the InstNum.
321 ValNo = InstNum - ValNo;
322 return getFnValueByID(ValNo, Ty);
325 bool ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
326 bool ParseModule(bool Resume);
327 bool ParseAttributeBlock();
328 bool ParseAttributeGroupBlock();
329 bool ParseTypeTable();
330 bool ParseTypeTableBody();
332 bool ParseValueSymbolTable();
333 bool ParseConstants();
334 bool RememberAndSkipFunctionBody();
335 bool ParseFunctionBody(Function *F);
336 bool GlobalCleanup();
337 bool ResolveGlobalAndAliasInits();
338 bool ParseMetadata();
339 bool ParseMetadataAttachment();
340 bool ParseModuleTriple(std::string &Triple);
341 bool ParseUseLists();
343 bool InitStreamFromBuffer();
344 bool InitLazyStream();
345 bool FindFunctionInStream(Function *F,
346 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator);
349 } // End llvm namespace