1 //===- ReadConst.cpp - Code to constants and constant pools ---------------===//
3 // This file implements functionality to deserialize constants and entire
6 // Note that this library should be as fast as possible, reentrant, and
9 //===----------------------------------------------------------------------===//
11 #include "ReaderInternals.h"
12 #include "llvm/Module.h"
13 #include "llvm/Constants.h"
16 const Type *BytecodeParser::parseTypeConstant(const unsigned char *&Buf,
17 const unsigned char *EndBuf) {
19 if (read_vbr(Buf, EndBuf, PrimType)) throw Error_readvbr;
22 if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
26 case Type::FunctionTyID: {
28 if (read_vbr(Buf, EndBuf, Typ)) return Val;
29 const Type *RetType = getType(Typ);
32 if (read_vbr(Buf, EndBuf, NumParams)) return Val;
34 std::vector<const Type*> Params;
36 if (read_vbr(Buf, EndBuf, Typ)) return Val;
37 Params.push_back(getType(Typ));
40 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
41 if (isVarArg) Params.pop_back();
43 return FunctionType::get(RetType, Params, isVarArg);
45 case Type::ArrayTyID: {
47 if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
48 const Type *ElementType = getType(ElTyp);
51 if (read_vbr(Buf, EndBuf, NumElements)) return Val;
53 BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
54 << NumElements << "\n");
55 return ArrayType::get(ElementType, NumElements);
57 case Type::StructTyID: {
59 std::vector<const Type*> Elements;
61 if (read_vbr(Buf, EndBuf, Typ)) return Val;
62 while (Typ) { // List is terminated by void/0 typeid
63 Elements.push_back(getType(Typ));
64 if (read_vbr(Buf, EndBuf, Typ)) return Val;
67 return StructType::get(Elements);
69 case Type::PointerTyID: {
71 if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
72 BCR_TRACE(5, "Pointer Type Constant #" << ElTyp << "\n");
73 return PointerType::get(getType(ElTyp));
76 case Type::OpaqueTyID: {
77 return OpaqueType::get();
81 std::cerr << __FILE__ << ":" << __LINE__
82 << ": Don't know how to deserialize"
83 << " primitive Type " << PrimType << "\n";
88 // parseTypeConstants - We have to use this weird code to handle recursive
89 // types. We know that recursive types will only reference the current slab of
90 // values in the type plane, but they can forward reference types before they
91 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
92 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
93 // this ugly problem, we pessimistically insert an opaque type for each type we
94 // are about to read. This means that forward references will resolve to
95 // something and when we reread the type later, we can replace the opaque type
96 // with a new resolved concrete type.
98 void debug_type_tables();
99 void BytecodeParser::parseTypeConstants(const unsigned char *&Buf,
100 const unsigned char *EndBuf,
101 TypeValuesListTy &Tab,
102 unsigned NumEntries) {
103 assert(Tab.size() == 0 && "should not have read type constants in before!");
105 // Insert a bunch of opaque types to be resolved later...
106 for (unsigned i = 0; i < NumEntries; ++i)
107 Tab.push_back(OpaqueType::get());
109 // Loop through reading all of the types. Forward types will make use of the
110 // opaque types just inserted.
112 for (unsigned i = 0; i < NumEntries; ++i) {
113 const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
114 if (NewTy == 0) throw std::string("Parsed invalid type.");
115 BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
116 "' Replacing: " << OldTy << "\n");
118 // Don't insertValue the new type... instead we want to replace the opaque
119 // type with the new concrete value...
122 // Refine the abstract type to the new type. This causes all uses of the
123 // abstract type to use the newty. This also will cause the opaque type
126 ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
128 // This should have replace the old opaque type with the new type in the
129 // value table... or with a preexisting type that was already in the system
130 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
133 BCR_TRACE(5, "Resulting types:\n");
134 for (unsigned i = 0; i < NumEntries; ++i) {
135 BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
141 Constant *BytecodeParser::parseConstantValue(const unsigned char *&Buf,
142 const unsigned char *EndBuf,
145 // We must check for a ConstantExpr before switching by type because
146 // a ConstantExpr can be of any type, and has no explicit value.
148 unsigned isExprNumArgs; // 0 if not expr; numArgs if is expr
149 if (read_vbr(Buf, EndBuf, isExprNumArgs)) throw Error_readvbr;
151 // FIXME: Encoding of constant exprs could be much more compact!
153 std::vector<Constant*> ArgVec;
154 ArgVec.reserve(isExprNumArgs);
155 if (read_vbr(Buf, EndBuf, Opcode)) throw Error_readvbr;
157 // Read the slot number and types of each of the arguments
158 for (unsigned i = 0; i != isExprNumArgs; ++i) {
159 unsigned ArgValSlot, ArgTypeSlot;
160 if (read_vbr(Buf, EndBuf, ArgValSlot)) throw Error_readvbr;
161 if (read_vbr(Buf, EndBuf, ArgTypeSlot)) throw Error_readvbr;
162 const Type *ArgTy = getType(ArgTypeSlot);
164 BCR_TRACE(4, "CE Arg " << i << ": Type: '" << *ArgTy << "' slot: "
165 << ArgValSlot << "\n");
167 // Get the arg value from its slot if it exists, otherwise a placeholder
168 ArgVec.push_back(getConstantValue(ArgTy, ArgValSlot));
171 // Construct a ConstantExpr of the appropriate kind
172 if (isExprNumArgs == 1) { // All one-operand expressions
173 assert(Opcode == Instruction::Cast);
174 return ConstantExpr::getCast(ArgVec[0], Ty);
175 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
176 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
177 return ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
178 } else { // All other 2-operand expressions
179 return ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
183 // Ok, not an ConstantExpr. We now know how to read the given type...
184 switch (Ty->getPrimitiveID()) {
185 case Type::BoolTyID: {
187 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
188 if (Val != 0 && Val != 1) throw std::string("Invalid boolean value read.");
189 return ConstantBool::get(Val == 1);
192 case Type::UByteTyID: // Unsigned integer types...
193 case Type::UShortTyID:
194 case Type::UIntTyID: {
196 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
197 if (!ConstantUInt::isValueValidForType(Ty, Val))
198 throw std::string("Invalid unsigned byte/short/int read.");
199 return ConstantUInt::get(Ty, Val);
202 case Type::ULongTyID: {
204 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
205 return ConstantUInt::get(Ty, Val);
208 case Type::SByteTyID: // Signed integer types...
209 case Type::ShortTyID:
210 case Type::IntTyID: {
213 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
214 if (!ConstantSInt::isValueValidForType(Ty, Val))
215 throw std::string("Invalid signed byte/short/int/long read.");
216 return ConstantSInt::get(Ty, Val);
219 case Type::FloatTyID: {
221 if (input_data(Buf, EndBuf, &F, &F+1)) throw Error_inputdata;
222 return ConstantFP::get(Ty, F);
225 case Type::DoubleTyID: {
227 if (input_data(Buf, EndBuf, &Val, &Val+1)) throw Error_inputdata;
228 return ConstantFP::get(Ty, Val);
232 throw std::string("Type constants shouldn't live in constant table!");
234 case Type::ArrayTyID: {
235 const ArrayType *AT = cast<ArrayType>(Ty);
236 unsigned NumElements = AT->getNumElements();
238 std::vector<Constant*> Elements;
239 while (NumElements--) { // Read all of the elements of the constant.
241 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
242 Elements.push_back(getConstantValue(AT->getElementType(), Slot));
244 return ConstantArray::get(AT, Elements);
247 case Type::StructTyID: {
248 const StructType *ST = cast<StructType>(Ty);
249 const StructType::ElementTypes &ET = ST->getElementTypes();
251 std::vector<Constant *> Elements;
252 for (unsigned i = 0; i < ET.size(); ++i) {
254 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
255 Elements.push_back(getConstantValue(ET[i], Slot));
258 return ConstantStruct::get(ST, Elements);
261 case Type::PointerTyID: { // ConstantPointerRef value...
262 const PointerType *PT = cast<PointerType>(Ty);
264 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
265 BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
267 // Check to see if we have already read this global variable...
268 Value *Val = getValue(PT, Slot, false);
271 if (!(GV = dyn_cast<GlobalValue>(Val)))
272 throw std::string("Value of ConstantPointerRef not in ValueTable!");
273 BCR_TRACE(5, "Value Found in ValueTable!\n");
274 } else if (RevisionNum > 0) {
275 // Revision #0 could have forward references to globals that were weird.
276 // We got rid of this in subsequent revs.
277 throw std::string("Forward references to globals not allowed.");
278 } else { // Nope... find or create a forward ref. for it
279 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
281 if (I != GlobalRefs.end()) {
282 BCR_TRACE(5, "Previous forward ref found!\n");
283 GV = cast<GlobalValue>(I->second);
285 BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
287 // Create a placeholder for the global variable reference...
288 GlobalVariable *GVar =
289 new GlobalVariable(PT->getElementType(), false,
290 GlobalValue::InternalLinkage);
292 // Keep track of the fact that we have a forward ref to recycle it
293 GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
295 // Must temporarily push this value into the module table...
296 TheModule->getGlobalList().push_back(GVar);
301 return ConstantPointerRef::get(GV);
305 throw std::string("Don't know how to deserialize constant value of type '"+
306 Ty->getDescription());
310 void BytecodeParser::ParseGlobalTypes(const unsigned char *&Buf,
311 const unsigned char *EndBuf) {
313 ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
316 void BytecodeParser::ParseConstantPool(const unsigned char *&Buf,
317 const unsigned char *EndBuf,
319 TypeValuesListTy &TypeTab) {
320 while (Buf < EndBuf) {
321 unsigned NumEntries, Typ;
323 if (read_vbr(Buf, EndBuf, NumEntries) ||
324 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
325 if (Typ == Type::TypeTyID) {
326 BCR_TRACE(3, "Type: 'type' NumEntries: " << NumEntries << "\n");
327 parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries);
329 const Type *Ty = getType(Typ);
330 BCR_TRACE(3, "Type: '" << *Ty << "' NumEntries: " << NumEntries << "\n");
332 for (unsigned i = 0; i < NumEntries; ++i) {
333 Constant *C = parseConstantValue(Buf, EndBuf, Ty);
334 assert(C && "parseConstantValue returned NULL!");
335 BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
336 unsigned Slot = insertValue(C, Typ, Tab);
338 // If we are reading a function constant table, make sure that we adjust
339 // the slot number to be the real global constant number.
341 if (&Tab != &ModuleValues && Typ < ModuleValues.size())
342 Slot += ModuleValues[Typ]->size();
343 ResolveReferencesToValue(C, Slot);
348 if (Buf > EndBuf) throw std::string("Read past end of buffer.");