blob: 3f86c1907b077fe6b9a0c12ae984e87d6f8a6654 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
12// Note that this library should be as fast as possible, reentrant, and
13// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000023#include "llvm/Instructions.h"
24#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000026#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000027#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000029#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000030#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Reid Spencer46b002c2004-07-11 17:28:43 +000033namespace {
34
Reid Spencer060d25d2004-06-29 23:29:38 +000035/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000036/// as a placeholder for the actual definition for forward constants defs.
37class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer46b002c2004-07-11 17:28:43 +000038 ConstantPlaceHolder(); // DO NOT IMPLEMENT
39 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000040public:
Chris Lattner389bd042004-12-09 06:19:44 +000041 ConstantPlaceHolder(const Type *Ty)
42 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000043};
Chris Lattner9e460f22003-10-04 20:00:03 +000044
Reid Spencer46b002c2004-07-11 17:28:43 +000045}
Reid Spencer060d25d2004-06-29 23:29:38 +000046
Reid Spencer24399722004-07-09 22:21:33 +000047// Provide some details on error
48inline void BytecodeReader::error(std::string err) {
49 err += " (Vers=" ;
50 err += itostr(RevisionNum) ;
51 err += ", Pos=" ;
52 err += itostr(At-MemStart);
53 err += ")";
54 throw err;
55}
56
Reid Spencer060d25d2004-06-29 23:29:38 +000057//===----------------------------------------------------------------------===//
58// Bytecode Reading Methods
59//===----------------------------------------------------------------------===//
60
Reid Spencer04cde2c2004-07-04 11:33:49 +000061/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000062inline bool BytecodeReader::moreInBlock() {
63 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000064}
65
Reid Spencer04cde2c2004-07-04 11:33:49 +000066/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000067inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000068 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000069 error(std::string("Attempt to read past the end of ") + block_name +
70 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000071}
Chris Lattner36392bc2003-10-08 21:18:57 +000072
Reid Spencer04cde2c2004-07-04 11:33:49 +000073/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000074inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000075 if (hasAlignment) {
76 BufPtr Save = At;
77 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
78 if (At > Save)
79 if (Handler) Handler->handleAlignment(At - Save);
80 if (At > BlockEnd)
81 error("Ran out of data while aligning!");
82 }
Reid Spencer060d25d2004-06-29 23:29:38 +000083}
84
Reid Spencer04cde2c2004-07-04 11:33:49 +000085/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000086inline unsigned BytecodeReader::read_uint() {
87 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000088 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000089 At += 4;
90 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
91}
92
Reid Spencer04cde2c2004-07-04 11:33:49 +000093/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000094inline unsigned BytecodeReader::read_vbr_uint() {
95 unsigned Shift = 0;
96 unsigned Result = 0;
97 BufPtr Save = At;
98
99 do {
100 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000101 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000102 Result |= (unsigned)((*At++) & 0x7F) << Shift;
103 Shift += 7;
104 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000105 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 return Result;
107}
108
Reid Spencer04cde2c2004-07-04 11:33:49 +0000109/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000110inline uint64_t BytecodeReader::read_vbr_uint64() {
111 unsigned Shift = 0;
112 uint64_t Result = 0;
113 BufPtr Save = At;
114
115 do {
116 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000117 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000118 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
119 Shift += 7;
120 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000121 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000122 return Result;
123}
124
Reid Spencer04cde2c2004-07-04 11:33:49 +0000125/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000126inline int64_t BytecodeReader::read_vbr_int64() {
127 uint64_t R = read_vbr_uint64();
128 if (R & 1) {
129 if (R != 1)
130 return -(int64_t)(R >> 1);
131 else // There is no such thing as -0 with integers. "-0" really means
132 // 0x8000000000000000.
133 return 1LL << 63;
134 } else
135 return (int64_t)(R >> 1);
136}
137
Reid Spencer04cde2c2004-07-04 11:33:49 +0000138/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000139inline std::string BytecodeReader::read_str() {
140 unsigned Size = read_vbr_uint();
141 const unsigned char *OldAt = At;
142 At += Size;
143 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000144 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000145 return std::string((char*)OldAt, Size);
146}
147
Reid Spencer04cde2c2004-07-04 11:33:49 +0000148/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000149inline void BytecodeReader::read_data(void *Ptr, void *End) {
150 unsigned char *Start = (unsigned char *)Ptr;
151 unsigned Amount = (unsigned char *)End - Start;
152 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000153 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000154 std::copy(At, At+Amount, Start);
155 At += Amount;
156}
157
Reid Spencer46b002c2004-07-11 17:28:43 +0000158/// Read a float value in little-endian order
159inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000160 /// FIXME: This isn't optimal, it has size problems on some platforms
161 /// where FP is not IEEE.
162 union {
163 float f;
164 uint32_t i;
165 } FloatUnion;
166 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
167 At+=sizeof(uint32_t);
168 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000169}
170
171/// Read a double value in little-endian order
172inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000173 /// FIXME: This isn't optimal, it has size problems on some platforms
174 /// where FP is not IEEE.
175 union {
176 double d;
177 uint64_t i;
178 } DoubleUnion;
Chris Lattner1d785162004-07-25 23:15:44 +0000179 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
180 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Reid Spencerada16182004-07-25 21:36:26 +0000181 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
182 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
183 At+=sizeof(uint64_t);
184 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000185}
186
Reid Spencer04cde2c2004-07-04 11:33:49 +0000187/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000188inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000189 if ( hasLongBlockHeaders ) {
190 Type = read_uint();
191 Size = read_uint();
192 switch (Type) {
193 case BytecodeFormat::Reserved_DoNotUse :
194 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000195 Type = BytecodeFormat::ModuleBlockID; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000196 case BytecodeFormat::Module:
197 Type = BytecodeFormat::ModuleBlockID; break;
198 case BytecodeFormat::Function:
199 Type = BytecodeFormat::FunctionBlockID; break;
200 case BytecodeFormat::ConstantPool:
201 Type = BytecodeFormat::ConstantPoolBlockID; break;
202 case BytecodeFormat::SymbolTable:
203 Type = BytecodeFormat::SymbolTableBlockID; break;
204 case BytecodeFormat::ModuleGlobalInfo:
205 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
206 case BytecodeFormat::GlobalTypePlane:
207 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
208 case BytecodeFormat::InstructionList:
209 Type = BytecodeFormat::InstructionListBlockID; break;
210 case BytecodeFormat::CompactionTable:
211 Type = BytecodeFormat::CompactionTableBlockID; break;
212 case BytecodeFormat::BasicBlock:
213 /// This block type isn't used after version 1.1. However, we have to
214 /// still allow the value in case this is an old bc format file.
215 /// We just let its value creep thru.
216 break;
217 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000218 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000219 break;
220 }
221 } else {
222 Size = read_uint();
223 Type = Size & 0x1F; // mask low order five bits
224 Size >>= 5; // get rid of five low order bits, leaving high 27
225 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000226 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000227 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000228 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000229 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000230 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000231}
232
233
234/// In LLVM 1.2 and before, Types were derived from Value and so they were
235/// written as part of the type planes along with any other Value. In LLVM
236/// 1.3 this changed so that Type does not derive from Value. Consequently,
237/// the BytecodeReader's containers for Values can't contain Types because
238/// there's no inheritance relationship. This means that the "Type Type"
239/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
240/// whenever a bytecode construct must have both types and values together,
241/// the types are always read/written first and then the Values. Furthermore
242/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
243/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
244/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
245/// For LLVM 1.2 and before, this function will decrement the type id by
246/// one to account for the missing Type::TypeTyID enumerator if the value is
247/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
248/// function returns true, otherwise false. This helps detect situations
249/// where the pre 1.3 bytecode is indicating that what follows is a type.
250/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000251inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
252 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
253 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000254 TypeId = Type::VoidTyID; // sanitize it
255 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000256 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000257 --TypeId; // shift all planes down because type type plane is missing
258 }
259 return false;
260}
261
262/// Reads a vbr uint to read in a type id and does the necessary
263/// conversion on it by calling sanitizeTypeId.
264/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
265/// @see sanitizeTypeId
266inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
267 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000268 if ( !has32BitTypes )
269 if ( TypeId == 0x00FFFFFF )
270 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000271 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000272}
273
274//===----------------------------------------------------------------------===//
275// IR Lookup Methods
276//===----------------------------------------------------------------------===//
277
Reid Spencer04cde2c2004-07-04 11:33:49 +0000278/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000279inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000280 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000281 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000282 return TyID >= Type::FirstDerivedTyID;
283}
284
Reid Spencer04cde2c2004-07-04 11:33:49 +0000285/// Obtain a type given a typeid and account for things like compaction tables,
286/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000287const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000288 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000289 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000290 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000291
292 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000293 ID -= Type::FirstDerivedTyID;
294
Reid Spencer060d25d2004-06-29 23:29:38 +0000295 if (!CompactionTypes.empty()) {
296 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000297 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000298 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000299 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000300
301 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000302 if (ID < ModuleTypes.size())
303 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000304
Reid Spencer46b002c2004-07-11 17:28:43 +0000305 // Nope, is it a function-level type?
306 ID -= ModuleTypes.size();
307 if (ID < FunctionTypes.size())
308 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000309
Reid Spencer46b002c2004-07-11 17:28:43 +0000310 error("Illegal type reference!");
311 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000312}
313
Reid Spencer04cde2c2004-07-04 11:33:49 +0000314/// Get a sanitized type id. This just makes sure that the \p ID
315/// is both sanitized and not the "type type" of pre-1.3 bytecode.
316/// @see sanitizeTypeId
317inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000318 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000319 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000320 return getType(ID);
321}
322
323/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000324/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000325/// then calls getType to return the type value.
326inline const Type* BytecodeReader::readSanitizedType() {
327 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000328 if (read_typeid(ID))
329 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000330 return getType(ID);
331}
332
333/// Get the slot number associated with a type accounting for primitive
334/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000335unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
336 if (Ty->isPrimitiveType())
337 return Ty->getTypeID();
338
339 // Scan the compaction table for the type if needed.
340 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000341 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
342 if (CompactionTypes[i].first == Ty)
343 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000344
Chris Lattner45b5dd22004-08-03 23:41:28 +0000345 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000346 }
347
348 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000349 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
350 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000351
352 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000353 return Type::FirstDerivedTyID + ModuleTypes.size() +
354 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000355
356 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000357 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000358 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000359 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000360 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000361}
362
Reid Spencer04cde2c2004-07-04 11:33:49 +0000363/// This is just like getType, but when a compaction table is in use, it is
364/// ignored. It also ignores function level types.
365/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000366const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
367 if (Slot < Type::FirstDerivedTyID) {
368 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000369 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000370 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000371 return Ty;
372 }
373 Slot -= Type::FirstDerivedTyID;
374 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000375 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000376 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000377}
378
Reid Spencer04cde2c2004-07-04 11:33:49 +0000379/// This is just like getTypeSlot, but when a compaction table is in use, it
380/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000381unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
382 if (Ty->isPrimitiveType())
383 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000384 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000385 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000386 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000387 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000388 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
389}
390
Reid Spencer04cde2c2004-07-04 11:33:49 +0000391/// Retrieve a value of a given type and slot number, possibly creating
392/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000393Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000394 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000395 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000396
Chris Lattner89e02532004-01-18 21:08:15 +0000397 // If there is a compaction table active, it defines the low-level numbers.
398 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000399 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
400 if (Num < CompactionValues[type].size())
401 return CompactionValues[type][Num];
402 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000403 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000404 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000405 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000406
Chris Lattner45b5dd22004-08-03 23:41:28 +0000407 // If the type plane was compactified, figure out the global type ID by
408 // adding the derived type ids and the distance.
409 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
410 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000411
Reid Spencer060d25d2004-06-29 23:29:38 +0000412 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000413 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000414 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000415 --Num;
416 }
417
Chris Lattner52f86d62004-01-20 00:54:06 +0000418 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
419 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000420 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000421 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000422 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000423 }
424
Reid Spencer060d25d2004-06-29 23:29:38 +0000425 if (FunctionValues.size() > type &&
426 FunctionValues[type] &&
427 Num < FunctionValues[type]->size())
428 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000429
Chris Lattner74734132002-08-17 22:01:27 +0000430 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000431
Reid Spencer551ccae2004-09-01 22:55:40 +0000432 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000433 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000434 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000435 if (I != ForwardReferences.end() && I->first == KeyValue)
436 return I->second; // We have already created this placeholder
437
Reid Spencer551ccae2004-09-01 22:55:40 +0000438 // If the type exists (it should)
439 if (const Type* Ty = getType(type)) {
440 // Create the place holder
441 Value *Val = new Argument(Ty);
442 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
443 return Val;
444 }
445 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000446}
447
Reid Spencer04cde2c2004-07-04 11:33:49 +0000448/// This is just like getValue, but when a compaction table is in use, it
449/// is ignored. Also, no forward references or other fancy features are
450/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000451Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
452 if (SlotNo == 0)
453 return Constant::getNullValue(getType(TyID));
454
455 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
456 TyID -= Type::FirstDerivedTyID;
457 if (TyID >= CompactionTypes.size())
458 error("Type ID out of range for compaction table!");
459 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000460 }
461
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000462 --SlotNo;
463
Reid Spencer060d25d2004-06-29 23:29:38 +0000464 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
465 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000466 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
467 error("Corrupt compaction table entry!"
468 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
469 + utostr(ModuleValues.size()));
470 else
471 error("Corrupt compaction table entry!"
472 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
473 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000474 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
475 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000476 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000477 }
478 return ModuleValues[TyID]->getOperand(SlotNo);
479}
480
Reid Spencer04cde2c2004-07-04 11:33:49 +0000481/// Just like getValue, except that it returns a null pointer
482/// only on error. It always returns a constant (meaning that if the value is
483/// defined, but is not a constant, that is an error). If the specified
484/// constant hasn't been parsed yet, a placeholder is defined and used.
485/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000486Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
487 if (Value *V = getValue(TypeSlot, Slot, false))
488 if (Constant *C = dyn_cast<Constant>(V))
489 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000490 else
Reid Spencera86037e2004-07-18 00:12:03 +0000491 error("Value for slot " + utostr(Slot) +
492 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000493
Chris Lattner389bd042004-12-09 06:19:44 +0000494 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000495 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
496
497 if (I != ConstantFwdRefs.end() && I->first == Key) {
498 return I->second;
499 } else {
500 // Create a placeholder for the constant reference and
501 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000502 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Reid Spencer060d25d2004-06-29 23:29:38 +0000503
504 // Keep track of the fact that we have a forward ref to recycle it
505 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
506 return C;
507 }
508}
509
510//===----------------------------------------------------------------------===//
511// IR Construction Methods
512//===----------------------------------------------------------------------===//
513
Reid Spencer04cde2c2004-07-04 11:33:49 +0000514/// As values are created, they are inserted into the appropriate place
515/// with this method. The ValueTable argument must be one of ModuleValues
516/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000517unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
518 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000519 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000520 !hasImplicitNull(type) &&
521 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000522
523 if (ValueTab.size() <= type)
524 ValueTab.resize(type+1);
525
526 if (!ValueTab[type]) ValueTab[type] = new ValueList();
527
528 ValueTab[type]->push_back(Val);
529
530 bool HasOffset = hasImplicitNull(type);
531 return ValueTab[type]->size()-1 + HasOffset;
532}
533
Reid Spencer04cde2c2004-07-04 11:33:49 +0000534/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000535void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000536 const FunctionType *FT = F->getFunctionType();
537 Function::aiterator AI = F->abegin();
538 for (FunctionType::param_iterator It = FT->param_begin();
539 It != FT->param_end(); ++It, ++AI)
540 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
541}
542
543//===----------------------------------------------------------------------===//
544// Bytecode Parsing Methods
545//===----------------------------------------------------------------------===//
546
Reid Spencer04cde2c2004-07-04 11:33:49 +0000547/// This method parses a single instruction. The instruction is
548/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000549/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000550void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000551 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000552 BufPtr SaveAt = At;
553
554 // Clear instruction data
555 Oprnds.clear();
556 unsigned iType = 0;
557 unsigned Opcode = 0;
558 unsigned Op = read_uint();
559
560 // bits Instruction format: Common to all formats
561 // --------------------------
562 // 01-00: Opcode type, fixed to 1.
563 // 07-02: Opcode
564 Opcode = (Op >> 2) & 63;
565 Oprnds.resize((Op >> 0) & 03);
566
567 // Extract the operands
568 switch (Oprnds.size()) {
569 case 1:
570 // bits Instruction format:
571 // --------------------------
572 // 19-08: Resulting type plane
573 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
574 //
575 iType = (Op >> 8) & 4095;
576 Oprnds[0] = (Op >> 20) & 4095;
577 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
578 Oprnds.resize(0);
579 break;
580 case 2:
581 // bits Instruction format:
582 // --------------------------
583 // 15-08: Resulting type plane
584 // 23-16: Operand #1
585 // 31-24: Operand #2
586 //
587 iType = (Op >> 8) & 255;
588 Oprnds[0] = (Op >> 16) & 255;
589 Oprnds[1] = (Op >> 24) & 255;
590 break;
591 case 3:
592 // bits Instruction format:
593 // --------------------------
594 // 13-08: Resulting type plane
595 // 19-14: Operand #1
596 // 25-20: Operand #2
597 // 31-26: Operand #3
598 //
599 iType = (Op >> 8) & 63;
600 Oprnds[0] = (Op >> 14) & 63;
601 Oprnds[1] = (Op >> 20) & 63;
602 Oprnds[2] = (Op >> 26) & 63;
603 break;
604 case 0:
605 At -= 4; // Hrm, try this again...
606 Opcode = read_vbr_uint();
607 Opcode >>= 2;
608 iType = read_vbr_uint();
609
610 unsigned NumOprnds = read_vbr_uint();
611 Oprnds.resize(NumOprnds);
612
613 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000614 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000615
616 for (unsigned i = 0; i != NumOprnds; ++i)
617 Oprnds[i] = read_vbr_uint();
618 align32();
619 break;
620 }
621
Reid Spencer04cde2c2004-07-04 11:33:49 +0000622 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000623
Reid Spencer46b002c2004-07-11 17:28:43 +0000624 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000625 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000626
627 // Declare the resulting instruction we'll build.
628 Instruction *Result = 0;
629
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000630 // If this is a bytecode format that did not include the unreachable
631 // instruction, bump up all opcodes numbers to make space.
632 if (hasNoUnreachableInst) {
633 if (Opcode >= Instruction::Unreachable &&
634 Opcode < 62) {
635 ++Opcode;
636 }
637 }
638
Reid Spencer060d25d2004-06-29 23:29:38 +0000639 // Handle binary operators
640 if (Opcode >= Instruction::BinaryOpsBegin &&
641 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
642 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
643 getValue(iType, Oprnds[0]),
644 getValue(iType, Oprnds[1]));
645
646 switch (Opcode) {
647 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000648 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000649 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000650 break;
651 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000652 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000653 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000654 break;
655 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000656 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000657 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000658 break;
659 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000660 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000661 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000662 break;
663 case Instruction::Select:
664 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
665 getValue(iType, Oprnds[1]),
666 getValue(iType, Oprnds[2]));
667 break;
668 case Instruction::PHI: {
669 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000670 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000671
672 PHINode *PN = new PHINode(InstTy);
673 PN->op_reserve(Oprnds.size());
674 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
675 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
676 Result = PN;
677 break;
678 }
679
680 case Instruction::Shl:
681 case Instruction::Shr:
682 Result = new ShiftInst((Instruction::OtherOps)Opcode,
683 getValue(iType, Oprnds[0]),
684 getValue(Type::UByteTyID, Oprnds[1]));
685 break;
686 case Instruction::Ret:
687 if (Oprnds.size() == 0)
688 Result = new ReturnInst();
689 else if (Oprnds.size() == 1)
690 Result = new ReturnInst(getValue(iType, Oprnds[0]));
691 else
Reid Spencer24399722004-07-09 22:21:33 +0000692 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000693 break;
694
695 case Instruction::Br:
696 if (Oprnds.size() == 1)
697 Result = new BranchInst(getBasicBlock(Oprnds[0]));
698 else if (Oprnds.size() == 3)
699 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000700 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000701 else
Reid Spencer24399722004-07-09 22:21:33 +0000702 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000703 break;
704 case Instruction::Switch: {
705 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000706 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000707
708 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
709 getBasicBlock(Oprnds[1]));
710 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
711 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
712 getBasicBlock(Oprnds[i+1]));
713 Result = I;
714 break;
715 }
716
717 case Instruction::Call: {
718 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000719 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000720
721 Value *F = getValue(iType, Oprnds[0]);
722
723 // Check to make sure we have a pointer to function type
724 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000725 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000726 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000727 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000728
729 std::vector<Value *> Params;
730 if (!FTy->isVarArg()) {
731 FunctionType::param_iterator It = FTy->param_begin();
732
733 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
734 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000735 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000736 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
737 }
738 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000739 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000740 } else {
741 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
742
743 unsigned FirstVariableOperand;
744 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000745 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000746
747 // Read all of the fixed arguments
748 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
749 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
750
751 FirstVariableOperand = FTy->getNumParams();
752
Chris Lattner4a242b32004-10-14 01:39:18 +0000753 if ((Oprnds.size()-FirstVariableOperand) & 1)
754 error("Invalid call instruction!"); // Must be pairs of type/value
Reid Spencer060d25d2004-06-29 23:29:38 +0000755
756 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000757 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000758 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
759 }
760
761 Result = new CallInst(F, Params);
762 break;
763 }
764 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000765 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000766 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000767 Value *F = getValue(iType, Oprnds[0]);
768
769 // Check to make sure we have a pointer to function type
770 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000771 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000772 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000773 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000774 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000775 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000776
777 std::vector<Value *> Params;
778 BasicBlock *Normal, *Except;
779
780 if (!FTy->isVarArg()) {
781 Normal = getBasicBlock(Oprnds[1]);
782 Except = getBasicBlock(Oprnds[2]);
783
784 FunctionType::param_iterator It = FTy->param_begin();
785 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
786 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000787 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000788 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
789 }
790 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000791 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000792 } else {
793 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
794
795 Normal = getBasicBlock(Oprnds[0]);
796 Except = getBasicBlock(Oprnds[1]);
797
798 unsigned FirstVariableArgument = FTy->getNumParams()+2;
799 for (unsigned i = 2; i != FirstVariableArgument; ++i)
800 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
801 Oprnds[i]));
802
803 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000804 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000805
806 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
807 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
808 }
809
810 Result = new InvokeInst(F, Normal, Except, Params);
811 break;
812 }
813 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000814 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000815 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000816 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000817 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000818
819 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
820 Oprnds.size() ? getValue(Type::UIntTyID,
821 Oprnds[0]) : 0);
822 break;
823
824 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000825 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000826 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000827 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000828 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000829
830 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
831 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000832 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000833 break;
834 case Instruction::Free:
835 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000836 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000837 Result = new FreeInst(getValue(iType, Oprnds[0]));
838 break;
839 case Instruction::GetElementPtr: {
840 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000841 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000842
843 std::vector<Value*> Idx;
844
845 const Type *NextTy = InstTy;
846 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
847 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000848 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000849 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000850
851 unsigned ValIdx = Oprnds[i];
852 unsigned IdxTy = 0;
853 if (!hasRestrictedGEPTypes) {
854 // Struct indices are always uints, sequential type indices can be any
855 // of the 32 or 64-bit integer types. The actual choice of type is
856 // encoded in the low two bits of the slot number.
857 if (isa<StructType>(TopTy))
858 IdxTy = Type::UIntTyID;
859 else {
860 switch (ValIdx & 3) {
861 default:
862 case 0: IdxTy = Type::UIntTyID; break;
863 case 1: IdxTy = Type::IntTyID; break;
864 case 2: IdxTy = Type::ULongTyID; break;
865 case 3: IdxTy = Type::LongTyID; break;
866 }
867 ValIdx >>= 2;
868 }
869 } else {
870 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
871 }
872
873 Idx.push_back(getValue(IdxTy, ValIdx));
874
875 // Convert ubyte struct indices into uint struct indices.
876 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
877 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
878 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
879
880 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
881 }
882
883 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
884 break;
885 }
886
887 case 62: // volatile load
888 case Instruction::Load:
889 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000890 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000891 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
892 break;
893
894 case 63: // volatile store
895 case Instruction::Store: {
896 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000897 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000898
899 Value *Ptr = getValue(iType, Oprnds[1]);
900 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
901 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
902 Opcode == 63);
903 break;
904 }
905 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000906 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000907 Result = new UnwindInst();
908 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000909 case Instruction::Unreachable:
910 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
911 Result = new UnreachableInst();
912 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000913 } // end switch(Opcode)
914
915 unsigned TypeSlot;
916 if (Result->getType() == InstTy)
917 TypeSlot = iType;
918 else
919 TypeSlot = getTypeSlot(Result->getType());
920
921 insertValue(Result, TypeSlot, FunctionValues);
922 BB->getInstList().push_back(Result);
923}
924
Reid Spencer04cde2c2004-07-04 11:33:49 +0000925/// Get a particular numbered basic block, which might be a forward reference.
926/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +0000927/// in a clean manner. This function is used when constructing phi, br, switch,
928/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +0000929/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000930BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000931 // Make sure there is room in the table...
932 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
933
934 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
935 // has already created this block, or if the forward reference has already
936 // been created.
937 if (ParsedBasicBlocks[ID])
938 return ParsedBasicBlocks[ID];
939
940 // Otherwise, the basic block has not yet been created. Do so and add it to
941 // the ParsedBasicBlocks list.
942 return ParsedBasicBlocks[ID] = new BasicBlock();
943}
944
Reid Spencer04cde2c2004-07-04 11:33:49 +0000945/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
946/// This method reads in one of the basicblock packets. This method is not used
947/// for bytecode files after LLVM 1.0
948/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000949BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
950 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000951
952 BasicBlock *BB = 0;
953
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000954 if (ParsedBasicBlocks.size() == BlockNo)
955 ParsedBasicBlocks.push_back(BB = new BasicBlock());
956 else if (ParsedBasicBlocks[BlockNo] == 0)
957 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
958 else
959 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000960
Reid Spencer060d25d2004-06-29 23:29:38 +0000961 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000962 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000963 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000964
Reid Spencer46b002c2004-07-11 17:28:43 +0000965 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000966 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000967}
968
Reid Spencer04cde2c2004-07-04 11:33:49 +0000969/// Parse all of the BasicBlock's & Instruction's in the body of a function.
970/// In post 1.0 bytecode files, we no longer emit basic block individually,
971/// in order to avoid per-basic-block overhead.
972/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000973unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000974 unsigned BlockNo = 0;
975 std::vector<unsigned> Args;
976
Reid Spencer46b002c2004-07-11 17:28:43 +0000977 while (moreInBlock()) {
978 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000979 BasicBlock *BB;
980 if (ParsedBasicBlocks.size() == BlockNo)
981 ParsedBasicBlocks.push_back(BB = new BasicBlock());
982 else if (ParsedBasicBlocks[BlockNo] == 0)
983 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
984 else
985 BB = ParsedBasicBlocks[BlockNo];
986 ++BlockNo;
987 F->getBasicBlockList().push_back(BB);
988
989 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000990 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000991 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000992
993 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000994 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000995
Reid Spencer46b002c2004-07-11 17:28:43 +0000996 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000997 }
998
999 return BlockNo;
1000}
1001
Reid Spencer04cde2c2004-07-04 11:33:49 +00001002/// Parse a symbol table. This works for both module level and function
1003/// level symbol tables. For function level symbol tables, the CurrentFunction
1004/// parameter must be non-zero and the ST parameter must correspond to
1005/// CurrentFunction's symbol table. For Module level symbol tables, the
1006/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001007void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001008 SymbolTable *ST) {
1009 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001010
Chris Lattner39cacce2003-10-10 05:43:47 +00001011 // Allow efficient basic block lookup by number.
1012 std::vector<BasicBlock*> BBMap;
1013 if (CurrentFunction)
1014 for (Function::iterator I = CurrentFunction->begin(),
1015 E = CurrentFunction->end(); I != E; ++I)
1016 BBMap.push_back(I);
1017
Reid Spencer04cde2c2004-07-04 11:33:49 +00001018 /// In LLVM 1.3 we write types separately from values so
1019 /// The types are always first in the symbol table. This is
1020 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001021 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001022 // Symtab block header: [num entries]
1023 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001024 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001025 // Symtab entry: [def slot #][name]
1026 unsigned slot = read_vbr_uint();
1027 std::string Name = read_str();
1028 const Type* T = getType(slot);
1029 ST->insert(Name, T);
1030 }
1031 }
1032
Reid Spencer46b002c2004-07-11 17:28:43 +00001033 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001034 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001035 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001036 unsigned Typ = 0;
1037 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001038 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001039
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001040 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001041 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001042 unsigned slot = read_vbr_uint();
1043 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001044
Reid Spencer04cde2c2004-07-04 11:33:49 +00001045 // if we're reading a pre 1.3 bytecode file and the type plane
1046 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001047 if (isTypeType) {
1048 const Type* T = getType(slot);
1049 if (T == 0)
1050 error("Failed type look-up for name '" + Name + "'");
1051 ST->insert(Name, T);
1052 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001053 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001054 Value *V = 0;
1055 if (Typ == Type::LabelTyID) {
1056 if (slot < BBMap.size())
1057 V = BBMap[slot];
1058 } else {
1059 V = getValue(Typ, slot, false); // Find mapping...
1060 }
1061 if (V == 0)
1062 error("Failed value look-up for name '" + Name + "'");
1063 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +00001064 }
Chris Lattner00950542001-06-06 20:29:01 +00001065 }
1066 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001067 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001068 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001069}
1070
Reid Spencer04cde2c2004-07-04 11:33:49 +00001071/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001072void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001073 for (unsigned i = 0; i != NumEntries; ++i) {
1074 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001075 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001076 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001077 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001078 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001079 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001080 }
1081}
1082
1083/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001084void BytecodeReader::ParseCompactionTable() {
1085
Reid Spencer46b002c2004-07-11 17:28:43 +00001086 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001087 if (Handler) Handler->handleCompactionTableBegin();
1088
Reid Spencer46b002c2004-07-11 17:28:43 +00001089 // In LLVM 1.3 Type no longer derives from Value. So,
1090 // we always write them first in the compaction table
1091 // because they can't occupy a "type plane" where the
1092 // Values reside.
1093 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001094 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001095 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001096 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001097
Reid Spencer46b002c2004-07-11 17:28:43 +00001098 // Compaction tables live in separate blocks so we have to loop
1099 // until we've read the whole thing.
1100 while (moreInBlock()) {
1101 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001102 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001103 unsigned Ty = 0;
1104 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001105
Reid Spencer46b002c2004-07-11 17:28:43 +00001106 // Decode the type from value read in. Most compaction table
1107 // planes will have one or two entries in them. If that's the
1108 // case then the length is encoded in the bottom two bits and
1109 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001110 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001111 // In this case, both low-order bits are set (value 3). This
1112 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001114 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001115 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001116 // In this case, the low-order bits specify the number of entries
1117 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001119 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001120 NumEntries &= 3;
1121 }
1122
Reid Spencer04cde2c2004-07-04 11:33:49 +00001123 // if we're reading a pre 1.3 bytecode file and the type plane
1124 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001125 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001126 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001127 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001128 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001129 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001130 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001131
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001132 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001133 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001134 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001135
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001136 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001137 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001138
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001139 // Push the implicit zero.
1140 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001141
1142 // Read in each of the entries, put them in the compaction table
1143 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001144 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001145 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001146 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001147 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001148 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001149 }
1150 }
1151 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001152 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001153 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001154}
1155
Reid Spencer46b002c2004-07-11 17:28:43 +00001156// Parse a single type. The typeid is read in first. If its a primitive type
1157// then nothing else needs to be read, we know how to instantiate it. If its
1158// a derived type, then additional data is read to fill out the type
1159// definition.
1160const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001161 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001162 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001163 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001164
1165 const Type *Result = 0;
1166 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1167 return Result;
1168
1169 switch (PrimType) {
1170 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001171 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001172
1173 unsigned NumParams = read_vbr_uint();
1174
1175 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001176 while (NumParams--)
1177 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001178
1179 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1180 if (isVarArg) Params.pop_back();
1181
1182 Result = FunctionType::get(RetType, Params, isVarArg);
1183 break;
1184 }
1185 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001186 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001187 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001188 Result = ArrayType::get(ElementType, NumElements);
1189 break;
1190 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001191 case Type::PackedTyID: {
1192 const Type *ElementType = readSanitizedType();
1193 unsigned NumElements = read_vbr_uint();
1194 Result = PackedType::get(ElementType, NumElements);
1195 break;
1196 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001197 case Type::StructTyID: {
1198 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001199 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001200 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001201 error("Invalid element type (type type) for structure!");
1202
Reid Spencer060d25d2004-06-29 23:29:38 +00001203 while (Typ) { // List is terminated by void/0 typeid
1204 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001205 if (read_typeid(Typ))
1206 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001207 }
1208
1209 Result = StructType::get(Elements);
1210 break;
1211 }
1212 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001213 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001214 break;
1215 }
1216
1217 case Type::OpaqueTyID: {
1218 Result = OpaqueType::get();
1219 break;
1220 }
1221
1222 default:
Reid Spencer24399722004-07-09 22:21:33 +00001223 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001224 break;
1225 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001226 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001227 return Result;
1228}
1229
Reid Spencer5b472d92004-08-21 20:49:23 +00001230// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001231// types. We know that recursive types will only reference the current slab of
1232// values in the type plane, but they can forward reference types before they
1233// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1234// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1235// this ugly problem, we pessimistically insert an opaque type for each type we
1236// are about to read. This means that forward references will resolve to
1237// something and when we reread the type later, we can replace the opaque type
1238// with a new resolved concrete type.
1239//
Reid Spencer46b002c2004-07-11 17:28:43 +00001240void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001241 assert(Tab.size() == 0 && "should not have read type constants in before!");
1242
1243 // Insert a bunch of opaque types to be resolved later...
1244 Tab.reserve(NumEntries);
1245 for (unsigned i = 0; i != NumEntries; ++i)
1246 Tab.push_back(OpaqueType::get());
1247
Reid Spencer5b472d92004-08-21 20:49:23 +00001248 if (Handler)
1249 Handler->handleTypeList(NumEntries);
1250
Reid Spencer060d25d2004-06-29 23:29:38 +00001251 // Loop through reading all of the types. Forward types will make use of the
1252 // opaque types just inserted.
1253 //
1254 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001255 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001256 const Type* OldTy = Tab[i].get();
1257 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001258 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001259
1260 // Don't directly push the new type on the Tab. Instead we want to replace
1261 // the opaque type we previously inserted with the new concrete value. This
1262 // approach helps with forward references to types. The refinement from the
1263 // abstract (opaque) type to the new type causes all uses of the abstract
1264 // type to use the concrete type (NewTy). This will also cause the opaque
1265 // type to be deleted.
1266 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1267
1268 // This should have replaced the old opaque type with the new type in the
1269 // value table... or with a preexisting type that was already in the system.
1270 // Let's just make sure it did.
1271 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1272 }
1273}
1274
Reid Spencer04cde2c2004-07-04 11:33:49 +00001275/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001276Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001277 // We must check for a ConstantExpr before switching by type because
1278 // a ConstantExpr can be of any type, and has no explicit value.
1279 //
1280 // 0 if not expr; numArgs if is expr
1281 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001282
Reid Spencer060d25d2004-06-29 23:29:38 +00001283 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001284 // 'undef' is encoded with 'exprnumargs' == 1.
1285 if (!hasNoUndefValue)
1286 if (--isExprNumArgs == 0)
1287 return UndefValue::get(getType(TypeID));
1288
Reid Spencer060d25d2004-06-29 23:29:38 +00001289 // FIXME: Encoding of constant exprs could be much more compact!
1290 std::vector<Constant*> ArgVec;
1291 ArgVec.reserve(isExprNumArgs);
1292 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001293
1294 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1295 if (hasNoUnreachableInst) Opcode++;
Reid Spencer060d25d2004-06-29 23:29:38 +00001296
1297 // Read the slot number and types of each of the arguments
1298 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1299 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001300 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001301 if (read_typeid(ArgTypeSlot))
1302 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001303
1304 // Get the arg value from its slot if it exists, otherwise a placeholder
1305 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1306 }
1307
1308 // Construct a ConstantExpr of the appropriate kind
1309 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001310 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001311 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001312
Reid Spencer060d25d2004-06-29 23:29:38 +00001313 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001314 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001315 return Result;
1316 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1317 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1318
1319 if (hasRestrictedGEPTypes) {
1320 const Type *BaseTy = ArgVec[0]->getType();
1321 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1322 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1323 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1324 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1325 if (isa<StructType>(*GTI)) {
1326 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001327 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001328 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1329 }
1330 }
1331
1332 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001333 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001334 return Result;
1335 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001336 if (ArgVec.size() != 3)
1337 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001338 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001339 ArgVec[2]);
1340 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001341 return Result;
1342 } else { // All other 2-operand expressions
1343 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001344 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 return Result;
1346 }
1347 }
1348
1349 // Ok, not an ConstantExpr. We now know how to read the given type...
1350 const Type *Ty = getType(TypeID);
1351 switch (Ty->getTypeID()) {
1352 case Type::BoolTyID: {
1353 unsigned Val = read_vbr_uint();
1354 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001355 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001356 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001357 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001358 return Result;
1359 }
1360
1361 case Type::UByteTyID: // Unsigned integer types...
1362 case Type::UShortTyID:
1363 case Type::UIntTyID: {
1364 unsigned Val = read_vbr_uint();
1365 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001366 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001367 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001368 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001369 return Result;
1370 }
1371
1372 case Type::ULongTyID: {
1373 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001374 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001375 return Result;
1376 }
1377
1378 case Type::SByteTyID: // Signed integer types...
1379 case Type::ShortTyID:
1380 case Type::IntTyID: {
1381 case Type::LongTyID:
1382 int64_t Val = read_vbr_int64();
1383 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001384 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001385 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001386 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001387 return Result;
1388 }
1389
1390 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001391 float Val;
1392 read_float(Val);
1393 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001395 return Result;
1396 }
1397
1398 case Type::DoubleTyID: {
1399 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001400 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001401 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001402 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 return Result;
1404 }
1405
Reid Spencer060d25d2004-06-29 23:29:38 +00001406 case Type::ArrayTyID: {
1407 const ArrayType *AT = cast<ArrayType>(Ty);
1408 unsigned NumElements = AT->getNumElements();
1409 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1410 std::vector<Constant*> Elements;
1411 Elements.reserve(NumElements);
1412 while (NumElements--) // Read all of the elements of the constant.
1413 Elements.push_back(getConstantValue(TypeSlot,
1414 read_vbr_uint()));
1415 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001416 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001417 return Result;
1418 }
1419
1420 case Type::StructTyID: {
1421 const StructType *ST = cast<StructType>(Ty);
1422
1423 std::vector<Constant *> Elements;
1424 Elements.reserve(ST->getNumElements());
1425 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1426 Elements.push_back(getConstantValue(ST->getElementType(i),
1427 read_vbr_uint()));
1428
1429 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001430 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001431 return Result;
1432 }
1433
Brian Gaeke715c90b2004-08-20 06:00:58 +00001434 case Type::PackedTyID: {
1435 const PackedType *PT = cast<PackedType>(Ty);
1436 unsigned NumElements = PT->getNumElements();
1437 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1438 std::vector<Constant*> Elements;
1439 Elements.reserve(NumElements);
1440 while (NumElements--) // Read all of the elements of the constant.
1441 Elements.push_back(getConstantValue(TypeSlot,
1442 read_vbr_uint()));
1443 Constant* Result = ConstantPacked::get(PT, Elements);
1444 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1445 return Result;
1446 }
1447
Chris Lattner638c3812004-11-19 16:24:05 +00001448 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001449 const PointerType *PT = cast<PointerType>(Ty);
1450 unsigned Slot = read_vbr_uint();
1451
1452 // Check to see if we have already read this global variable...
1453 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001454 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001455 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1456 if (!GV) error("GlobalValue not in ValueTable!");
1457 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1458 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001459 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001460 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001461 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 }
1463
1464 default:
Reid Spencer24399722004-07-09 22:21:33 +00001465 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001466 Ty->getDescription());
1467 break;
1468 }
Reid Spencer24399722004-07-09 22:21:33 +00001469 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001470}
1471
Reid Spencer04cde2c2004-07-04 11:33:49 +00001472/// Resolve references for constants. This function resolves the forward
1473/// referenced constants in the ConstantFwdRefs map. It uses the
1474/// replaceAllUsesWith method of Value class to substitute the placeholder
1475/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001476void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1477 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001478 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001479 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001480 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001481
Chris Lattner29b789b2003-11-19 17:27:18 +00001482 Value *PH = I->second; // Get the placeholder...
1483 PH->replaceAllUsesWith(NewV);
1484 delete PH; // Delete the old placeholder
1485 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001486}
1487
Reid Spencer04cde2c2004-07-04 11:33:49 +00001488/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001489void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1490 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001491 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001492 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001493 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001494 const Type *Ty = getType(Typ);
1495 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001496 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001497
1498 const ArrayType *ATy = cast<ArrayType>(Ty);
1499 if (ATy->getElementType() != Type::SByteTy &&
1500 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001501 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001502
1503 // Read character data. The type tells us how long the string is.
1504 char Data[ATy->getNumElements()];
1505 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001506
Reid Spencer060d25d2004-06-29 23:29:38 +00001507 std::vector<Constant*> Elements(ATy->getNumElements());
1508 if (ATy->getElementType() == Type::SByteTy)
1509 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1510 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1511 else
1512 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1513 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001514
Reid Spencer060d25d2004-06-29 23:29:38 +00001515 // Create the constant, inserting it as needed.
1516 Constant *C = ConstantArray::get(ATy, Elements);
1517 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001518 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001519 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001520 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001521}
1522
Reid Spencer04cde2c2004-07-04 11:33:49 +00001523/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001524void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001525 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001526 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001527 if (Handler) Handler->handleGlobalConstantsBegin();
1528
1529 /// In LLVM 1.3 Type does not derive from Value so the types
1530 /// do not occupy a plane. Consequently, we read the types
1531 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001532 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001533 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001534 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001535 }
1536
Reid Spencer46b002c2004-07-11 17:28:43 +00001537 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001538 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001539 unsigned Typ = 0;
1540 bool isTypeType = read_typeid(Typ);
1541
1542 /// In LLVM 1.2 and before, Types were written to the
1543 /// bytecode file in the "Type Type" plane (#12).
1544 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001545 if (isTypeType) {
1546 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001547 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001548 /// Use of Type::VoidTyID is a misnomer. It actually means
1549 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001550 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1551 ParseStringConstants(NumEntries, Tab);
1552 } else {
1553 for (unsigned i = 0; i < NumEntries; ++i) {
1554 Constant *C = ParseConstantValue(Typ);
1555 assert(C && "ParseConstantValue returned NULL!");
1556 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001557
Reid Spencer060d25d2004-06-29 23:29:38 +00001558 // If we are reading a function constant table, make sure that we adjust
1559 // the slot number to be the real global constant number.
1560 //
1561 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1562 ModuleValues[Typ])
1563 Slot += ModuleValues[Typ]->size();
Chris Lattner389bd042004-12-09 06:19:44 +00001564 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001565 }
1566 }
1567 }
Chris Lattner02dce162004-12-04 05:28:27 +00001568
1569 // After we have finished parsing the constant pool, we had better not have
1570 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001571 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001572 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001573 Constant* missingConst = I->second;
1574 error(utostr(ConstantFwdRefs.size()) +
1575 " unresolved constant reference exist. First one is '" +
1576 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001577 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001578 }
Chris Lattner02dce162004-12-04 05:28:27 +00001579
Reid Spencer060d25d2004-06-29 23:29:38 +00001580 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001581 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001582}
Chris Lattner00950542001-06-06 20:29:01 +00001583
Reid Spencer04cde2c2004-07-04 11:33:49 +00001584/// Parse the contents of a function. Note that this function can be
1585/// called lazily by materializeFunction
1586/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001587void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001588
1589 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001590 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1591
Reid Spencer060d25d2004-06-29 23:29:38 +00001592 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001593 switch (LinkageType) {
1594 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1595 case 1: Linkage = GlobalValue::WeakLinkage; break;
1596 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1597 case 3: Linkage = GlobalValue::InternalLinkage; break;
1598 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001599 default:
Reid Spencer24399722004-07-09 22:21:33 +00001600 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001601 Linkage = GlobalValue::InternalLinkage;
1602 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001603 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001604
Reid Spencer46b002c2004-07-11 17:28:43 +00001605 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001606 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001607
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001608 // Keep track of how many basic blocks we have read in...
1609 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001610 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001611
Reid Spencer060d25d2004-06-29 23:29:38 +00001612 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001613 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001614 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001615 BufPtr OldAt = At;
1616 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001617
1618 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001619 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001620 if (!InsertedArguments) {
1621 // Insert arguments into the value table before we parse the first basic
1622 // block in the function, but after we potentially read in the
1623 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001624 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001625 InsertedArguments = true;
1626 }
1627
Reid Spencer04cde2c2004-07-04 11:33:49 +00001628 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001629 break;
1630
Reid Spencerad89bd62004-07-25 18:07:36 +00001631 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001632 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001633 break;
1634
Chris Lattner00950542001-06-06 20:29:01 +00001635 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001636 if (!InsertedArguments) {
1637 // Insert arguments into the value table before we parse the first basic
1638 // block in the function, but after we potentially read in the
1639 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001640 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001641 InsertedArguments = true;
1642 }
1643
Reid Spencer060d25d2004-06-29 23:29:38 +00001644 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001645 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001646 break;
1647 }
1648
Reid Spencerad89bd62004-07-25 18:07:36 +00001649 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001650 // Insert arguments into the value table before we parse the instruction
1651 // list for the function, but after we potentially read in the compaction
1652 // table.
1653 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001654 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001655 InsertedArguments = true;
1656 }
1657
Reid Spencer060d25d2004-06-29 23:29:38 +00001658 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001659 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001660 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001661 break;
1662 }
1663
Reid Spencerad89bd62004-07-25 18:07:36 +00001664 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001665 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001666 break;
1667
1668 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001669 At += Size;
1670 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001671 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001672 break;
1673 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001674 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001675
Misha Brukman12c29d12003-09-22 23:38:23 +00001676 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001677 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001678 }
1679
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001680 // Make sure there were no references to non-existant basic blocks.
1681 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001682 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001683
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001684 ParsedBasicBlocks.clear();
1685
Chris Lattner97330cf2003-10-09 23:10:14 +00001686 // Resolve forward references. Replace any uses of a forward reference value
1687 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001688 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001689 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1690 I = ForwardReferences.begin();
1691 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001692 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001693 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001694 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001695 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001696 }
Chris Lattner00950542001-06-06 20:29:01 +00001697
Misha Brukman12c29d12003-09-22 23:38:23 +00001698 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001699 FunctionTypes.clear();
1700 CompactionTypes.clear();
1701 CompactionValues.clear();
1702 freeTable(FunctionValues);
1703
Reid Spencer04cde2c2004-07-04 11:33:49 +00001704 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001705}
1706
Reid Spencer04cde2c2004-07-04 11:33:49 +00001707/// This function parses LLVM functions lazily. It obtains the type of the
1708/// function and records where the body of the function is in the bytecode
1709/// buffer. The caller can then use the ParseNextFunction and
1710/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001711void BytecodeReader::ParseFunctionLazily() {
1712 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001713 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001714
Reid Spencer060d25d2004-06-29 23:29:38 +00001715 Function *Func = FunctionSignatureList.back();
1716 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001717
Reid Spencer060d25d2004-06-29 23:29:38 +00001718 // Save the information for future reading of the function
1719 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001720
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001721 // This function has a body but it's not loaded so it appears `External'.
1722 // Mark it as a `Ghost' instead to notify the users that it has a body.
1723 Func->setLinkage(GlobalValue::GhostLinkage);
1724
Reid Spencer060d25d2004-06-29 23:29:38 +00001725 // Pretend we've `parsed' this function
1726 At = BlockEnd;
1727}
Chris Lattner89e02532004-01-18 21:08:15 +00001728
Reid Spencer04cde2c2004-07-04 11:33:49 +00001729/// The ParserFunction method lazily parses one function. Use this method to
1730/// casue the parser to parse a specific function in the module. Note that
1731/// this will remove the function from what is to be included by
1732/// ParseAllFunctionBodies.
1733/// @see ParseAllFunctionBodies
1734/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001735void BytecodeReader::ParseFunction(Function* Func) {
1736 // Find {start, end} pointers and slot in the map. If not there, we're done.
1737 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001738
Reid Spencer060d25d2004-06-29 23:29:38 +00001739 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001740 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001741 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001742 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001743 }
1744
Reid Spencer060d25d2004-06-29 23:29:38 +00001745 BlockStart = At = Fi->second.Buf;
1746 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001747 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001748
1749 LazyFunctionLoadMap.erase(Fi);
1750
Reid Spencer46b002c2004-07-11 17:28:43 +00001751 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001752}
1753
Reid Spencer04cde2c2004-07-04 11:33:49 +00001754/// The ParseAllFunctionBodies method parses through all the previously
1755/// unparsed functions in the bytecode file. If you want to completely parse
1756/// a bytecode file, this method should be called after Parsebytecode because
1757/// Parsebytecode only records the locations in the bytecode file of where
1758/// the function definitions are located. This function uses that information
1759/// to materialize the functions.
1760/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001761void BytecodeReader::ParseAllFunctionBodies() {
1762 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1763 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001764
Reid Spencer46b002c2004-07-11 17:28:43 +00001765 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001766 Function* Func = Fi->first;
1767 BlockStart = At = Fi->second.Buf;
1768 BlockEnd = Fi->second.EndBuf;
1769 this->ParseFunctionBody(Func);
1770 ++Fi;
1771 }
1772}
Chris Lattner89e02532004-01-18 21:08:15 +00001773
Reid Spencer04cde2c2004-07-04 11:33:49 +00001774/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001775void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001776 // Read the number of types
1777 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001778
1779 // Ignore the type plane identifier for types if the bc file is pre 1.3
1780 if (hasTypeDerivedFromValue)
1781 read_vbr_uint();
1782
Reid Spencer46b002c2004-07-11 17:28:43 +00001783 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001784}
1785
Reid Spencer04cde2c2004-07-04 11:33:49 +00001786/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001787void BytecodeReader::ParseModuleGlobalInfo() {
1788
Reid Spencer04cde2c2004-07-04 11:33:49 +00001789 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001790
Chris Lattner70cc3392001-09-10 07:58:01 +00001791 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001792 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001793 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001794 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1795 // Linkage, bit4+ = slot#
1796 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001797 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001798 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001799 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001800 bool isConstant = VarType & 1;
1801 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001802 GlobalValue::LinkageTypes Linkage;
1803
Chris Lattnerc08912f2004-01-14 16:44:44 +00001804 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001805 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1806 case 1: Linkage = GlobalValue::WeakLinkage; break;
1807 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1808 case 3: Linkage = GlobalValue::InternalLinkage; break;
1809 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001810 default:
Reid Spencer24399722004-07-09 22:21:33 +00001811 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001812 Linkage = GlobalValue::InternalLinkage;
1813 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001814 }
1815
1816 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001817 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001818 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001819 }
1820
Reid Spencer46b002c2004-07-11 17:28:43 +00001821 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001822 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001823 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001824
Chris Lattner52e20b02003-03-19 20:54:26 +00001825 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001826
Chris Lattner70cc3392001-09-10 07:58:01 +00001827 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001828 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001829 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001830 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001831
Reid Spencer060d25d2004-06-29 23:29:38 +00001832 unsigned initSlot = 0;
1833 if (hasInitializer) {
1834 initSlot = read_vbr_uint();
1835 GlobalInits.push_back(std::make_pair(GV, initSlot));
1836 }
1837
1838 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001839 if (Handler)
1840 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001841
1842 // Get next item
1843 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001844 }
1845
Chris Lattner52e20b02003-03-19 20:54:26 +00001846 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001847 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001848
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001849 if (hasNoFlagsForFunctions)
1850 FnSignature = (FnSignature << 5) + 1;
1851
1852 // List is terminated by VoidTy.
1853 while ((FnSignature >> 5) != Type::VoidTyID) {
1854 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001855 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001856 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001857 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001858 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001859 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001860
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001861 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001862 const FunctionType* FTy =
1863 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001864
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001865
Chris Lattner18549c22004-11-15 21:43:03 +00001866 // Insert the place holder.
1867 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001868 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001869 insertValue(Func, FnSignature >> 5, ModuleValues);
1870
1871 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001872 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001873
Chris Lattner97fbc502004-11-15 22:38:52 +00001874 // Save this for later so we know type of lazily instantiated functions.
1875 // Note that known-external functions do not have FunctionInfo blocks, so we
1876 // do not add them to the FunctionSignatureList.
1877 if ((Flags & (1 << 4)) == 0)
1878 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001879
Reid Spencer04cde2c2004-07-04 11:33:49 +00001880 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001881
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001882 // Get the next function signature.
1883 FnSignature = read_vbr_uint();
1884 if (hasNoFlagsForFunctions)
1885 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001886 }
1887
Chris Lattner74734132002-08-17 22:01:27 +00001888 // Now that the function signature list is set up, reverse it so that we can
1889 // remove elements efficiently from the back of the vector.
1890 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001891
Reid Spencerad89bd62004-07-25 18:07:36 +00001892 // If this bytecode format has dependent library information in it ..
1893 if (!hasNoDependentLibraries) {
1894 // Read in the number of dependent library items that follow
1895 unsigned num_dep_libs = read_vbr_uint();
1896 std::string dep_lib;
1897 while( num_dep_libs-- ) {
1898 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001899 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001900 if (Handler)
1901 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001902 }
1903
Reid Spencer5b472d92004-08-21 20:49:23 +00001904
Reid Spencerad89bd62004-07-25 18:07:36 +00001905 // Read target triple and place into the module
1906 std::string triple = read_str();
1907 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001908 if (Handler)
1909 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001910 }
1911
1912 if (hasInconsistentModuleGlobalInfo)
1913 align32();
1914
Chris Lattner00950542001-06-06 20:29:01 +00001915 // This is for future proofing... in the future extra fields may be added that
1916 // we don't understand, so we transparently ignore them.
1917 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001918 At = BlockEnd;
1919
Reid Spencer04cde2c2004-07-04 11:33:49 +00001920 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001921}
1922
Reid Spencer04cde2c2004-07-04 11:33:49 +00001923/// Parse the version information and decode it by setting flags on the
1924/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001925void BytecodeReader::ParseVersionInfo() {
1926 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001927
1928 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001929 Module::Endianness Endianness;
1930 Module::PointerSize PointerSize;
1931 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1932 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1933
1934 bool hasNoEndianness = Version & 4;
1935 bool hasNoPointerSize = Version & 8;
1936
1937 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001938
1939 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001940 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001941 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001942 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001943 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001944 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001945 has32BitTypes = false;
1946 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00001947 hasAlignment = false;
Reid Spencer5b472d92004-08-21 20:49:23 +00001948 hasInconsistentBBSlotNums = false;
1949 hasVBRByteTypes = false;
1950 hasUnnecessaryModuleBlockId = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001951 hasNoUndefValue = false;
1952 hasNoFlagsForFunctions = false;
1953 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001954
1955 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00001956 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001957 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001958 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001959 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001960
Chris Lattner80b97342004-01-17 23:25:43 +00001961 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001962
1963 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001964 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001965
1966 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1967 // included the size for the alignment at the end, where the rest of the
1968 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001969
1970 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1971 // structures and longs for sequential types.
1972 hasRestrictedGEPTypes = true;
1973
Reid Spencer04cde2c2004-07-04 11:33:49 +00001974 // LLVM 1.2 and before had the Type class derive from Value class. This
1975 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1976 // written differently because Types can no longer be part of the
1977 // type planes for Values.
1978 hasTypeDerivedFromValue = true;
1979
Chris Lattner5fa428f2004-04-05 01:27:26 +00001980 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001981
Reid Spencer5b472d92004-08-21 20:49:23 +00001982 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00001983
Reid Spencer5b472d92004-08-21 20:49:23 +00001984 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00001985 // especially for small files where the 8 bytes per block is a large
1986 // fraction of the total block size. In LLVM 1.3, the block type and length
1987 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
1988 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00001989 hasLongBlockHeaders = true;
1990
Reid Spencer5b472d92004-08-21 20:49:23 +00001991 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00001992 // this has been reduced to vbr_uint24. It shouldn't make much difference
1993 // since we haven't run into a module with > 24 million types, but for
1994 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
1995 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00001996 has32BitTypes = true;
1997
Reid Spencer5b472d92004-08-21 20:49:23 +00001998 // LLVM 1.2 and earlier did not provide a target triple nor a list of
1999 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2000 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002001 hasNoDependentLibraries = true;
2002
2003 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002004
2005 case 3: // LLVM 1.3 (Released)
2006 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2007 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2008 // of GEP references to a constant array), this can increase the file size
2009 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002010 hasAlignment = true;
2011
2012 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002013
2014 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002015 // In version 4, we did not support the 'undef' constant.
2016 hasNoUndefValue = true;
2017
2018 // In version 4 and above, we did not include space for flags for functions
2019 // in the module info block.
2020 hasNoFlagsForFunctions = true;
2021
2022 // In version 4 and above, we did not include the 'unreachable' instruction
2023 // in the opcode numbering in the bytecode file.
2024 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002025 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002026
2027 // FALL THROUGH
2028
2029 case 5: // 1.x.x (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002030 break;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002031 // FIXME: NONE of this is implemented yet!
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002032
2033 // In version 5, basic blocks have a minimum index of 0 whereas all the
Reid Spencer5b472d92004-08-21 20:49:23 +00002034 // other primitives have a minimum index of 1 (because 0 is the "null"
2035 // value. In version 5, we made this consistent.
2036 hasInconsistentBBSlotNums = true;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002037
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002038 // In version 5, the types SByte and UByte were encoded as vbr_uint so that
Reid Spencer5b472d92004-08-21 20:49:23 +00002039 // signed values > 63 and unsigned values >127 would be encoded as two
2040 // bytes. In version 5, they are encoded directly in a single byte.
2041 hasVBRByteTypes = true;
2042
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002043 // In version 5, modules begin with a "Module Block" which encodes a 4-byte
Reid Spencer5b472d92004-08-21 20:49:23 +00002044 // integer value 0x01 to identify the module block. This is unnecessary and
2045 // removed in version 5.
2046 hasUnnecessaryModuleBlockId = true;
2047
Chris Lattner036b8aa2003-03-06 17:55:45 +00002048 default:
Reid Spencer24399722004-07-09 22:21:33 +00002049 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002050 }
2051
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002052 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2053 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002054
Brian Gaekefe2102b2004-07-14 20:33:13 +00002055 TheModule->setEndianness(Endianness);
2056 TheModule->setPointerSize(PointerSize);
2057
Reid Spencer46b002c2004-07-11 17:28:43 +00002058 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002059}
2060
Reid Spencer04cde2c2004-07-04 11:33:49 +00002061/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002062void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002063 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002064
Reid Spencer060d25d2004-06-29 23:29:38 +00002065 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002066
2067 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002068 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002069 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002070
Reid Spencer060d25d2004-06-29 23:29:38 +00002071 bool SeenModuleGlobalInfo = false;
2072 bool SeenGlobalTypePlane = false;
2073 BufPtr MyEnd = BlockEnd;
2074 while (At < MyEnd) {
2075 BufPtr OldAt = At;
2076 read_block(Type, Size);
2077
Chris Lattner00950542001-06-06 20:29:01 +00002078 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002079
Reid Spencerad89bd62004-07-25 18:07:36 +00002080 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002081 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002082 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002083
Reid Spencer5b472d92004-08-21 20:49:23 +00002084 if (Size > 0)
2085 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002086 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002087 break;
2088
Reid Spencerad89bd62004-07-25 18:07:36 +00002089 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002090 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002091 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002092 ParseModuleGlobalInfo();
2093 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002094 break;
2095
Reid Spencerad89bd62004-07-25 18:07:36 +00002096 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002097 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002098 break;
2099
Reid Spencerad89bd62004-07-25 18:07:36 +00002100 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002101 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002102 break;
Chris Lattner00950542001-06-06 20:29:01 +00002103
Reid Spencerad89bd62004-07-25 18:07:36 +00002104 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002105 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002106 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002107
Chris Lattner00950542001-06-06 20:29:01 +00002108 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002109 At += Size;
2110 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002111 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002112 }
Chris Lattner00950542001-06-06 20:29:01 +00002113 break;
2114 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002115 BlockEnd = MyEnd;
2116 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002117 }
2118
Chris Lattner52e20b02003-03-19 20:54:26 +00002119 // After the module constant pool has been read, we can safely initialize
2120 // global variables...
2121 while (!GlobalInits.empty()) {
2122 GlobalVariable *GV = GlobalInits.back().first;
2123 unsigned Slot = GlobalInits.back().second;
2124 GlobalInits.pop_back();
2125
2126 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002127 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002128
2129 const llvm::PointerType* GVType = GV->getType();
2130 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002131 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002132 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002133 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002134 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002135 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002136 } else
Reid Spencer24399722004-07-09 22:21:33 +00002137 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002138 }
2139
Reid Spencer060d25d2004-06-29 23:29:38 +00002140 /// Make sure we pulled them all out. If we didn't then there's a declaration
2141 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002142 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002143 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002144}
2145
Reid Spencer04cde2c2004-07-04 11:33:49 +00002146/// This function completely parses a bytecode buffer given by the \p Buf
2147/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002148void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002149 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002150
Reid Spencer060d25d2004-06-29 23:29:38 +00002151 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002152 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002153 At = MemStart = BlockStart = Buf;
2154 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002155
Reid Spencer060d25d2004-06-29 23:29:38 +00002156 // Create the module
2157 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002158
Reid Spencer04cde2c2004-07-04 11:33:49 +00002159 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002160
Reid Spencerf0c977c2004-11-07 18:20:55 +00002161 // Read the four bytes of the signature.
2162 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002163
Reid Spencerf0c977c2004-11-07 18:20:55 +00002164 // If this is a compressed file
2165 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002166
Reid Spencerf0c977c2004-11-07 18:20:55 +00002167 // Invoke the decompression of the bytecode. Note that we have to skip the
2168 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002169 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2170 // member for retention until BytecodeReader is destructed.
2171 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2172 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002173
2174 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002175 // into the new decompressed block. After decompression, the
2176 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002177 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002178 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002179 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002180
Reid Spencerf0c977c2004-11-07 18:20:55 +00002181 // else if this isn't a regular (uncompressed) bytecode file, then its
2182 // and error, generate that now.
2183 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2184 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002185 }
2186
Reid Spencer060d25d2004-06-29 23:29:38 +00002187 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002188 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002189
Reid Spencerad89bd62004-07-25 18:07:36 +00002190 // Get the module block and size and verify. This is handled specially
2191 // because the module block/size is always written in long format. Other
2192 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002193 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002194 Type = read_uint();
2195 Size = read_uint();
2196 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002197 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002198 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002199 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002200
2201 // It looks like the darwin ranlib program is broken, and adds trailing
2202 // garbage to the end of some bytecode files. This hack allows the bc
2203 // reader to ignore trailing garbage on bytecode files.
2204 if (At + Size < MemEnd)
2205 MemEnd = BlockEnd = At+Size;
2206
2207 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002208 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002209 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002210
2211 // Parse the module contents
2212 this->ParseModule();
2213
Reid Spencer060d25d2004-06-29 23:29:38 +00002214 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002215 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002216 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002217
Reid Spencer5c15fe52004-07-05 00:57:50 +00002218 // Tell the handler we're done with the module
2219 if (Handler)
2220 Handler->handleModuleEnd(ModuleID);
2221
2222 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002223 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002224
Reid Spencer46b002c2004-07-11 17:28:43 +00002225 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002226 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002227 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002228 delete TheModule;
2229 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002230 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002231 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002232 decompressedBlock = 0;
2233 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002234 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002235 } catch (...) {
2236 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002237 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002238 freeState();
2239 delete TheModule;
2240 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002241 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002242 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002243 decompressedBlock = 0;
2244 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002245 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002246 }
Chris Lattner00950542001-06-06 20:29:01 +00002247}
Reid Spencer060d25d2004-06-29 23:29:38 +00002248
2249//===----------------------------------------------------------------------===//
2250//=== Default Implementations of Handler Methods
2251//===----------------------------------------------------------------------===//
2252
2253BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002254
2255// vim: sw=2