Added LLVM project notice to the top of every C++ source file.
[oota-llvm.git] / lib / Bytecode / Reader / ConstantReader.cpp
1 //===- ReadConst.cpp - Code to constants and constant pools ---------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements functionality to deserialize constants and entire 
11 // constant pools.
12 // 
13 // Note that this library should be as fast as possible, reentrant, and 
14 // thread-safe!!
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "ReaderInternals.h"
19 #include "llvm/Module.h"
20 #include "llvm/Constants.h"
21 #include <algorithm>
22
23 const Type *BytecodeParser::parseTypeConstant(const unsigned char *&Buf,
24                                               const unsigned char *EndBuf) {
25   unsigned PrimType;
26   if (read_vbr(Buf, EndBuf, PrimType)) throw Error_readvbr;
27
28   const Type *Val = 0;
29   if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
30     return Val;
31   
32   switch (PrimType) {
33   case Type::FunctionTyID: {
34     unsigned Typ;
35     if (read_vbr(Buf, EndBuf, Typ)) return Val;
36     const Type *RetType = getType(Typ);
37
38     unsigned NumParams;
39     if (read_vbr(Buf, EndBuf, NumParams)) return Val;
40
41     std::vector<const Type*> Params;
42     while (NumParams--) {
43       if (read_vbr(Buf, EndBuf, Typ)) return Val;
44       Params.push_back(getType(Typ));
45     }
46
47     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
48     if (isVarArg) Params.pop_back();
49
50     return FunctionType::get(RetType, Params, isVarArg);
51   }
52   case Type::ArrayTyID: {
53     unsigned ElTyp;
54     if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
55     const Type *ElementType = getType(ElTyp);
56
57     unsigned NumElements;
58     if (read_vbr(Buf, EndBuf, NumElements)) return Val;
59
60     BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size=" 
61               << NumElements << "\n");
62     return ArrayType::get(ElementType, NumElements);
63   }
64   case Type::StructTyID: {
65     unsigned Typ;
66     std::vector<const Type*> Elements;
67
68     if (read_vbr(Buf, EndBuf, Typ)) return Val;
69     while (Typ) {         // List is terminated by void/0 typeid
70       Elements.push_back(getType(Typ));
71       if (read_vbr(Buf, EndBuf, Typ)) return Val;
72     }
73
74     return StructType::get(Elements);
75   }
76   case Type::PointerTyID: {
77     unsigned ElTyp;
78     if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
79     BCR_TRACE(5, "Pointer Type Constant #" << ElTyp << "\n");
80     return PointerType::get(getType(ElTyp));
81   }
82
83   case Type::OpaqueTyID: {
84     return OpaqueType::get();
85   }
86
87   default:
88     std::cerr << __FILE__ << ":" << __LINE__
89               << ": Don't know how to deserialize"
90               << " primitive Type " << PrimType << "\n";
91     return Val;
92   }
93 }
94
95 // parseTypeConstants - We have to use this weird code to handle recursive
96 // types.  We know that recursive types will only reference the current slab of
97 // values in the type plane, but they can forward reference types before they
98 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
99 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
100 // this ugly problem, we pessimistically insert an opaque type for each type we
101 // are about to read.  This means that forward references will resolve to
102 // something and when we reread the type later, we can replace the opaque type
103 // with a new resolved concrete type.
104 //
105 void debug_type_tables();
106 void BytecodeParser::parseTypeConstants(const unsigned char *&Buf,
107                                         const unsigned char *EndBuf,
108                                         TypeValuesListTy &Tab,
109                                         unsigned NumEntries) {
110   assert(Tab.size() == 0 && "should not have read type constants in before!");
111
112   // Insert a bunch of opaque types to be resolved later...
113   for (unsigned i = 0; i < NumEntries; ++i)
114     Tab.push_back(OpaqueType::get());
115
116   // Loop through reading all of the types.  Forward types will make use of the
117   // opaque types just inserted.
118   //
119   for (unsigned i = 0; i < NumEntries; ++i) {
120     const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
121     if (NewTy == 0) throw std::string("Parsed invalid type.");
122     BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
123               "' Replacing: " << OldTy << "\n");
124
125     // Don't insertValue the new type... instead we want to replace the opaque
126     // type with the new concrete value...
127     //
128
129     // Refine the abstract type to the new type.  This causes all uses of the
130     // abstract type to use the newty.  This also will cause the opaque type
131     // to be deleted...
132     //
133     ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
134
135     // This should have replace the old opaque type with the new type in the
136     // value table... or with a preexisting type that was already in the system
137     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
138   }
139
140   BCR_TRACE(5, "Resulting types:\n");
141   for (unsigned i = 0; i < NumEntries; ++i) {
142     BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
143   }
144   debug_type_tables();
145 }
146
147
148 Constant *BytecodeParser::parseConstantValue(const unsigned char *&Buf,
149                                              const unsigned char *EndBuf,
150                                              const Type *Ty) {
151
152   // We must check for a ConstantExpr before switching by type because
153   // a ConstantExpr can be of any type, and has no explicit value.
154   // 
155   unsigned isExprNumArgs;               // 0 if not expr; numArgs if is expr
156   if (read_vbr(Buf, EndBuf, isExprNumArgs)) throw Error_readvbr;
157   if (isExprNumArgs) {
158     // FIXME: Encoding of constant exprs could be much more compact!
159     unsigned Opcode;
160     std::vector<Constant*> ArgVec;
161     ArgVec.reserve(isExprNumArgs);
162     if (read_vbr(Buf, EndBuf, Opcode)) throw Error_readvbr;
163
164     // Read the slot number and types of each of the arguments
165     for (unsigned i = 0; i != isExprNumArgs; ++i) {
166       unsigned ArgValSlot, ArgTypeSlot;
167       if (read_vbr(Buf, EndBuf, ArgValSlot)) throw Error_readvbr;
168       if (read_vbr(Buf, EndBuf, ArgTypeSlot)) throw Error_readvbr;
169       const Type *ArgTy = getType(ArgTypeSlot);
170       
171       BCR_TRACE(4, "CE Arg " << i << ": Type: '" << *ArgTy << "'  slot: "
172                 << ArgValSlot << "\n");
173       
174       // Get the arg value from its slot if it exists, otherwise a placeholder
175       ArgVec.push_back(getConstantValue(ArgTy, ArgValSlot));
176     }
177     
178     // Construct a ConstantExpr of the appropriate kind
179     if (isExprNumArgs == 1) {           // All one-operand expressions
180       assert(Opcode == Instruction::Cast);
181       return ConstantExpr::getCast(ArgVec[0], Ty);
182     } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
183       std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
184       return ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
185     } else {                            // All other 2-operand expressions
186       return ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
187     }
188   }
189   
190   // Ok, not an ConstantExpr.  We now know how to read the given type...
191   switch (Ty->getPrimitiveID()) {
192   case Type::BoolTyID: {
193     unsigned Val;
194     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
195     if (Val != 0 && Val != 1) throw std::string("Invalid boolean value read.");
196     return ConstantBool::get(Val == 1);
197   }
198
199   case Type::UByteTyID:   // Unsigned integer types...
200   case Type::UShortTyID:
201   case Type::UIntTyID: {
202     unsigned Val;
203     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
204     if (!ConstantUInt::isValueValidForType(Ty, Val)) 
205       throw std::string("Invalid unsigned byte/short/int read.");
206     return ConstantUInt::get(Ty, Val);
207   }
208
209   case Type::ULongTyID: {
210     uint64_t Val;
211     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
212     return ConstantUInt::get(Ty, Val);
213   }
214
215   case Type::SByteTyID:   // Signed integer types...
216   case Type::ShortTyID:
217   case Type::IntTyID: {
218   case Type::LongTyID:
219     int64_t Val;
220     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
221     if (!ConstantSInt::isValueValidForType(Ty, Val)) 
222       throw std::string("Invalid signed byte/short/int/long read.");
223     return ConstantSInt::get(Ty, Val);
224   }
225
226   case Type::FloatTyID: {
227     float F;
228     if (input_data(Buf, EndBuf, &F, &F+1)) throw Error_inputdata;
229     return ConstantFP::get(Ty, F);
230   }
231
232   case Type::DoubleTyID: {
233     double Val;
234     if (input_data(Buf, EndBuf, &Val, &Val+1)) throw Error_inputdata;
235     return ConstantFP::get(Ty, Val);
236   }
237
238   case Type::TypeTyID:
239     throw std::string("Type constants shouldn't live in constant table!");
240
241   case Type::ArrayTyID: {
242     const ArrayType *AT = cast<ArrayType>(Ty);
243     unsigned NumElements = AT->getNumElements();
244
245     std::vector<Constant*> Elements;
246     while (NumElements--) {   // Read all of the elements of the constant.
247       unsigned Slot;
248       if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
249       Elements.push_back(getConstantValue(AT->getElementType(), Slot));
250     }
251     return ConstantArray::get(AT, Elements);
252   }
253
254   case Type::StructTyID: {
255     const StructType *ST = cast<StructType>(Ty);
256     const StructType::ElementTypes &ET = ST->getElementTypes();
257
258     std::vector<Constant *> Elements;
259     for (unsigned i = 0; i < ET.size(); ++i) {
260       unsigned Slot;
261       if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
262       Elements.push_back(getConstantValue(ET[i], Slot));
263     }
264
265     return ConstantStruct::get(ST, Elements);
266   }    
267
268   case Type::PointerTyID: {  // ConstantPointerRef value...
269     const PointerType *PT = cast<PointerType>(Ty);
270     unsigned Slot;
271     if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
272     BCR_TRACE(4, "CPR: Type: '" << Ty << "'  slot: " << Slot << "\n");
273     
274     // Check to see if we have already read this global variable...
275     Value *Val = getValue(PT, Slot, false);
276     GlobalValue *GV;
277     if (Val) {
278       if (!(GV = dyn_cast<GlobalValue>(Val))) 
279         throw std::string("Value of ConstantPointerRef not in ValueTable!");
280       BCR_TRACE(5, "Value Found in ValueTable!\n");
281     } else if (RevisionNum > 0) {
282       // Revision #0 could have forward references to globals that were weird.
283       // We got rid of this in subsequent revs.
284       throw std::string("Forward references to globals not allowed.");
285     } else {         // Nope... find or create a forward ref. for it
286       GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
287       
288       if (I != GlobalRefs.end()) {
289         BCR_TRACE(5, "Previous forward ref found!\n");
290         GV = cast<GlobalValue>(I->second);
291       } else {
292         BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
293         
294         // Create a placeholder for the global variable reference...
295         GlobalVariable *GVar =
296           new GlobalVariable(PT->getElementType(), false,
297                              GlobalValue::InternalLinkage);
298         
299         // Keep track of the fact that we have a forward ref to recycle it
300         GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
301         
302         // Must temporarily push this value into the module table...
303         TheModule->getGlobalList().push_back(GVar);
304         GV = GVar;
305       }
306     }
307     
308     return ConstantPointerRef::get(GV);
309   }
310
311   default:
312     throw std::string("Don't know how to deserialize constant value of type '"+
313                       Ty->getDescription());
314   }
315 }
316
317 void BytecodeParser::ParseGlobalTypes(const unsigned char *&Buf,
318                                       const unsigned char *EndBuf) {
319   ValueTable T;
320   ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
321 }
322
323 void BytecodeParser::ParseConstantPool(const unsigned char *&Buf,
324                                        const unsigned char *EndBuf,
325                                        ValueTable &Tab, 
326                                        TypeValuesListTy &TypeTab) {
327   while (Buf < EndBuf) {
328     unsigned NumEntries, Typ;
329
330     if (read_vbr(Buf, EndBuf, NumEntries) ||
331         read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
332     if (Typ == Type::TypeTyID) {
333       BCR_TRACE(3, "Type: 'type'  NumEntries: " << NumEntries << "\n");
334       parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries);
335     } else {
336       const Type *Ty = getType(Typ);
337       BCR_TRACE(3, "Type: '" << *Ty << "'  NumEntries: " << NumEntries << "\n");
338
339       for (unsigned i = 0; i < NumEntries; ++i) {
340         Constant *C = parseConstantValue(Buf, EndBuf, Ty);
341         assert(C && "parseConstantValue returned NULL!");
342         BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
343         unsigned Slot = insertValue(C, Typ, Tab);
344
345         // If we are reading a function constant table, make sure that we adjust
346         // the slot number to be the real global constant number.
347         //
348         if (&Tab != &ModuleValues && Typ < ModuleValues.size())
349           Slot += ModuleValues[Typ]->size();
350         ResolveReferencesToValue(C, Slot);
351       }
352     }
353   }
354   
355   if (Buf > EndBuf) throw std::string("Read past end of buffer.");
356 }