Revert 55090, regressions in:
[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/ParameterAttributes.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/ADT/DenseMap.h"
24 #include <vector>
25
26 namespace llvm {
27   class MemoryBuffer;
28   
29 //===----------------------------------------------------------------------===//
30 //                          BitcodeReaderValueList Class
31 //===----------------------------------------------------------------------===//
32
33 class BitcodeReaderValueList : public User {
34   unsigned Capacity;
35 public:
36   BitcodeReaderValueList() : User(Type::VoidTy, Value::ArgumentVal, 0, 0)
37                            , Capacity(0) {}
38
39   /// Provide fast operand accessors
40   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
41
42   // vector compatibility methods
43   unsigned size() const { return getNumOperands(); }
44   void resize(unsigned);
45   void push_back(Value *V) {
46     unsigned OldOps(NumOperands), NewOps(NumOperands + 1);
47     resize(NewOps);
48     NumOperands = NewOps;
49     OperandList[OldOps] = V;
50   }
51   
52   void clear() {
53     if (OperandList) dropHungoffUses(OperandList);
54     Capacity = 0;
55   }
56   
57   Value *operator[](unsigned i) const { return getOperand(i); }
58   
59   Value *back() const { return getOperand(size() - 1); }
60   void pop_back() { setOperand(size() - 1, 0); --NumOperands; }
61   bool empty() const { return NumOperands == 0; }
62   void shrinkTo(unsigned N) {
63     assert(N <= NumOperands && "Invalid shrinkTo request!");
64     while (NumOperands > N)
65       pop_back();
66   }
67   virtual void print(std::ostream&) const {}
68   
69   Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
70   Value *getValueFwdRef(unsigned Idx, const Type *Ty);
71   
72   void AssignValue(Value *V, unsigned Idx) {
73     if (Idx == size()) {
74       push_back(V);
75     } else if (Value *OldV = getOperand(Idx)) {
76       // If there was a forward reference to this value, replace it.
77       setOperand(Idx, V);
78       OldV->replaceAllUsesWith(V);
79       delete OldV;
80     } else {
81       initVal(Idx, V);
82     }
83   }
84   
85 private:
86   void initVal(unsigned Idx, Value *V) {
87     if (Idx >= size()) {
88       // Insert a bunch of null values.
89       resize(Idx * 2 + 1);
90     }
91     assert(getOperand(Idx) == 0 && "Cannot init an already init'd Use!");
92     OperandList[Idx] = V;
93   }
94 };
95
96 template <>
97 struct OperandTraits<BitcodeReaderValueList> : HungoffOperandTraits</*16 FIXME*/> {
98 };
99
100 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BitcodeReaderValueList, Value)  
101
102 class BitcodeReader : public ModuleProvider {
103   MemoryBuffer *Buffer;
104   BitstreamReader Stream;
105   
106   const char *ErrorString;
107   
108   std::vector<PATypeHolder> TypeList;
109   BitcodeReaderValueList ValueList;
110   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
111   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
112   
113   /// ParamAttrs - The set of parameter attributes by index.  Index zero in the
114   /// file is for null, and is thus not represented here.  As such all indices
115   /// are off by one.
116   std::vector<PAListPtr> ParamAttrs;
117   
118   /// FunctionBBs - While parsing a function body, this is a list of the basic
119   /// blocks for the function.
120   std::vector<BasicBlock*> FunctionBBs;
121   
122   // When reading the module header, this list is populated with functions that
123   // have bodies later in the file.
124   std::vector<Function*> FunctionsWithBodies;
125
126   // When intrinsic functions are encountered which require upgrading they are 
127   // stored here with their replacement function.
128   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
129   UpgradedIntrinsicMap UpgradedIntrinsics;
130   
131   // After the module header has been read, the FunctionsWithBodies list is 
132   // reversed.  This keeps track of whether we've done this yet.
133   bool HasReversedFunctionsWithBodies;
134   
135   /// DeferredFunctionInfo - When function bodies are initially scanned, this
136   /// map contains info about where to find deferred function body (in the
137   /// stream) and what linkage the original function had.
138   DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
139 public:
140   explicit BitcodeReader(MemoryBuffer *buffer)
141       : Buffer(buffer), ErrorString(0) {
142     HasReversedFunctionsWithBodies = false;
143   }
144   ~BitcodeReader() {
145     FreeState();
146   }
147   
148   void FreeState();
149   
150   /// releaseMemoryBuffer - This causes the reader to completely forget about
151   /// the memory buffer it contains, which prevents the buffer from being
152   /// destroyed when it is deleted.
153   void releaseMemoryBuffer() {
154     Buffer = 0;
155   }
156   
157   virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
158   virtual Module *materializeModule(std::string *ErrInfo = 0);
159   virtual void dematerializeFunction(Function *F);
160   virtual Module *releaseModule(std::string *ErrInfo = 0);
161
162   bool Error(const char *Str) {
163     ErrorString = Str;
164     return true;
165   }
166   const char *getErrorString() const { return ErrorString; }
167   
168   /// @brief Main interface to parsing a bitcode buffer.
169   /// @returns true if an error occurred.
170   bool ParseBitcode();
171 private:
172   const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
173   Value *getFnValueByID(unsigned ID, const Type *Ty) {
174     return ValueList.getValueFwdRef(ID, Ty);
175   }
176   BasicBlock *getBasicBlock(unsigned ID) const {
177     if (ID >= FunctionBBs.size()) return 0; // Invalid ID
178     return FunctionBBs[ID];
179   }
180   PAListPtr getParamAttrs(unsigned i) const {
181     if (i-1 < ParamAttrs.size())
182       return ParamAttrs[i-1];
183     return PAListPtr();
184   }
185   
186   /// getValueTypePair - Read a value/type pair out of the specified record from
187   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
188   /// Return true on failure.
189   bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
190                         unsigned InstNum, Value *&ResVal) {
191     if (Slot == Record.size()) return true;
192     unsigned ValNo = (unsigned)Record[Slot++];
193     if (ValNo < InstNum) {
194       // If this is not a forward reference, just return the value we already
195       // have.
196       ResVal = getFnValueByID(ValNo, 0);
197       return ResVal == 0;
198     } else if (Slot == Record.size()) {
199       return true;
200     }
201     
202     unsigned TypeNo = (unsigned)Record[Slot++];
203     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
204     return ResVal == 0;
205   }
206   bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
207                 const Type *Ty, Value *&ResVal) {
208     if (Slot == Record.size()) return true;
209     unsigned ValNo = (unsigned)Record[Slot++];
210     ResVal = getFnValueByID(ValNo, Ty);
211     return ResVal == 0;
212   }
213
214   
215   bool ParseModule(const std::string &ModuleID);
216   bool ParseParamAttrBlock();
217   bool ParseTypeTable();
218   bool ParseTypeSymbolTable();
219   bool ParseValueSymbolTable();
220   bool ParseConstants();
221   bool RememberAndSkipFunctionBody();
222   bool ParseFunctionBody(Function *F);
223   bool ResolveGlobalAndAliasInits();
224 };
225   
226 } // End llvm namespace
227
228 #endif