blob: abe11c828bea9eb3c19fec06803a67da3aa2a26d [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"
Misha Brukman12c29d12003-09-22 23:38:23 +000027#include "Support/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000028#include <sstream>
29
Chris Lattner29b789b2003-11-19 17:27:18 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Reid Spencer060d25d2004-06-29 23:29:38 +000032/// @brief A class for maintaining the slot number definition
33/// as a placeholder for the actual definition.
34template<class SuperType>
35class PlaceholderDef : public SuperType {
36 unsigned ID;
37 PlaceholderDef(); // DO NOT IMPLEMENT
38 void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
39public:
40 PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
41 unsigned getID() { return ID; }
42};
Chris Lattner9e460f22003-10-04 20:00:03 +000043
Reid Spencer060d25d2004-06-29 23:29:38 +000044struct ConstantPlaceHolderHelper : public ConstantExpr {
45 ConstantPlaceHolderHelper(const Type *Ty)
46 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty) {}
47};
48
49typedef PlaceholderDef<ConstantPlaceHolderHelper> ConstPHolder;
50
Reid Spencer24399722004-07-09 22:21:33 +000051// Provide some details on error
52inline void BytecodeReader::error(std::string err) {
53 err += " (Vers=" ;
54 err += itostr(RevisionNum) ;
55 err += ", Pos=" ;
56 err += itostr(At-MemStart);
57 err += ")";
58 throw err;
59}
60
Reid Spencer060d25d2004-06-29 23:29:38 +000061//===----------------------------------------------------------------------===//
62// Bytecode Reading Methods
63//===----------------------------------------------------------------------===//
64
Reid Spencer04cde2c2004-07-04 11:33:49 +000065/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000066inline bool BytecodeReader::moreInBlock() {
67 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000068}
69
Reid Spencer04cde2c2004-07-04 11:33:49 +000070/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000071inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
72 if ( At > BlockEnd )
Reid Spencer24399722004-07-09 22:21:33 +000073 error(std::string("Attempt to read past the end of ") + block_name + " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline void BytecodeReader::align32() {
78 BufPtr Save = At;
79 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
80 if ( At > Save )
Reid Spencer04cde2c2004-07-04 11:33:49 +000081 if (Handler) Handler->handleAlignment( At - Save );
Reid Spencer060d25d2004-06-29 23:29:38 +000082 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000083 error("Ran out of data while aligning!");
Reid Spencer060d25d2004-06-29 23:29:38 +000084}
85
Reid Spencer04cde2c2004-07-04 11:33:49 +000086/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000087inline unsigned BytecodeReader::read_uint() {
88 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000089 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000090 At += 4;
91 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
92}
93
Reid Spencer04cde2c2004-07-04 11:33:49 +000094/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000095inline unsigned BytecodeReader::read_vbr_uint() {
96 unsigned Shift = 0;
97 unsigned Result = 0;
98 BufPtr Save = At;
99
100 do {
101 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000102 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000103 Result |= (unsigned)((*At++) & 0x7F) << Shift;
104 Shift += 7;
105 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000106 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000107 return Result;
108}
109
Reid Spencer04cde2c2004-07-04 11:33:49 +0000110/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000111inline uint64_t BytecodeReader::read_vbr_uint64() {
112 unsigned Shift = 0;
113 uint64_t Result = 0;
114 BufPtr Save = At;
115
116 do {
117 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000118 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000119 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
120 Shift += 7;
121 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000122 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000123 return Result;
124}
125
Reid Spencer04cde2c2004-07-04 11:33:49 +0000126/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000127inline int64_t BytecodeReader::read_vbr_int64() {
128 uint64_t R = read_vbr_uint64();
129 if (R & 1) {
130 if (R != 1)
131 return -(int64_t)(R >> 1);
132 else // There is no such thing as -0 with integers. "-0" really means
133 // 0x8000000000000000.
134 return 1LL << 63;
135 } else
136 return (int64_t)(R >> 1);
137}
138
Reid Spencer04cde2c2004-07-04 11:33:49 +0000139/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000140inline std::string BytecodeReader::read_str() {
141 unsigned Size = read_vbr_uint();
142 const unsigned char *OldAt = At;
143 At += Size;
144 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000145 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000146 return std::string((char*)OldAt, Size);
147}
148
Reid Spencer04cde2c2004-07-04 11:33:49 +0000149/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000150inline void BytecodeReader::read_data(void *Ptr, void *End) {
151 unsigned char *Start = (unsigned char *)Ptr;
152 unsigned Amount = (unsigned char *)End - Start;
153 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000154 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000155 std::copy(At, At+Amount, Start);
156 At += Amount;
157}
158
Reid Spencer04cde2c2004-07-04 11:33:49 +0000159/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000160inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
161 Type = read_uint();
162 Size = read_uint();
163 BlockStart = At;
164 if ( At + Size > BlockEnd )
Reid Spencer24399722004-07-09 22:21:33 +0000165 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000166 BlockEnd = At + Size;
Reid Spencer04cde2c2004-07-04 11:33:49 +0000167 if (Handler) Handler->handleBlock( Type, BlockStart, Size );
168}
169
170
171/// In LLVM 1.2 and before, Types were derived from Value and so they were
172/// written as part of the type planes along with any other Value. In LLVM
173/// 1.3 this changed so that Type does not derive from Value. Consequently,
174/// the BytecodeReader's containers for Values can't contain Types because
175/// there's no inheritance relationship. This means that the "Type Type"
176/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
177/// whenever a bytecode construct must have both types and values together,
178/// the types are always read/written first and then the Values. Furthermore
179/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
180/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
181/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
182/// For LLVM 1.2 and before, this function will decrement the type id by
183/// one to account for the missing Type::TypeTyID enumerator if the value is
184/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
185/// function returns true, otherwise false. This helps detect situations
186/// where the pre 1.3 bytecode is indicating that what follows is a type.
187/// @returns true iff type id corresponds to pre 1.3 "type type"
188inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId ) {
189 if ( hasTypeDerivedFromValue ) { /// do nothing if 1.3 or later
190 if ( TypeId == Type::LabelTyID ) {
191 TypeId = Type::VoidTyID; // sanitize it
192 return true; // indicate we got TypeTyID in pre 1.3 bytecode
193 } else if ( TypeId > Type::LabelTyID )
194 --TypeId; // shift all planes down because type type plane is missing
195 }
196 return false;
197}
198
199/// Reads a vbr uint to read in a type id and does the necessary
200/// conversion on it by calling sanitizeTypeId.
201/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
202/// @see sanitizeTypeId
203inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
204 TypeId = read_vbr_uint();
205 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000206}
207
208//===----------------------------------------------------------------------===//
209// IR Lookup Methods
210//===----------------------------------------------------------------------===//
211
Reid Spencer04cde2c2004-07-04 11:33:49 +0000212/// Determine if a type id has an implicit null value
Reid Spencer060d25d2004-06-29 23:29:38 +0000213inline bool BytecodeReader::hasImplicitNull(unsigned TyID ) {
214 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000215 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000216 return TyID >= Type::FirstDerivedTyID;
217}
218
Reid Spencer04cde2c2004-07-04 11:33:49 +0000219/// Obtain a type given a typeid and account for things like compaction tables,
220/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000221const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000222 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000223 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000224 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000225
226 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000227 ID -= Type::FirstDerivedTyID;
228
Reid Spencer060d25d2004-06-29 23:29:38 +0000229 if (!CompactionTypes.empty()) {
230 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000231 error("Type ID out of range for compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000232 return CompactionTypes[ID];
Chris Lattner89e02532004-01-18 21:08:15 +0000233 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000234
235 // Is it a module-level type?
Reid Spencer060d25d2004-06-29 23:29:38 +0000236 if (ID < ModuleTypes.size())
237 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000238
Reid Spencer060d25d2004-06-29 23:29:38 +0000239 // Nope, is it a function-level type?
240 ID -= ModuleTypes.size();
241 if (ID < FunctionTypes.size())
242 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000243
Reid Spencer24399722004-07-09 22:21:33 +0000244 error("Illegal type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000245 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000246}
247
Reid Spencer04cde2c2004-07-04 11:33:49 +0000248/// Get a sanitized type id. This just makes sure that the \p ID
249/// is both sanitized and not the "type type" of pre-1.3 bytecode.
250/// @see sanitizeTypeId
251inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer24399722004-07-09 22:21:33 +0000252 if ( sanitizeTypeId(ID) )
253 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000254 return getType(ID);
255}
256
257/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000258/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000259/// then calls getType to return the type value.
260inline const Type* BytecodeReader::readSanitizedType() {
261 unsigned ID;
Reid Spencer24399722004-07-09 22:21:33 +0000262 if ( read_typeid(ID) )
263 error( "Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000264 return getType(ID);
265}
266
267/// Get the slot number associated with a type accounting for primitive
268/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000269unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
270 if (Ty->isPrimitiveType())
271 return Ty->getTypeID();
272
273 // Scan the compaction table for the type if needed.
274 if (!CompactionTypes.empty()) {
275 std::vector<const Type*>::const_iterator I =
Reid Spencer04cde2c2004-07-04 11:33:49 +0000276 find(CompactionTypes.begin(), CompactionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000277
278 if (I == CompactionTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000279 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000280 return Type::FirstDerivedTyID + (&*I - &CompactionTypes[0]);
281 }
282
283 // Check the function level types first...
284 TypeListTy::iterator I = find(FunctionTypes.begin(), FunctionTypes.end(), Ty);
285
286 if (I != FunctionTypes.end())
287 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer04cde2c2004-07-04 11:33:49 +0000288 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000289
290 // Check the module level types now...
291 I = find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
292 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000293 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000294 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000295}
296
Reid Spencer04cde2c2004-07-04 11:33:49 +0000297/// This is just like getType, but when a compaction table is in use, it is
298/// ignored. It also ignores function level types.
299/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000300const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
301 if (Slot < Type::FirstDerivedTyID) {
302 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer24399722004-07-09 22:21:33 +0000303 if ( ! Ty )
304 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000305 return Ty;
306 }
307 Slot -= Type::FirstDerivedTyID;
308 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000309 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000310 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000311}
312
Reid Spencer04cde2c2004-07-04 11:33:49 +0000313/// This is just like getTypeSlot, but when a compaction table is in use, it
314/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000315unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
316 if (Ty->isPrimitiveType())
317 return Ty->getTypeID();
318 TypeListTy::iterator I = find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000319 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000320 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000321 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000322 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
323}
324
Reid Spencer04cde2c2004-07-04 11:33:49 +0000325/// Retrieve a value of a given type and slot number, possibly creating
326/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000327Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000328 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000329 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000330
Chris Lattner89e02532004-01-18 21:08:15 +0000331 // If there is a compaction table active, it defines the low-level numbers.
332 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000333 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
334 if (Num < CompactionValues[type].size())
335 return CompactionValues[type][Num];
336 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000337 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000338 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000339 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000340
341 // If the type plane was compactified, figure out the global type ID
342 // by adding the derived type ids and the distance.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000343 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000344 const Type *Ty = CompactionTypes[type-Type::FirstDerivedTyID];
345 TypeListTy::iterator I =
Reid Spencer04cde2c2004-07-04 11:33:49 +0000346 find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000347 assert(I != ModuleTypes.end());
348 GlobalTyID = Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner52f86d62004-01-20 00:54:06 +0000349 }
Chris Lattner00950542001-06-06 20:29:01 +0000350
Reid Spencer060d25d2004-06-29 23:29:38 +0000351 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000352 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000353 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000354 --Num;
355 }
356
Chris Lattner52f86d62004-01-20 00:54:06 +0000357 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
358 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000359 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000360 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000361 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000362 }
363
Reid Spencer060d25d2004-06-29 23:29:38 +0000364 if (FunctionValues.size() > type &&
365 FunctionValues[type] &&
366 Num < FunctionValues[type]->size())
367 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000368
Chris Lattner74734132002-08-17 22:01:27 +0000369 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000370
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000371 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000372 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000373 if (I != ForwardReferences.end() && I->first == KeyValue)
374 return I->second; // We have already created this placeholder
375
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000376 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000377 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000378 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000379}
380
Reid Spencer04cde2c2004-07-04 11:33:49 +0000381/// This is just like getValue, but when a compaction table is in use, it
382/// is ignored. Also, no forward references or other fancy features are
383/// supported.
Reid Spencer060d25d2004-06-29 23:29:38 +0000384Value* BytecodeReader::getGlobalTableValue(const Type *Ty, unsigned SlotNo) {
385 // FIXME: getTypeSlot is inefficient!
386 unsigned TyID = getGlobalTableTypeSlot(Ty);
387
388 if (TyID != Type::LabelTyID) {
389 if (SlotNo == 0)
390 return Constant::getNullValue(Ty);
391 --SlotNo;
392 }
393
394 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
395 SlotNo >= ModuleValues[TyID]->size()) {
Reid Spencer24399722004-07-09 22:21:33 +0000396 error("Corrupt compaction table entry!"
397 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
398 + utostr(ModuleValues.size()) + ", "
399 + utohexstr(int((void*)ModuleValues[TyID])) + ", "
400 + utostr(ModuleValues[TyID]->size()) );
Reid Spencer060d25d2004-06-29 23:29:38 +0000401 }
402 return ModuleValues[TyID]->getOperand(SlotNo);
403}
404
Reid Spencer04cde2c2004-07-04 11:33:49 +0000405/// Just like getValue, except that it returns a null pointer
406/// only on error. It always returns a constant (meaning that if the value is
407/// defined, but is not a constant, that is an error). If the specified
408/// constant hasn't been parsed yet, a placeholder is defined and used.
409/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000410Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
411 if (Value *V = getValue(TypeSlot, Slot, false))
412 if (Constant *C = dyn_cast<Constant>(V))
413 return C; // If we already have the value parsed, just return it
414 else if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
415 // ConstantPointerRef's are an abomination, but at least they don't have
416 // to infest bytecode files.
417 return ConstantPointerRef::get(GV);
418 else
Reid Spencer24399722004-07-09 22:21:33 +0000419 error("Reference of a value is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000420
421 const Type *Ty = getType(TypeSlot);
422 std::pair<const Type*, unsigned> Key(Ty, Slot);
423 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
424
425 if (I != ConstantFwdRefs.end() && I->first == Key) {
426 return I->second;
427 } else {
428 // Create a placeholder for the constant reference and
429 // keep track of the fact that we have a forward ref to recycle it
430 Constant *C = new ConstPHolder(Ty, Slot);
431
432 // Keep track of the fact that we have a forward ref to recycle it
433 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
434 return C;
435 }
436}
437
438//===----------------------------------------------------------------------===//
439// IR Construction Methods
440//===----------------------------------------------------------------------===//
441
Reid Spencer04cde2c2004-07-04 11:33:49 +0000442/// As values are created, they are inserted into the appropriate place
443/// with this method. The ValueTable argument must be one of ModuleValues
444/// or FunctionValues data members of this class.
Reid Spencer060d25d2004-06-29 23:29:38 +0000445unsigned BytecodeReader::insertValue(
446 Value *Val, unsigned type, ValueTable &ValueTab) {
447 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000448 !hasImplicitNull(type) &&
449 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000450
451 if (ValueTab.size() <= type)
452 ValueTab.resize(type+1);
453
454 if (!ValueTab[type]) ValueTab[type] = new ValueList();
455
456 ValueTab[type]->push_back(Val);
457
458 bool HasOffset = hasImplicitNull(type);
459 return ValueTab[type]->size()-1 + HasOffset;
460}
461
Reid Spencer04cde2c2004-07-04 11:33:49 +0000462/// Insert the arguments of a function as new values in the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +0000463void BytecodeReader::insertArguments(Function* F ) {
464 const FunctionType *FT = F->getFunctionType();
465 Function::aiterator AI = F->abegin();
466 for (FunctionType::param_iterator It = FT->param_begin();
467 It != FT->param_end(); ++It, ++AI)
468 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
469}
470
471//===----------------------------------------------------------------------===//
472// Bytecode Parsing Methods
473//===----------------------------------------------------------------------===//
474
Reid Spencer04cde2c2004-07-04 11:33:49 +0000475/// This method parses a single instruction. The instruction is
476/// inserted at the end of the \p BB provided. The arguments of
477/// the instruction are provided in the \p Args vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000478void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
479 BasicBlock* BB) {
480 BufPtr SaveAt = At;
481
482 // Clear instruction data
483 Oprnds.clear();
484 unsigned iType = 0;
485 unsigned Opcode = 0;
486 unsigned Op = read_uint();
487
488 // bits Instruction format: Common to all formats
489 // --------------------------
490 // 01-00: Opcode type, fixed to 1.
491 // 07-02: Opcode
492 Opcode = (Op >> 2) & 63;
493 Oprnds.resize((Op >> 0) & 03);
494
495 // Extract the operands
496 switch (Oprnds.size()) {
497 case 1:
498 // bits Instruction format:
499 // --------------------------
500 // 19-08: Resulting type plane
501 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
502 //
503 iType = (Op >> 8) & 4095;
504 Oprnds[0] = (Op >> 20) & 4095;
505 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
506 Oprnds.resize(0);
507 break;
508 case 2:
509 // bits Instruction format:
510 // --------------------------
511 // 15-08: Resulting type plane
512 // 23-16: Operand #1
513 // 31-24: Operand #2
514 //
515 iType = (Op >> 8) & 255;
516 Oprnds[0] = (Op >> 16) & 255;
517 Oprnds[1] = (Op >> 24) & 255;
518 break;
519 case 3:
520 // bits Instruction format:
521 // --------------------------
522 // 13-08: Resulting type plane
523 // 19-14: Operand #1
524 // 25-20: Operand #2
525 // 31-26: Operand #3
526 //
527 iType = (Op >> 8) & 63;
528 Oprnds[0] = (Op >> 14) & 63;
529 Oprnds[1] = (Op >> 20) & 63;
530 Oprnds[2] = (Op >> 26) & 63;
531 break;
532 case 0:
533 At -= 4; // Hrm, try this again...
534 Opcode = read_vbr_uint();
535 Opcode >>= 2;
536 iType = read_vbr_uint();
537
538 unsigned NumOprnds = read_vbr_uint();
539 Oprnds.resize(NumOprnds);
540
541 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000542 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000543
544 for (unsigned i = 0; i != NumOprnds; ++i)
545 Oprnds[i] = read_vbr_uint();
546 align32();
547 break;
548 }
549
Reid Spencer04cde2c2004-07-04 11:33:49 +0000550 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000551
552 // Hae enough to inform the handler now
Reid Spencer04cde2c2004-07-04 11:33:49 +0000553 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000554
555 // Declare the resulting instruction we'll build.
556 Instruction *Result = 0;
557
558 // Handle binary operators
559 if (Opcode >= Instruction::BinaryOpsBegin &&
560 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
561 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
562 getValue(iType, Oprnds[0]),
563 getValue(iType, Oprnds[1]));
564
565 switch (Opcode) {
566 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000567 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000568 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000569 break;
570 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000571 Result = new VAArgInst(getValue(iType, Oprnds[0]),
572 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000573 break;
574 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000575 Result = new VANextInst(getValue(iType, Oprnds[0]),
576 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000577 break;
578 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000579 Result = new CastInst(getValue(iType, Oprnds[0]),
580 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000581 break;
582 case Instruction::Select:
583 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
584 getValue(iType, Oprnds[1]),
585 getValue(iType, Oprnds[2]));
586 break;
587 case Instruction::PHI: {
588 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000589 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000590
591 PHINode *PN = new PHINode(InstTy);
592 PN->op_reserve(Oprnds.size());
593 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
594 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
595 Result = PN;
596 break;
597 }
598
599 case Instruction::Shl:
600 case Instruction::Shr:
601 Result = new ShiftInst((Instruction::OtherOps)Opcode,
602 getValue(iType, Oprnds[0]),
603 getValue(Type::UByteTyID, Oprnds[1]));
604 break;
605 case Instruction::Ret:
606 if (Oprnds.size() == 0)
607 Result = new ReturnInst();
608 else if (Oprnds.size() == 1)
609 Result = new ReturnInst(getValue(iType, Oprnds[0]));
610 else
Reid Spencer24399722004-07-09 22:21:33 +0000611 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000612 break;
613
614 case Instruction::Br:
615 if (Oprnds.size() == 1)
616 Result = new BranchInst(getBasicBlock(Oprnds[0]));
617 else if (Oprnds.size() == 3)
618 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000619 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000620 else
Reid Spencer24399722004-07-09 22:21:33 +0000621 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000622 break;
623 case Instruction::Switch: {
624 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000625 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000626
627 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
628 getBasicBlock(Oprnds[1]));
629 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
630 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
631 getBasicBlock(Oprnds[i+1]));
632 Result = I;
633 break;
634 }
635
636 case Instruction::Call: {
637 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000638 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000639
640 Value *F = getValue(iType, Oprnds[0]);
641
642 // Check to make sure we have a pointer to function type
643 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000644 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000645 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000646 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000647
648 std::vector<Value *> Params;
649 if (!FTy->isVarArg()) {
650 FunctionType::param_iterator It = FTy->param_begin();
651
652 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
653 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000654 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000655 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
656 }
657 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000658 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000659 } else {
660 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
661
662 unsigned FirstVariableOperand;
663 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000664 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000665
666 // Read all of the fixed arguments
667 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
668 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
669
670 FirstVariableOperand = FTy->getNumParams();
671
672 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
Reid Spencer24399722004-07-09 22:21:33 +0000673 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000674
675 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000676 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000677 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
678 }
679
680 Result = new CallInst(F, Params);
681 break;
682 }
683 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000684 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000685 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000686 Value *F = getValue(iType, Oprnds[0]);
687
688 // Check to make sure we have a pointer to function type
689 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000690 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000691 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000692 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000693 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000694 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000695
696 std::vector<Value *> Params;
697 BasicBlock *Normal, *Except;
698
699 if (!FTy->isVarArg()) {
700 Normal = getBasicBlock(Oprnds[1]);
701 Except = getBasicBlock(Oprnds[2]);
702
703 FunctionType::param_iterator It = FTy->param_begin();
704 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
705 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000706 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000707 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
708 }
709 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000710 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000711 } else {
712 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
713
714 Normal = getBasicBlock(Oprnds[0]);
715 Except = getBasicBlock(Oprnds[1]);
716
717 unsigned FirstVariableArgument = FTy->getNumParams()+2;
718 for (unsigned i = 2; i != FirstVariableArgument; ++i)
719 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
720 Oprnds[i]));
721
722 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000723 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000724
725 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
726 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
727 }
728
729 Result = new InvokeInst(F, Normal, Except, Params);
730 break;
731 }
732 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000733 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000734 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000735 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000736 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000737
738 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
739 Oprnds.size() ? getValue(Type::UIntTyID,
740 Oprnds[0]) : 0);
741 break;
742
743 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000744 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000745 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000746 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000747 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000748
749 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
750 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000751 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000752 break;
753 case Instruction::Free:
754 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000755 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000756 Result = new FreeInst(getValue(iType, Oprnds[0]));
757 break;
758 case Instruction::GetElementPtr: {
759 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000760 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000761
762 std::vector<Value*> Idx;
763
764 const Type *NextTy = InstTy;
765 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
766 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000767 if (!TopTy)
Reid Spencer24399722004-07-09 22:21:33 +0000768 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000769
770 unsigned ValIdx = Oprnds[i];
771 unsigned IdxTy = 0;
772 if (!hasRestrictedGEPTypes) {
773 // Struct indices are always uints, sequential type indices can be any
774 // of the 32 or 64-bit integer types. The actual choice of type is
775 // encoded in the low two bits of the slot number.
776 if (isa<StructType>(TopTy))
777 IdxTy = Type::UIntTyID;
778 else {
779 switch (ValIdx & 3) {
780 default:
781 case 0: IdxTy = Type::UIntTyID; break;
782 case 1: IdxTy = Type::IntTyID; break;
783 case 2: IdxTy = Type::ULongTyID; break;
784 case 3: IdxTy = Type::LongTyID; break;
785 }
786 ValIdx >>= 2;
787 }
788 } else {
789 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
790 }
791
792 Idx.push_back(getValue(IdxTy, ValIdx));
793
794 // Convert ubyte struct indices into uint struct indices.
795 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
796 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
797 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
798
799 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
800 }
801
802 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
803 break;
804 }
805
806 case 62: // volatile load
807 case Instruction::Load:
808 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000809 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000810 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
811 break;
812
813 case 63: // volatile store
814 case Instruction::Store: {
815 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000816 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000817
818 Value *Ptr = getValue(iType, Oprnds[1]);
819 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
820 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
821 Opcode == 63);
822 break;
823 }
824 case Instruction::Unwind:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000825 if (Oprnds.size() != 0)
Reid Spencer24399722004-07-09 22:21:33 +0000826 error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000827 Result = new UnwindInst();
828 break;
829 } // end switch(Opcode)
830
831 unsigned TypeSlot;
832 if (Result->getType() == InstTy)
833 TypeSlot = iType;
834 else
835 TypeSlot = getTypeSlot(Result->getType());
836
837 insertValue(Result, TypeSlot, FunctionValues);
838 BB->getInstList().push_back(Result);
839}
840
Reid Spencer04cde2c2004-07-04 11:33:49 +0000841/// Get a particular numbered basic block, which might be a forward reference.
842/// This works together with ParseBasicBlock to handle these forward references
843/// in a clean manner. This function is used when constructing phi, br, switch,
844/// and other instructions that reference basic blocks. Blocks are numbered
845/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000846BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000847 // Make sure there is room in the table...
848 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
849
850 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
851 // has already created this block, or if the forward reference has already
852 // been created.
853 if (ParsedBasicBlocks[ID])
854 return ParsedBasicBlocks[ID];
855
856 // Otherwise, the basic block has not yet been created. Do so and add it to
857 // the ParsedBasicBlocks list.
858 return ParsedBasicBlocks[ID] = new BasicBlock();
859}
860
Reid Spencer04cde2c2004-07-04 11:33:49 +0000861/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
862/// This method reads in one of the basicblock packets. This method is not used
863/// for bytecode files after LLVM 1.0
864/// @returns The basic block constructed.
Reid Spencer060d25d2004-06-29 23:29:38 +0000865BasicBlock *BytecodeReader::ParseBasicBlock( unsigned BlockNo) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000866 if (Handler) Handler->handleBasicBlockBegin( BlockNo );
Reid Spencer060d25d2004-06-29 23:29:38 +0000867
868 BasicBlock *BB = 0;
869
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000870 if (ParsedBasicBlocks.size() == BlockNo)
871 ParsedBasicBlocks.push_back(BB = new BasicBlock());
872 else if (ParsedBasicBlocks[BlockNo] == 0)
873 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
874 else
875 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000876
Reid Spencer060d25d2004-06-29 23:29:38 +0000877 std::vector<unsigned> Operands;
878 while ( moreInBlock() )
879 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000880
Reid Spencer04cde2c2004-07-04 11:33:49 +0000881 if (Handler) Handler->handleBasicBlockEnd( BlockNo );
Misha Brukman12c29d12003-09-22 23:38:23 +0000882 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000883}
884
Reid Spencer04cde2c2004-07-04 11:33:49 +0000885/// Parse all of the BasicBlock's & Instruction's in the body of a function.
886/// In post 1.0 bytecode files, we no longer emit basic block individually,
887/// in order to avoid per-basic-block overhead.
888/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000889unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000890 unsigned BlockNo = 0;
891 std::vector<unsigned> Args;
892
Reid Spencer060d25d2004-06-29 23:29:38 +0000893 while ( moreInBlock() ) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000894 if (Handler) Handler->handleBasicBlockBegin( BlockNo );
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000895 BasicBlock *BB;
896 if (ParsedBasicBlocks.size() == BlockNo)
897 ParsedBasicBlocks.push_back(BB = new BasicBlock());
898 else if (ParsedBasicBlocks[BlockNo] == 0)
899 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
900 else
901 BB = ParsedBasicBlocks[BlockNo];
902 ++BlockNo;
903 F->getBasicBlockList().push_back(BB);
904
905 // Read instructions into this basic block until we get to a terminator
Reid Spencer060d25d2004-06-29 23:29:38 +0000906 while ( moreInBlock() && !BB->getTerminator())
907 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000908
909 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000910 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000911
912 if (Handler) Handler->handleBasicBlockEnd( BlockNo-1 );
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000913 }
914
915 return BlockNo;
916}
917
Reid Spencer04cde2c2004-07-04 11:33:49 +0000918/// Parse a symbol table. This works for both module level and function
919/// level symbol tables. For function level symbol tables, the CurrentFunction
920/// parameter must be non-zero and the ST parameter must correspond to
921/// CurrentFunction's symbol table. For Module level symbol tables, the
922/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +0000923void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000924 SymbolTable *ST) {
925 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000926
Chris Lattner39cacce2003-10-10 05:43:47 +0000927 // Allow efficient basic block lookup by number.
928 std::vector<BasicBlock*> BBMap;
929 if (CurrentFunction)
930 for (Function::iterator I = CurrentFunction->begin(),
931 E = CurrentFunction->end(); I != E; ++I)
932 BBMap.push_back(I);
933
Reid Spencer04cde2c2004-07-04 11:33:49 +0000934 /// In LLVM 1.3 we write types separately from values so
935 /// The types are always first in the symbol table. This is
936 /// because Type no longer derives from Value.
937 if ( ! hasTypeDerivedFromValue ) {
938 // Symtab block header: [num entries]
939 unsigned NumEntries = read_vbr_uint();
940 for ( unsigned i = 0; i < NumEntries; ++i ) {
941 // Symtab entry: [def slot #][name]
942 unsigned slot = read_vbr_uint();
943 std::string Name = read_str();
944 const Type* T = getType(slot);
945 ST->insert(Name, T);
946 }
947 }
948
Reid Spencer060d25d2004-06-29 23:29:38 +0000949 while ( moreInBlock() ) {
Chris Lattner00950542001-06-06 20:29:01 +0000950 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000951 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000952 unsigned Typ = 0;
953 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +0000954 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +0000955
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000956 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000957 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000958 unsigned slot = read_vbr_uint();
959 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +0000960
Reid Spencer04cde2c2004-07-04 11:33:49 +0000961 // if we're reading a pre 1.3 bytecode file and the type plane
962 // is the "type type", handle it here
963 if ( isTypeType ) {
964 const Type* T = getType(slot);
965 if ( T == 0 )
Reid Spencer24399722004-07-09 22:21:33 +0000966 error("Failed type look-up for name '" + Name + "'");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000967 ST->insert(Name, T);
968 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +0000969 } else {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000970 Value *V = 0;
971 if (Typ == Type::LabelTyID) {
972 if (slot < BBMap.size())
973 V = BBMap[slot];
974 } else {
975 V = getValue(Typ, slot, false); // Find mapping...
976 }
977 if (V == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000978 error("Failed value look-up for name '" + Name + "'");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000979 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +0000980 }
Chris Lattner00950542001-06-06 20:29:01 +0000981 }
982 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000983 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000984 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000985}
986
Reid Spencer04cde2c2004-07-04 11:33:49 +0000987/// Read in the types portion of a compaction table.
988void BytecodeReader::ParseCompactionTypes( unsigned NumEntries ) {
989 for (unsigned i = 0; i != NumEntries; ++i) {
990 unsigned TypeSlot = 0;
Reid Spencer24399722004-07-09 22:21:33 +0000991 if ( read_typeid(TypeSlot) )
992 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000993 const Type *Typ = getGlobalTableType(TypeSlot);
994 CompactionTypes.push_back(Typ);
995 if (Handler) Handler->handleCompactionTableType( i, TypeSlot, Typ );
996 }
997}
998
999/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001000void BytecodeReader::ParseCompactionTable() {
1001
Reid Spencer04cde2c2004-07-04 11:33:49 +00001002 if (Handler) Handler->handleCompactionTableBegin();
1003
1004 /// In LLVM 1.3 Type no longer derives from Value. So,
1005 /// we always write them first in the compaction table
1006 /// because they can't occupy a "type plane" where the
1007 /// Values reside.
1008 if ( ! hasTypeDerivedFromValue ) {
1009 unsigned NumEntries = read_vbr_uint();
1010 ParseCompactionTypes( NumEntries );
1011 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001012
1013 while ( moreInBlock() ) {
1014 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001015 unsigned Ty = 0;
1016 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001017
1018 if ((NumEntries & 3) == 3) {
1019 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001020 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001021 } else {
1022 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001023 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001024 NumEntries &= 3;
1025 }
1026
Reid Spencer04cde2c2004-07-04 11:33:49 +00001027 // if we're reading a pre 1.3 bytecode file and the type plane
1028 // is the "type type", handle it here
1029 if ( isTypeType ) {
1030 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001031 } else {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001032 if (Ty >= CompactionValues.size())
1033 CompactionValues.resize(Ty+1);
1034
1035 if (!CompactionValues[Ty].empty())
Reid Spencer24399722004-07-09 22:21:33 +00001036 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001037
1038 if (Handler) Handler->handleCompactionTablePlane( Ty, NumEntries );
1039
Reid Spencer060d25d2004-06-29 23:29:38 +00001040 const Type *Typ = getType(Ty);
1041 // Push the implicit zero
1042 CompactionValues[Ty].push_back(Constant::getNullValue(Typ));
1043 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001044 unsigned ValSlot = read_vbr_uint();
1045 Value *V = getGlobalTableValue(Typ, ValSlot);
1046 CompactionValues[Ty].push_back(V);
1047 if (Handler) Handler->handleCompactionTableValue( i, Ty, ValSlot, Typ );
Reid Spencer060d25d2004-06-29 23:29:38 +00001048 }
1049 }
1050 }
Reid Spencer04cde2c2004-07-04 11:33:49 +00001051 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001052}
1053
1054// Parse a single type constant.
1055const Type *BytecodeReader::ParseTypeConstant() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001056 unsigned PrimType = 0;
Reid Spencer24399722004-07-09 22:21:33 +00001057 if ( read_typeid(PrimType) )
1058 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001059
1060 const Type *Result = 0;
1061 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1062 return Result;
1063
1064 switch (PrimType) {
1065 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001066 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001067
1068 unsigned NumParams = read_vbr_uint();
1069
1070 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001071 while (NumParams--)
1072 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001073
1074 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1075 if (isVarArg) Params.pop_back();
1076
1077 Result = FunctionType::get(RetType, Params, isVarArg);
1078 break;
1079 }
1080 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001081 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001082 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001083 Result = ArrayType::get(ElementType, NumElements);
1084 break;
1085 }
1086 case Type::StructTyID: {
1087 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001088 unsigned Typ = 0;
Reid Spencer24399722004-07-09 22:21:33 +00001089 if ( read_typeid(Typ) )
1090 error("Invalid element type (type type) for structure!");
1091
Reid Spencer060d25d2004-06-29 23:29:38 +00001092 while (Typ) { // List is terminated by void/0 typeid
1093 Elements.push_back(getType(Typ));
Reid Spencer24399722004-07-09 22:21:33 +00001094 if ( read_typeid(Typ) )
1095 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001096 }
1097
1098 Result = StructType::get(Elements);
1099 break;
1100 }
1101 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001102 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001103 break;
1104 }
1105
1106 case Type::OpaqueTyID: {
1107 Result = OpaqueType::get();
1108 break;
1109 }
1110
1111 default:
Reid Spencer24399722004-07-09 22:21:33 +00001112 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 break;
1114 }
Reid Spencer04cde2c2004-07-04 11:33:49 +00001115 if (Handler) Handler->handleType( Result );
Reid Spencer060d25d2004-06-29 23:29:38 +00001116 return Result;
1117}
1118
1119// ParseTypeConstants - We have to use this weird code to handle recursive
1120// types. We know that recursive types will only reference the current slab of
1121// values in the type plane, but they can forward reference types before they
1122// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1123// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1124// this ugly problem, we pessimistically insert an opaque type for each type we
1125// are about to read. This means that forward references will resolve to
1126// something and when we reread the type later, we can replace the opaque type
1127// with a new resolved concrete type.
1128//
1129void BytecodeReader::ParseTypeConstants(TypeListTy &Tab, unsigned NumEntries){
1130 assert(Tab.size() == 0 && "should not have read type constants in before!");
1131
1132 // Insert a bunch of opaque types to be resolved later...
1133 Tab.reserve(NumEntries);
1134 for (unsigned i = 0; i != NumEntries; ++i)
1135 Tab.push_back(OpaqueType::get());
1136
1137 // Loop through reading all of the types. Forward types will make use of the
1138 // opaque types just inserted.
1139 //
1140 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001141 const Type* NewTy = ParseTypeConstant();
1142 const Type* OldTy = Tab[i].get();
1143 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001144 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001145
1146 // Don't directly push the new type on the Tab. Instead we want to replace
1147 // the opaque type we previously inserted with the new concrete value. This
1148 // approach helps with forward references to types. The refinement from the
1149 // abstract (opaque) type to the new type causes all uses of the abstract
1150 // type to use the concrete type (NewTy). This will also cause the opaque
1151 // type to be deleted.
1152 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1153
1154 // This should have replaced the old opaque type with the new type in the
1155 // value table... or with a preexisting type that was already in the system.
1156 // Let's just make sure it did.
1157 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1158 }
1159}
1160
Reid Spencer04cde2c2004-07-04 11:33:49 +00001161/// Parse a single constant value
Reid Spencer060d25d2004-06-29 23:29:38 +00001162Constant *BytecodeReader::ParseConstantValue( unsigned TypeID) {
1163 // We must check for a ConstantExpr before switching by type because
1164 // a ConstantExpr can be of any type, and has no explicit value.
1165 //
1166 // 0 if not expr; numArgs if is expr
1167 unsigned isExprNumArgs = read_vbr_uint();
1168
1169 if (isExprNumArgs) {
1170 // FIXME: Encoding of constant exprs could be much more compact!
1171 std::vector<Constant*> ArgVec;
1172 ArgVec.reserve(isExprNumArgs);
1173 unsigned Opcode = read_vbr_uint();
1174
1175 // Read the slot number and types of each of the arguments
1176 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1177 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001178 unsigned ArgTypeSlot = 0;
Reid Spencer24399722004-07-09 22:21:33 +00001179 if ( read_typeid(ArgTypeSlot) )
1180 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001181
1182 // Get the arg value from its slot if it exists, otherwise a placeholder
1183 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1184 }
1185
1186 // Construct a ConstantExpr of the appropriate kind
1187 if (isExprNumArgs == 1) { // All one-operand expressions
1188 assert(Opcode == Instruction::Cast);
1189 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001190 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001191 return Result;
1192 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1193 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1194
1195 if (hasRestrictedGEPTypes) {
1196 const Type *BaseTy = ArgVec[0]->getType();
1197 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1198 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1199 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1200 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1201 if (isa<StructType>(*GTI)) {
1202 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001203 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001204 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1205 }
1206 }
1207
1208 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001209 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001210 return Result;
1211 } else if (Opcode == Instruction::Select) {
1212 assert(ArgVec.size() == 3);
1213 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001214 ArgVec[2]);
1215 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001216 return Result;
1217 } else { // All other 2-operand expressions
1218 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001219 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001220 return Result;
1221 }
1222 }
1223
1224 // Ok, not an ConstantExpr. We now know how to read the given type...
1225 const Type *Ty = getType(TypeID);
1226 switch (Ty->getTypeID()) {
1227 case Type::BoolTyID: {
1228 unsigned Val = read_vbr_uint();
1229 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001230 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001231 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001232 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001233 return Result;
1234 }
1235
1236 case Type::UByteTyID: // Unsigned integer types...
1237 case Type::UShortTyID:
1238 case Type::UIntTyID: {
1239 unsigned Val = read_vbr_uint();
1240 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001241 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001242 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001243 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001244 return Result;
1245 }
1246
1247 case Type::ULongTyID: {
1248 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001249 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001250 return Result;
1251 }
1252
1253 case Type::SByteTyID: // Signed integer types...
1254 case Type::ShortTyID:
1255 case Type::IntTyID: {
1256 case Type::LongTyID:
1257 int64_t Val = read_vbr_int64();
1258 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001259 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001260 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001261 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001262 return Result;
1263 }
1264
1265 case Type::FloatTyID: {
1266 float F;
1267 read_data(&F, &F+1);
1268 Constant* Result = ConstantFP::get(Ty, F);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001269 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001270 return Result;
1271 }
1272
1273 case Type::DoubleTyID: {
1274 double Val;
1275 read_data(&Val, &Val+1);
1276 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001277 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001278 return Result;
1279 }
1280
Reid Spencer060d25d2004-06-29 23:29:38 +00001281 case Type::ArrayTyID: {
1282 const ArrayType *AT = cast<ArrayType>(Ty);
1283 unsigned NumElements = AT->getNumElements();
1284 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1285 std::vector<Constant*> Elements;
1286 Elements.reserve(NumElements);
1287 while (NumElements--) // Read all of the elements of the constant.
1288 Elements.push_back(getConstantValue(TypeSlot,
1289 read_vbr_uint()));
1290 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001291 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001292 return Result;
1293 }
1294
1295 case Type::StructTyID: {
1296 const StructType *ST = cast<StructType>(Ty);
1297
1298 std::vector<Constant *> Elements;
1299 Elements.reserve(ST->getNumElements());
1300 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1301 Elements.push_back(getConstantValue(ST->getElementType(i),
1302 read_vbr_uint()));
1303
1304 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001305 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001306 return Result;
1307 }
1308
1309 case Type::PointerTyID: { // ConstantPointerRef value...
1310 const PointerType *PT = cast<PointerType>(Ty);
1311 unsigned Slot = read_vbr_uint();
1312
1313 // Check to see if we have already read this global variable...
1314 Value *Val = getValue(TypeID, Slot, false);
1315 GlobalValue *GV;
1316 if (Val) {
1317 if (!(GV = dyn_cast<GlobalValue>(Val)))
Reid Spencer24399722004-07-09 22:21:33 +00001318 error("Value of ConstantPointerRef not in ValueTable!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001319 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001320 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001321 }
1322
1323 Constant* Result = ConstantPointerRef::get(GV);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001324 if (Handler) Handler->handleConstantPointer(PT, Slot, GV, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001325 return Result;
1326 }
1327
1328 default:
Reid Spencer24399722004-07-09 22:21:33 +00001329 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001330 Ty->getDescription());
1331 break;
1332 }
Reid Spencer24399722004-07-09 22:21:33 +00001333 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001334}
1335
Reid Spencer04cde2c2004-07-04 11:33:49 +00001336/// Resolve references for constants. This function resolves the forward
1337/// referenced constants in the ConstantFwdRefs map. It uses the
1338/// replaceAllUsesWith method of Value class to substitute the placeholder
1339/// instance with the actual instance.
Reid Spencer060d25d2004-06-29 23:29:38 +00001340void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001341 ConstantRefsType::iterator I =
1342 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1343 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001344
Chris Lattner29b789b2003-11-19 17:27:18 +00001345 Value *PH = I->second; // Get the placeholder...
1346 PH->replaceAllUsesWith(NewV);
1347 delete PH; // Delete the old placeholder
1348 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001349}
1350
Reid Spencer04cde2c2004-07-04 11:33:49 +00001351/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001352void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1353 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001354 unsigned Typ = 0;
Reid Spencer24399722004-07-09 22:21:33 +00001355 if ( read_typeid(Typ) )
1356 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001357 const Type *Ty = getType(Typ);
1358 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001359 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001360
1361 const ArrayType *ATy = cast<ArrayType>(Ty);
1362 if (ATy->getElementType() != Type::SByteTy &&
1363 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001364 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001365
1366 // Read character data. The type tells us how long the string is.
1367 char Data[ATy->getNumElements()];
1368 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001369
Reid Spencer060d25d2004-06-29 23:29:38 +00001370 std::vector<Constant*> Elements(ATy->getNumElements());
1371 if (ATy->getElementType() == Type::SByteTy)
1372 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1373 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1374 else
1375 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1376 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001377
Reid Spencer060d25d2004-06-29 23:29:38 +00001378 // Create the constant, inserting it as needed.
1379 Constant *C = ConstantArray::get(ATy, Elements);
1380 unsigned Slot = insertValue(C, Typ, Tab);
1381 ResolveReferencesToConstant(C, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001382 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001383 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001384}
1385
Reid Spencer04cde2c2004-07-04 11:33:49 +00001386/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001387void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001388 TypeListTy &TypeTab,
1389 bool isFunction) {
1390 if (Handler) Handler->handleGlobalConstantsBegin();
1391
1392 /// In LLVM 1.3 Type does not derive from Value so the types
1393 /// do not occupy a plane. Consequently, we read the types
1394 /// first in the constant pool.
1395 if ( isFunction && !hasTypeDerivedFromValue ) {
1396 unsigned NumEntries = read_vbr_uint();
1397 ParseTypeConstants(TypeTab, NumEntries);
1398 }
1399
Reid Spencer060d25d2004-06-29 23:29:38 +00001400 while ( moreInBlock() ) {
1401 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001402 unsigned Typ = 0;
1403 bool isTypeType = read_typeid(Typ);
1404
1405 /// In LLVM 1.2 and before, Types were written to the
1406 /// bytecode file in the "Type Type" plane (#12).
1407 /// In 1.3 plane 12 is now the label plane. Handle this here.
1408 if ( isTypeType ) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 ParseTypeConstants(TypeTab, NumEntries);
1410 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001411 /// Use of Type::VoidTyID is a misnomer. It actually means
1412 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001413 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1414 ParseStringConstants(NumEntries, Tab);
1415 } else {
1416 for (unsigned i = 0; i < NumEntries; ++i) {
1417 Constant *C = ParseConstantValue(Typ);
1418 assert(C && "ParseConstantValue returned NULL!");
1419 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001420
Reid Spencer060d25d2004-06-29 23:29:38 +00001421 // If we are reading a function constant table, make sure that we adjust
1422 // the slot number to be the real global constant number.
1423 //
1424 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1425 ModuleValues[Typ])
1426 Slot += ModuleValues[Typ]->size();
1427 ResolveReferencesToConstant(C, Slot);
1428 }
1429 }
1430 }
1431 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001432 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001433}
Chris Lattner00950542001-06-06 20:29:01 +00001434
Reid Spencer04cde2c2004-07-04 11:33:49 +00001435/// Parse the contents of a function. Note that this function can be
1436/// called lazily by materializeFunction
1437/// @see materializeFunction
Reid Spencer060d25d2004-06-29 23:29:38 +00001438void BytecodeReader::ParseFunctionBody(Function* F ) {
1439
1440 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001441 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1442
Reid Spencer060d25d2004-06-29 23:29:38 +00001443 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001444 switch (LinkageType) {
1445 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1446 case 1: Linkage = GlobalValue::WeakLinkage; break;
1447 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1448 case 3: Linkage = GlobalValue::InternalLinkage; break;
1449 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001450 default:
Reid Spencer24399722004-07-09 22:21:33 +00001451 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001452 Linkage = GlobalValue::InternalLinkage;
1453 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001454 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001455
Reid Spencer060d25d2004-06-29 23:29:38 +00001456 F->setLinkage( Linkage );
Reid Spencer04cde2c2004-07-04 11:33:49 +00001457 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001458
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001459 // Keep track of how many basic blocks we have read in...
1460 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001461 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001462
Reid Spencer060d25d2004-06-29 23:29:38 +00001463 BufPtr MyEnd = BlockEnd;
1464 while ( At < MyEnd ) {
Chris Lattner00950542001-06-06 20:29:01 +00001465 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001466 BufPtr OldAt = At;
1467 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001468
1469 switch (Type) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001470 case BytecodeFormat::ConstantPool:
Chris Lattner89e02532004-01-18 21:08:15 +00001471 if (!InsertedArguments) {
1472 // Insert arguments into the value table before we parse the first basic
1473 // block in the function, but after we potentially read in the
1474 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001475 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001476 InsertedArguments = true;
1477 }
1478
Reid Spencer04cde2c2004-07-04 11:33:49 +00001479 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001480 break;
1481
Chris Lattner89e02532004-01-18 21:08:15 +00001482 case BytecodeFormat::CompactionTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001483 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001484 break;
1485
Chris Lattner00950542001-06-06 20:29:01 +00001486 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001487 if (!InsertedArguments) {
1488 // Insert arguments into the value table before we parse the first basic
1489 // block in the function, but after we potentially read in the
1490 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001491 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001492 InsertedArguments = true;
1493 }
1494
Reid Spencer060d25d2004-06-29 23:29:38 +00001495 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001496 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001497 break;
1498 }
1499
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001500 case BytecodeFormat::InstructionList: {
Chris Lattner89e02532004-01-18 21:08:15 +00001501 // Insert arguments into the value table before we parse the instruction
1502 // list for the function, but after we potentially read in the compaction
1503 // table.
1504 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001505 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001506 InsertedArguments = true;
1507 }
1508
Reid Spencer060d25d2004-06-29 23:29:38 +00001509 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001510 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001511 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001512 break;
1513 }
1514
Chris Lattner29b789b2003-11-19 17:27:18 +00001515 case BytecodeFormat::SymbolTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001516 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001517 break;
1518
1519 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001520 At += Size;
1521 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001522 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001523 break;
1524 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001525 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001526
Misha Brukman12c29d12003-09-22 23:38:23 +00001527 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001528 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001529 }
1530
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001531 // Make sure there were no references to non-existant basic blocks.
1532 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001533 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001534
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001535 ParsedBasicBlocks.clear();
1536
Chris Lattner97330cf2003-10-09 23:10:14 +00001537 // Resolve forward references. Replace any uses of a forward reference value
1538 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001539
Chris Lattner97330cf2003-10-09 23:10:14 +00001540 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1541 // number of operands. PHI nodes often have forward references, and can also
1542 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001543 //
1544 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1545 // should be simplified back to using it!
1546 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001547 std::map<Value*, Value*> ForwardRefMapping;
1548 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1549 I = ForwardReferences.begin(), E = ForwardReferences.end();
1550 I != E; ++I)
1551 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1552 false);
1553
1554 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1555 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1556 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1557 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
1558 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1559 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1560 }
1561
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001562 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001563 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1564 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001565 Value *PlaceHolder = I->second;
1566 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001567
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001568 // Now that all the uses are gone, delete the placeholder...
1569 // If we couldn't find a def (error case), then leak a little
1570 // memory, because otherwise we can't remove all uses!
1571 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001572 }
Chris Lattner00950542001-06-06 20:29:01 +00001573
Misha Brukman12c29d12003-09-22 23:38:23 +00001574 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001575 FunctionTypes.clear();
1576 CompactionTypes.clear();
1577 CompactionValues.clear();
1578 freeTable(FunctionValues);
1579
Reid Spencer04cde2c2004-07-04 11:33:49 +00001580 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001581}
1582
Reid Spencer04cde2c2004-07-04 11:33:49 +00001583/// This function parses LLVM functions lazily. It obtains the type of the
1584/// function and records where the body of the function is in the bytecode
1585/// buffer. The caller can then use the ParseNextFunction and
1586/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001587void BytecodeReader::ParseFunctionLazily() {
1588 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001589 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001590
Reid Spencer060d25d2004-06-29 23:29:38 +00001591 Function *Func = FunctionSignatureList.back();
1592 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001593
Reid Spencer060d25d2004-06-29 23:29:38 +00001594 // Save the information for future reading of the function
1595 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001596
Reid Spencer060d25d2004-06-29 23:29:38 +00001597 // Pretend we've `parsed' this function
1598 At = BlockEnd;
1599}
Chris Lattner89e02532004-01-18 21:08:15 +00001600
Reid Spencer04cde2c2004-07-04 11:33:49 +00001601/// The ParserFunction method lazily parses one function. Use this method to
1602/// casue the parser to parse a specific function in the module. Note that
1603/// this will remove the function from what is to be included by
1604/// ParseAllFunctionBodies.
1605/// @see ParseAllFunctionBodies
1606/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001607void BytecodeReader::ParseFunction(Function* Func) {
1608 // Find {start, end} pointers and slot in the map. If not there, we're done.
1609 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001610
Reid Spencer060d25d2004-06-29 23:29:38 +00001611 // Make sure we found it
1612 if ( Fi == LazyFunctionLoadMap.end() ) {
Reid Spencer24399722004-07-09 22:21:33 +00001613 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001614 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001615 }
1616
Reid Spencer060d25d2004-06-29 23:29:38 +00001617 BlockStart = At = Fi->second.Buf;
1618 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001619 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001620
1621 LazyFunctionLoadMap.erase(Fi);
1622
1623 this->ParseFunctionBody( Func );
Chris Lattner89e02532004-01-18 21:08:15 +00001624}
1625
Reid Spencer04cde2c2004-07-04 11:33:49 +00001626/// The ParseAllFunctionBodies method parses through all the previously
1627/// unparsed functions in the bytecode file. If you want to completely parse
1628/// a bytecode file, this method should be called after Parsebytecode because
1629/// Parsebytecode only records the locations in the bytecode file of where
1630/// the function definitions are located. This function uses that information
1631/// to materialize the functions.
1632/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001633void BytecodeReader::ParseAllFunctionBodies() {
1634 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1635 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001636
Reid Spencer060d25d2004-06-29 23:29:38 +00001637 while ( Fi != Fe ) {
1638 Function* Func = Fi->first;
1639 BlockStart = At = Fi->second.Buf;
1640 BlockEnd = Fi->second.EndBuf;
1641 this->ParseFunctionBody(Func);
1642 ++Fi;
1643 }
1644}
Chris Lattner89e02532004-01-18 21:08:15 +00001645
Reid Spencer04cde2c2004-07-04 11:33:49 +00001646/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001647void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001648 // Read the number of types
1649 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001650
1651 // Ignore the type plane identifier for types if the bc file is pre 1.3
1652 if (hasTypeDerivedFromValue)
1653 read_vbr_uint();
1654
Reid Spencer04cde2c2004-07-04 11:33:49 +00001655 ParseTypeConstants(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001656}
1657
Reid Spencer04cde2c2004-07-04 11:33:49 +00001658/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001659void BytecodeReader::ParseModuleGlobalInfo() {
1660
Reid Spencer04cde2c2004-07-04 11:33:49 +00001661 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001662
Chris Lattner70cc3392001-09-10 07:58:01 +00001663 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001664 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001665 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001666 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1667 // Linkage, bit4+ = slot#
1668 unsigned SlotNo = VarType >> 5;
Reid Spencer24399722004-07-09 22:21:33 +00001669 if ( sanitizeTypeId(SlotNo) )
1670 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001671 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001672 bool isConstant = VarType & 1;
1673 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001674 GlobalValue::LinkageTypes Linkage;
1675
Chris Lattnerc08912f2004-01-14 16:44:44 +00001676 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001677 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1678 case 1: Linkage = GlobalValue::WeakLinkage; break;
1679 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1680 case 3: Linkage = GlobalValue::InternalLinkage; break;
1681 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001682 default:
Reid Spencer24399722004-07-09 22:21:33 +00001683 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001684 Linkage = GlobalValue::InternalLinkage;
1685 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001686 }
1687
1688 const Type *Ty = getType(SlotNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001689 if ( !Ty ) {
Reid Spencer24399722004-07-09 22:21:33 +00001690 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001691 }
1692
1693 if ( !isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001694 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001695 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001696
Chris Lattner52e20b02003-03-19 20:54:26 +00001697 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001698
Chris Lattner70cc3392001-09-10 07:58:01 +00001699 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001700 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001701 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001702 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001703
Reid Spencer060d25d2004-06-29 23:29:38 +00001704 unsigned initSlot = 0;
1705 if (hasInitializer) {
1706 initSlot = read_vbr_uint();
1707 GlobalInits.push_back(std::make_pair(GV, initSlot));
1708 }
1709
1710 // Notify handler about the global value.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001711 if (Handler) Handler->handleGlobalVariable( ElTy, isConstant, Linkage, SlotNo, initSlot );
Reid Spencer060d25d2004-06-29 23:29:38 +00001712
1713 // Get next item
1714 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001715 }
1716
Chris Lattner52e20b02003-03-19 20:54:26 +00001717 // Read the function objects for all of the functions that are coming
Reid Spencer04cde2c2004-07-04 11:33:49 +00001718 unsigned FnSignature = 0;
Reid Spencer24399722004-07-09 22:21:33 +00001719 if ( read_typeid(FnSignature) )
1720 error("Invalid function type (type type) found");
1721
Chris Lattner74734132002-08-17 22:01:27 +00001722 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1723 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +00001724 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001725 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001726 error("Function not a pointer to function type! Ty = " +
1727 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001728 // FIXME: what should Ty be if handler continues?
1729 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001730
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001731 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001732 const FunctionType* FTy =
1733 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001734
Reid Spencer060d25d2004-06-29 23:29:38 +00001735 // Insert the place hodler
1736 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001737 "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001738 insertValue(Func, FnSignature, ModuleValues);
Chris Lattner00950542001-06-06 20:29:01 +00001739
Reid Spencer060d25d2004-06-29 23:29:38 +00001740 // Save this for later so we know type of lazily instantiated functions
Chris Lattner29b789b2003-11-19 17:27:18 +00001741 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001742
Reid Spencer04cde2c2004-07-04 11:33:49 +00001743 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001744
1745 // Get Next function signature
Reid Spencer24399722004-07-09 22:21:33 +00001746 if ( read_typeid(FnSignature) )
1747 error("Invalid function type (type type) found");
Chris Lattner00950542001-06-06 20:29:01 +00001748 }
1749
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001750 if (hasInconsistentModuleGlobalInfo)
Reid Spencer060d25d2004-06-29 23:29:38 +00001751 align32();
Chris Lattner74734132002-08-17 22:01:27 +00001752
1753 // Now that the function signature list is set up, reverse it so that we can
1754 // remove elements efficiently from the back of the vector.
1755 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001756
1757 // This is for future proofing... in the future extra fields may be added that
1758 // we don't understand, so we transparently ignore them.
1759 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001760 At = BlockEnd;
1761
Reid Spencer04cde2c2004-07-04 11:33:49 +00001762 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001763}
1764
Reid Spencer04cde2c2004-07-04 11:33:49 +00001765/// Parse the version information and decode it by setting flags on the
1766/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001767void BytecodeReader::ParseVersionInfo() {
1768 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001769
1770 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001771 Module::Endianness Endianness;
1772 Module::PointerSize PointerSize;
1773 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1774 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1775
1776 bool hasNoEndianness = Version & 4;
1777 bool hasNoPointerSize = Version & 8;
1778
1779 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001780
1781 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001782 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001783 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001784 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001785 hasTypeDerivedFromValue = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001786
1787 switch (RevisionNum) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001788 case 0: // LLVM 1.0, 1.1 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001789 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001790 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001791 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001792
Chris Lattner80b97342004-01-17 23:25:43 +00001793 // FALL THROUGH
Chris Lattnerc08912f2004-01-14 16:44:44 +00001794 case 1: // LLVM 1.2 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001795 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001796
1797 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1798 // included the size for the alignment at the end, where the rest of the
1799 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001800
1801 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1802 // structures and longs for sequential types.
1803 hasRestrictedGEPTypes = true;
1804
Reid Spencer04cde2c2004-07-04 11:33:49 +00001805 // LLVM 1.2 and before had the Type class derive from Value class. This
1806 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1807 // written differently because Types can no longer be part of the
1808 // type planes for Values.
1809 hasTypeDerivedFromValue = true;
1810
Chris Lattner5fa428f2004-04-05 01:27:26 +00001811 // FALL THROUGH
1812 case 2: // LLVM 1.3 release version
Chris Lattnerc08912f2004-01-14 16:44:44 +00001813 break;
1814
Chris Lattner036b8aa2003-03-06 17:55:45 +00001815 default:
Reid Spencer24399722004-07-09 22:21:33 +00001816 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00001817 }
1818
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001819 if (hasNoEndianness) Endianness = Module::AnyEndianness;
1820 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00001821
Reid Spencer04cde2c2004-07-04 11:33:49 +00001822 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize );
Chris Lattner036b8aa2003-03-06 17:55:45 +00001823}
1824
Reid Spencer04cde2c2004-07-04 11:33:49 +00001825/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001826void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001827 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001828
Reid Spencer060d25d2004-06-29 23:29:38 +00001829 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001830
1831 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001832 ParseVersionInfo();
1833 align32(); /// FIXME: Is this redundant? VI is first and 4 bytes!
Chris Lattner00950542001-06-06 20:29:01 +00001834
Reid Spencer060d25d2004-06-29 23:29:38 +00001835 bool SeenModuleGlobalInfo = false;
1836 bool SeenGlobalTypePlane = false;
1837 BufPtr MyEnd = BlockEnd;
1838 while (At < MyEnd) {
1839 BufPtr OldAt = At;
1840 read_block(Type, Size);
1841
Chris Lattner00950542001-06-06 20:29:01 +00001842 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001843
Chris Lattner52e20b02003-03-19 20:54:26 +00001844 case BytecodeFormat::GlobalTypePlane:
Reid Spencer060d25d2004-06-29 23:29:38 +00001845 if ( SeenGlobalTypePlane )
Reid Spencer24399722004-07-09 22:21:33 +00001846 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001847
1848 ParseGlobalTypes();
1849 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001850 break;
1851
Reid Spencer060d25d2004-06-29 23:29:38 +00001852 case BytecodeFormat::ModuleGlobalInfo:
1853 if ( SeenModuleGlobalInfo )
Reid Spencer24399722004-07-09 22:21:33 +00001854 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001855 ParseModuleGlobalInfo();
1856 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001857 break;
1858
Chris Lattner1d670cc2001-09-07 16:37:43 +00001859 case BytecodeFormat::ConstantPool:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001860 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001861 break;
1862
Reid Spencer060d25d2004-06-29 23:29:38 +00001863 case BytecodeFormat::Function:
1864 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001865 break;
Chris Lattner00950542001-06-06 20:29:01 +00001866
1867 case BytecodeFormat::SymbolTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001868 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001869 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001870
Chris Lattner00950542001-06-06 20:29:01 +00001871 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001872 At += Size;
1873 if (OldAt > At) {
Reid Spencer24399722004-07-09 22:21:33 +00001874 error("Unexpected Block of Type #" + utostr(Type) + " encountered!" );
Reid Spencer060d25d2004-06-29 23:29:38 +00001875 }
Chris Lattner00950542001-06-06 20:29:01 +00001876 break;
1877 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001878 BlockEnd = MyEnd;
1879 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001880 }
1881
Chris Lattner52e20b02003-03-19 20:54:26 +00001882 // After the module constant pool has been read, we can safely initialize
1883 // global variables...
1884 while (!GlobalInits.empty()) {
1885 GlobalVariable *GV = GlobalInits.back().first;
1886 unsigned Slot = GlobalInits.back().second;
1887 GlobalInits.pop_back();
1888
1889 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001890 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001891
1892 const llvm::PointerType* GVType = GV->getType();
1893 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001894 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00001895 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001896 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001897 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001898 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001899 } else
Reid Spencer24399722004-07-09 22:21:33 +00001900 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001901 }
1902
Reid Spencer060d25d2004-06-29 23:29:38 +00001903 /// Make sure we pulled them all out. If we didn't then there's a declaration
1904 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001905 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001906 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001907}
1908
Reid Spencer04cde2c2004-07-04 11:33:49 +00001909/// This function completely parses a bytecode buffer given by the \p Buf
1910/// and \p Length parameters.
Reid Spencer060d25d2004-06-29 23:29:38 +00001911void BytecodeReader::ParseBytecode(
1912 BufPtr Buf, unsigned Length,
Reid Spencer5c15fe52004-07-05 00:57:50 +00001913 const std::string &ModuleID,
1914 bool processFunctions) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001915
Reid Spencer060d25d2004-06-29 23:29:38 +00001916 try {
1917 At = MemStart = BlockStart = Buf;
1918 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001919
Reid Spencer060d25d2004-06-29 23:29:38 +00001920 // Create the module
1921 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00001922
Reid Spencer04cde2c2004-07-04 11:33:49 +00001923 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00001924
1925 // Read and check signature...
1926 unsigned Sig = read_uint();
1927 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
Reid Spencer24399722004-07-09 22:21:33 +00001928 error("Invalid bytecode signature: " + utostr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00001929 }
1930
1931
1932 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00001933 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00001934
1935 // Get the module block and size and verify
1936 unsigned Type, Size;
1937 read_block(Type, Size);
1938 if ( Type != BytecodeFormat::Module ) {
Reid Spencer24399722004-07-09 22:21:33 +00001939 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
1940 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00001941 }
1942 if ( At + Size != MemEnd ) {
Reid Spencer24399722004-07-09 22:21:33 +00001943 error("Invalid Top Level Block Length! Type:" + utostr(Type)
1944 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00001945 }
1946
1947 // Parse the module contents
1948 this->ParseModule();
1949
Reid Spencer060d25d2004-06-29 23:29:38 +00001950 // Check for missing functions
1951 if ( hasFunctions() )
Reid Spencer24399722004-07-09 22:21:33 +00001952 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001953
Reid Spencer5c15fe52004-07-05 00:57:50 +00001954 // Process all the function bodies now, if requested
1955 if ( processFunctions )
1956 ParseAllFunctionBodies();
1957
1958 // Tell the handler we're done with the module
1959 if (Handler)
1960 Handler->handleModuleEnd(ModuleID);
1961
1962 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00001963 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00001964
1965 } catch (std::string& errstr ) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001966 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00001967 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001968 delete TheModule;
1969 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00001970 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00001971 } catch (...) {
1972 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001973 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00001974 freeState();
1975 delete TheModule;
1976 TheModule = 0;
1977 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001978 }
Chris Lattner00950542001-06-06 20:29:01 +00001979}
Reid Spencer060d25d2004-06-29 23:29:38 +00001980
1981//===----------------------------------------------------------------------===//
1982//=== Default Implementations of Handler Methods
1983//===----------------------------------------------------------------------===//
1984
1985BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00001986
1987// vim: sw=2