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