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