Make a major API change to BitstreamReader: split all the reading
[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   
30 //===----------------------------------------------------------------------===//
31 //                          BitcodeReaderValueList Class
32 //===----------------------------------------------------------------------===//
33
34 class BitcodeReaderValueList {
35   std::vector<WeakVH> ValuePtrs;
36   
37   /// ResolveConstants - As we resolve forward-referenced constants, we add
38   /// information about them to this vector.  This allows us to resolve them in
39   /// bulk instead of resolving each reference at a time.  See the code in
40   /// ResolveConstantForwardRefs for more information about this.
41   ///
42   /// The key of this vector is the placeholder constant, the value is the slot
43   /// number that holds the resolved value.
44   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
45   ResolveConstantsTy ResolveConstants;
46 public:
47   BitcodeReaderValueList() {}
48   ~BitcodeReaderValueList() {
49     assert(ResolveConstants.empty() && "Constants not resolved?");
50   }
51
52   // vector compatibility methods
53   unsigned size() const { return ValuePtrs.size(); }
54   void resize(unsigned N) { ValuePtrs.resize(N); }
55   void push_back(Value *V) {
56     ValuePtrs.push_back(V);
57   }
58   
59   void clear() {
60     assert(ResolveConstants.empty() && "Constants not resolved?");
61     ValuePtrs.clear();
62   }
63   
64   Value *operator[](unsigned i) const {
65     assert(i < ValuePtrs.size());
66     return ValuePtrs[i];
67   }
68   
69   Value *back() const { return ValuePtrs.back(); }
70     void pop_back() { ValuePtrs.pop_back(); }
71   bool empty() const { return ValuePtrs.empty(); }
72   void shrinkTo(unsigned N) {
73     assert(N <= size() && "Invalid shrinkTo request!");
74     ValuePtrs.resize(N);
75   }
76   
77   Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
78   Value *getValueFwdRef(unsigned Idx, const Type *Ty);
79   
80   void AssignValue(Value *V, unsigned Idx);
81   
82   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
83   /// resolves any forward references.
84   void ResolveConstantForwardRefs();
85 };
86
87 class BitcodeReader : public ModuleProvider {
88   MemoryBuffer *Buffer;
89   BitstreamReader StreamFile;
90   BitstreamCursor Stream;
91   
92   const char *ErrorString;
93   
94   std::vector<PATypeHolder> TypeList;
95   BitcodeReaderValueList ValueList;
96   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
97   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
98   
99   /// MAttributes - The set of attributes by index.  Index zero in the
100   /// file is for null, and is thus not represented here.  As such all indices
101   /// are off by one.
102   std::vector<AttrListPtr> MAttributes;
103   
104   /// FunctionBBs - While parsing a function body, this is a list of the basic
105   /// blocks for the function.
106   std::vector<BasicBlock*> FunctionBBs;
107   
108   // When reading the module header, this list is populated with functions that
109   // have bodies later in the file.
110   std::vector<Function*> FunctionsWithBodies;
111
112   // When intrinsic functions are encountered which require upgrading they are 
113   // stored here with their replacement function.
114   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
115   UpgradedIntrinsicMap UpgradedIntrinsics;
116   
117   // After the module header has been read, the FunctionsWithBodies list is 
118   // reversed.  This keeps track of whether we've done this yet.
119   bool HasReversedFunctionsWithBodies;
120   
121   /// DeferredFunctionInfo - When function bodies are initially scanned, this
122   /// map contains info about where to find deferred function body (in the
123   /// stream) and what linkage the original function had.
124   DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
125 public:
126   explicit BitcodeReader(MemoryBuffer *buffer)
127       : Buffer(buffer), ErrorString(0) {
128     HasReversedFunctionsWithBodies = false;
129   }
130   ~BitcodeReader() {
131     FreeState();
132   }
133   
134   void FreeState();
135   
136   /// releaseMemoryBuffer - This causes the reader to completely forget about
137   /// the memory buffer it contains, which prevents the buffer from being
138   /// destroyed when it is deleted.
139   void releaseMemoryBuffer() {
140     Buffer = 0;
141   }
142   
143   virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
144   virtual Module *materializeModule(std::string *ErrInfo = 0);
145   virtual void dematerializeFunction(Function *F);
146   virtual Module *releaseModule(std::string *ErrInfo = 0);
147
148   bool Error(const char *Str) {
149     ErrorString = Str;
150     return true;
151   }
152   const char *getErrorString() const { return ErrorString; }
153   
154   /// @brief Main interface to parsing a bitcode buffer.
155   /// @returns true if an error occurred.
156   bool ParseBitcode();
157 private:
158   const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
159   Value *getFnValueByID(unsigned ID, const Type *Ty) {
160     return ValueList.getValueFwdRef(ID, Ty);
161   }
162   BasicBlock *getBasicBlock(unsigned ID) const {
163     if (ID >= FunctionBBs.size()) return 0; // Invalid ID
164     return FunctionBBs[ID];
165   }
166   AttrListPtr getAttributes(unsigned i) const {
167     if (i-1 < MAttributes.size())
168       return MAttributes[i-1];
169     return AttrListPtr();
170   }
171   
172   /// getValueTypePair - Read a value/type pair out of the specified record from
173   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
174   /// Return true on failure.
175   bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
176                         unsigned InstNum, Value *&ResVal) {
177     if (Slot == Record.size()) return true;
178     unsigned ValNo = (unsigned)Record[Slot++];
179     if (ValNo < InstNum) {
180       // If this is not a forward reference, just return the value we already
181       // have.
182       ResVal = getFnValueByID(ValNo, 0);
183       return ResVal == 0;
184     } else if (Slot == Record.size()) {
185       return true;
186     }
187     
188     unsigned TypeNo = (unsigned)Record[Slot++];
189     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
190     return ResVal == 0;
191   }
192   bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
193                 const Type *Ty, Value *&ResVal) {
194     if (Slot == Record.size()) return true;
195     unsigned ValNo = (unsigned)Record[Slot++];
196     ResVal = getFnValueByID(ValNo, Ty);
197     return ResVal == 0;
198   }
199
200   
201   bool ParseModule(const std::string &ModuleID);
202   bool ParseAttributeBlock();
203   bool ParseTypeTable();
204   bool ParseTypeSymbolTable();
205   bool ParseValueSymbolTable();
206   bool ParseConstants();
207   bool RememberAndSkipFunctionBody();
208   bool ParseFunctionBody(Function *F);
209   bool ResolveGlobalAndAliasInits();
210 };
211   
212 } // End llvm namespace
213
214 #endif