add bitcode reader support for blockaddress. We can now fully
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.h
1 //===- BitcodeReader.h - Internal BitcodeReader impl ------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitcodeReader class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef BITCODE_READER_H
15 #define BITCODE_READER_H
16
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/Attributes.h"
19 #include "llvm/Type.h"
20 #include "llvm/OperandTraits.h"
21 #include "llvm/Bitcode/BitstreamReader.h"
22 #include "llvm/Bitcode/LLVMBitCodes.h"
23 #include "llvm/Support/ValueHandle.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include <vector>
26
27 namespace llvm {
28   class MemoryBuffer;
29   class LLVMContext;
30   
31 //===----------------------------------------------------------------------===//
32 //                          BitcodeReaderValueList Class
33 //===----------------------------------------------------------------------===//
34
35 class BitcodeReaderValueList {
36   std::vector<WeakVH> ValuePtrs;
37   
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.
42   ///
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;
47   LLVMContext& Context;
48 public:
49   BitcodeReaderValueList(LLVMContext& C) : Context(C) {}
50   ~BitcodeReaderValueList() {
51     assert(ResolveConstants.empty() && "Constants not resolved?");
52   }
53
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);
59   }
60   
61   void clear() {
62     assert(ResolveConstants.empty() && "Constants not resolved?");
63     ValuePtrs.clear();
64   }
65   
66   Value *operator[](unsigned i) const {
67     assert(i < ValuePtrs.size());
68     return ValuePtrs[i];
69   }
70   
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!");
76     ValuePtrs.resize(N);
77   }
78   
79   Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
80   Value *getValueFwdRef(unsigned Idx, const Type *Ty);
81   
82   void AssignValue(Value *V, unsigned Idx);
83   
84   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
85   /// resolves any forward references.
86   void ResolveConstantForwardRefs();
87 };
88
89
90 //===----------------------------------------------------------------------===//
91 //                          BitcodeReaderMDValueList Class
92 //===----------------------------------------------------------------------===//
93
94 class BitcodeReaderMDValueList {
95   std::vector<WeakVH> MDValuePtrs;
96   
97   LLVMContext &Context;
98 public:
99   BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
100
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(); }
109   
110   Value *operator[](unsigned i) const {
111     assert(i < MDValuePtrs.size());
112     return MDValuePtrs[i];
113   }
114   
115   void shrinkTo(unsigned N) {
116     assert(N <= size() && "Invalid shrinkTo request!");
117     MDValuePtrs.resize(N);
118   }
119
120   Value *getValueFwdRef(unsigned Idx);
121   void AssignValue(Value *V, unsigned Idx);
122 };
123
124 class BitcodeReader : public ModuleProvider {
125   LLVMContext &Context;
126   MemoryBuffer *Buffer;
127   BitstreamReader StreamFile;
128   BitstreamCursor Stream;
129   
130   const char *ErrorString;
131   
132   std::vector<PATypeHolder> TypeList;
133   BitcodeReaderValueList ValueList;
134   BitcodeReaderMDValueList MDValueList;
135   SmallVector<Instruction *, 64> InstructionList;
136
137   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
138   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
139   
140   /// MAttributes - The set of attributes by index.  Index zero in the
141   /// file is for null, and is thus not represented here.  As such all indices
142   /// are off by one.
143   std::vector<AttrListPtr> MAttributes;
144   
145   /// FunctionBBs - While parsing a function body, this is a list of the basic
146   /// blocks for the function.
147   std::vector<BasicBlock*> FunctionBBs;
148   
149   // When reading the module header, this list is populated with functions that
150   // have bodies later in the file.
151   std::vector<Function*> FunctionsWithBodies;
152
153   // When intrinsic functions are encountered which require upgrading they are 
154   // stored here with their replacement function.
155   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
156   UpgradedIntrinsicMap UpgradedIntrinsics;
157   
158   // After the module header has been read, the FunctionsWithBodies list is 
159   // reversed.  This keeps track of whether we've done this yet.
160   bool HasReversedFunctionsWithBodies;
161   
162   /// DeferredFunctionInfo - When function bodies are initially scanned, this
163   /// map contains info about where to find deferred function body (in the
164   /// stream) and what linkage the original function had.
165   DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
166   
167   /// BlockAddrFwdRefs - These are blockaddr references to basic blocks.  These
168   /// are resolved lazily when functions are loaded.
169   typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
170   DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
171   
172 public:
173   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext& C)
174     : Context(C), Buffer(buffer), ErrorString(0), ValueList(C), MDValueList(C) {
175     HasReversedFunctionsWithBodies = false;
176   }
177   ~BitcodeReader() {
178     FreeState();
179   }
180   
181   void FreeState();
182   
183   /// releaseMemoryBuffer - This causes the reader to completely forget about
184   /// the memory buffer it contains, which prevents the buffer from being
185   /// destroyed when it is deleted.
186   void releaseMemoryBuffer() {
187     Buffer = 0;
188   }
189   
190   virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
191   virtual Module *materializeModule(std::string *ErrInfo = 0);
192   virtual void dematerializeFunction(Function *F);
193   virtual Module *releaseModule(std::string *ErrInfo = 0);
194
195   bool Error(const char *Str) {
196     ErrorString = Str;
197     return true;
198   }
199   const char *getErrorString() const { return ErrorString; }
200   
201   /// @brief Main interface to parsing a bitcode buffer.
202   /// @returns true if an error occurred.
203   bool ParseBitcode();
204 private:
205   const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
206   Value *getFnValueByID(unsigned ID, const Type *Ty) {
207     if (Ty == Type::getMetadataTy(Context))
208       return MDValueList.getValueFwdRef(ID);
209     else
210       return ValueList.getValueFwdRef(ID, Ty);
211   }
212   BasicBlock *getBasicBlock(unsigned ID) const {
213     if (ID >= FunctionBBs.size()) return 0; // Invalid ID
214     return FunctionBBs[ID];
215   }
216   AttrListPtr getAttributes(unsigned i) const {
217     if (i-1 < MAttributes.size())
218       return MAttributes[i-1];
219     return AttrListPtr();
220   }
221   
222   /// getValueTypePair - Read a value/type pair out of the specified record from
223   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
224   /// Return true on failure.
225   bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
226                         unsigned InstNum, Value *&ResVal) {
227     if (Slot == Record.size()) return true;
228     unsigned ValNo = (unsigned)Record[Slot++];
229     if (ValNo < InstNum) {
230       // If this is not a forward reference, just return the value we already
231       // have.
232       ResVal = getFnValueByID(ValNo, 0);
233       return ResVal == 0;
234     } else if (Slot == Record.size()) {
235       return true;
236     }
237     
238     unsigned TypeNo = (unsigned)Record[Slot++];
239     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
240     return ResVal == 0;
241   }
242   bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
243                 const Type *Ty, Value *&ResVal) {
244     if (Slot == Record.size()) return true;
245     unsigned ValNo = (unsigned)Record[Slot++];
246     ResVal = getFnValueByID(ValNo, Ty);
247     return ResVal == 0;
248   }
249
250   
251   bool ParseModule(const std::string &ModuleID);
252   bool ParseAttributeBlock();
253   bool ParseTypeTable();
254   bool ParseTypeSymbolTable();
255   bool ParseValueSymbolTable();
256   bool ParseConstants();
257   bool RememberAndSkipFunctionBody();
258   bool ParseFunctionBody(Function *F);
259   bool ResolveGlobalAndAliasInits();
260   bool ParseMetadata();
261   bool ParseMetadataAttachment();
262 };
263   
264 } // End llvm namespace
265
266 #endif