blob: 3ebd7c88f4d39d533716ccbb585a8306a90e625e [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 Spencer46b002c2004-07-11 17:28:43 +000032namespace {
33
Reid Spencer060d25d2004-06-29 23:29:38 +000034/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000035/// as a placeholder for the actual definition for forward constants defs.
36class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer060d25d2004-06-29 23:29:38 +000037 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +000038 ConstantPlaceHolder(); // DO NOT IMPLEMENT
39 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000040public:
Reid Spencer46b002c2004-07-11 17:28:43 +000041 ConstantPlaceHolder(const Type *Ty, unsigned id)
42 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
43 ID(id) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000044 unsigned getID() { return ID; }
45};
Chris Lattner9e460f22003-10-04 20:00:03 +000046
Reid Spencer46b002c2004-07-11 17:28:43 +000047}
Reid Spencer060d25d2004-06-29 23:29:38 +000048
Reid Spencer24399722004-07-09 22:21:33 +000049// Provide some details on error
50inline void BytecodeReader::error(std::string err) {
51 err += " (Vers=" ;
52 err += itostr(RevisionNum) ;
53 err += ", Pos=" ;
54 err += itostr(At-MemStart);
55 err += ")";
56 throw err;
57}
58
Reid Spencer060d25d2004-06-29 23:29:38 +000059//===----------------------------------------------------------------------===//
60// Bytecode Reading Methods
61//===----------------------------------------------------------------------===//
62
Reid Spencer04cde2c2004-07-04 11:33:49 +000063/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000064inline bool BytecodeReader::moreInBlock() {
65 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000066}
67
Reid Spencer04cde2c2004-07-04 11:33:49 +000068/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000069inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000070 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000071 error(std::string("Attempt to read past the end of ") + block_name + " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000072}
Chris Lattner36392bc2003-10-08 21:18:57 +000073
Reid Spencer04cde2c2004-07-04 11:33:49 +000074/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000075inline void BytecodeReader::align32() {
76 BufPtr Save = At;
77 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
Reid Spencer46b002c2004-07-11 17:28:43 +000078 if (At > Save)
79 if (Handler) Handler->handleAlignment(At - Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000080 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000081 error("Ran out of data while aligning!");
Reid Spencer060d25d2004-06-29 23:29:38 +000082}
83
Reid Spencer04cde2c2004-07-04 11:33:49 +000084/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000085inline unsigned BytecodeReader::read_uint() {
86 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000087 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000088 At += 4;
89 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
90}
91
Reid Spencer04cde2c2004-07-04 11:33:49 +000092/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000093inline unsigned BytecodeReader::read_vbr_uint() {
94 unsigned Shift = 0;
95 unsigned Result = 0;
96 BufPtr Save = At;
97
98 do {
99 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000100 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000101 Result |= (unsigned)((*At++) & 0x7F) << Shift;
102 Shift += 7;
103 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000104 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000105 return Result;
106}
107
Reid Spencer04cde2c2004-07-04 11:33:49 +0000108/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000109inline uint64_t BytecodeReader::read_vbr_uint64() {
110 unsigned Shift = 0;
111 uint64_t Result = 0;
112 BufPtr Save = At;
113
114 do {
115 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000116 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000117 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
118 Shift += 7;
119 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000120 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000121 return Result;
122}
123
Reid Spencer04cde2c2004-07-04 11:33:49 +0000124/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000125inline int64_t BytecodeReader::read_vbr_int64() {
126 uint64_t R = read_vbr_uint64();
127 if (R & 1) {
128 if (R != 1)
129 return -(int64_t)(R >> 1);
130 else // There is no such thing as -0 with integers. "-0" really means
131 // 0x8000000000000000.
132 return 1LL << 63;
133 } else
134 return (int64_t)(R >> 1);
135}
136
Reid Spencer04cde2c2004-07-04 11:33:49 +0000137/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000138inline std::string BytecodeReader::read_str() {
139 unsigned Size = read_vbr_uint();
140 const unsigned char *OldAt = At;
141 At += Size;
142 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000143 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000144 return std::string((char*)OldAt, Size);
145}
146
Reid Spencer04cde2c2004-07-04 11:33:49 +0000147/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000148inline void BytecodeReader::read_data(void *Ptr, void *End) {
149 unsigned char *Start = (unsigned char *)Ptr;
150 unsigned Amount = (unsigned char *)End - Start;
151 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000152 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000153 std::copy(At, At+Amount, Start);
154 At += Amount;
155}
156
Reid Spencer46b002c2004-07-11 17:28:43 +0000157/// Read a float value in little-endian order
158inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000159 /// FIXME: This isn't optimal, it has size problems on some platforms
160 /// where FP is not IEEE.
161 union {
162 float f;
163 uint32_t i;
164 } FloatUnion;
165 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
166 At+=sizeof(uint32_t);
167 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000168}
169
170/// Read a double value in little-endian order
171inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000172 /// FIXME: This isn't optimal, it has size problems on some platforms
173 /// where FP is not IEEE.
174 union {
175 double d;
176 uint64_t i;
177 } DoubleUnion;
Chris Lattner1d785162004-07-25 23:15:44 +0000178 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
179 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Reid Spencerada16182004-07-25 21:36:26 +0000180 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
181 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
182 At+=sizeof(uint64_t);
183 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000184}
185
Reid Spencer04cde2c2004-07-04 11:33:49 +0000186/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000187inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000188 if ( hasLongBlockHeaders ) {
189 Type = read_uint();
190 Size = read_uint();
191 switch (Type) {
192 case BytecodeFormat::Reserved_DoNotUse :
193 error("Reserved_DoNotUse used as Module Type?");
194 Type = BytecodeFormat::Module; break;
195 case BytecodeFormat::Module:
196 Type = BytecodeFormat::ModuleBlockID; break;
197 case BytecodeFormat::Function:
198 Type = BytecodeFormat::FunctionBlockID; break;
199 case BytecodeFormat::ConstantPool:
200 Type = BytecodeFormat::ConstantPoolBlockID; break;
201 case BytecodeFormat::SymbolTable:
202 Type = BytecodeFormat::SymbolTableBlockID; break;
203 case BytecodeFormat::ModuleGlobalInfo:
204 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
205 case BytecodeFormat::GlobalTypePlane:
206 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
207 case BytecodeFormat::InstructionList:
208 Type = BytecodeFormat::InstructionListBlockID; break;
209 case BytecodeFormat::CompactionTable:
210 Type = BytecodeFormat::CompactionTableBlockID; break;
211 case BytecodeFormat::BasicBlock:
212 /// This block type isn't used after version 1.1. However, we have to
213 /// still allow the value in case this is an old bc format file.
214 /// We just let its value creep thru.
215 break;
216 default:
217 error("Invalid module type found: " + utostr(Type));
218 break;
219 }
220 } else {
221 Size = read_uint();
222 Type = Size & 0x1F; // mask low order five bits
223 Size >>= 5; // get rid of five low order bits, leaving high 27
224 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000225 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000226 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000227 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000228 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000229 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000230}
231
232
233/// In LLVM 1.2 and before, Types were derived from Value and so they were
234/// written as part of the type planes along with any other Value. In LLVM
235/// 1.3 this changed so that Type does not derive from Value. Consequently,
236/// the BytecodeReader's containers for Values can't contain Types because
237/// there's no inheritance relationship. This means that the "Type Type"
238/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
239/// whenever a bytecode construct must have both types and values together,
240/// the types are always read/written first and then the Values. Furthermore
241/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
242/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
243/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
244/// For LLVM 1.2 and before, this function will decrement the type id by
245/// one to account for the missing Type::TypeTyID enumerator if the value is
246/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
247/// function returns true, otherwise false. This helps detect situations
248/// where the pre 1.3 bytecode is indicating that what follows is a type.
249/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000250inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
251 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
252 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000253 TypeId = Type::VoidTyID; // sanitize it
254 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000255 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000256 --TypeId; // shift all planes down because type type plane is missing
257 }
258 return false;
259}
260
261/// Reads a vbr uint to read in a type id and does the necessary
262/// conversion on it by calling sanitizeTypeId.
263/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
264/// @see sanitizeTypeId
265inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
266 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000267 if ( !has32BitTypes )
268 if ( TypeId == 0x00FFFFFF )
269 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000270 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000271}
272
273//===----------------------------------------------------------------------===//
274// IR Lookup Methods
275//===----------------------------------------------------------------------===//
276
Reid Spencer04cde2c2004-07-04 11:33:49 +0000277/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000278inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000279 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000280 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000281 return TyID >= Type::FirstDerivedTyID;
282}
283
Reid Spencer04cde2c2004-07-04 11:33:49 +0000284/// Obtain a type given a typeid and account for things like compaction tables,
285/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000286const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000287 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000288 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000289 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000290
291 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000292 ID -= Type::FirstDerivedTyID;
293
Reid Spencer060d25d2004-06-29 23:29:38 +0000294 if (!CompactionTypes.empty()) {
295 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000296 error("Type ID out of range for compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000297 return CompactionTypes[ID];
Chris Lattner89e02532004-01-18 21:08:15 +0000298 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000299
300 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000301 if (ID < ModuleTypes.size())
302 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000303
Reid Spencer46b002c2004-07-11 17:28:43 +0000304 // Nope, is it a function-level type?
305 ID -= ModuleTypes.size();
306 if (ID < FunctionTypes.size())
307 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000308
Reid Spencer46b002c2004-07-11 17:28:43 +0000309 error("Illegal type reference!");
310 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000311}
312
Reid Spencer04cde2c2004-07-04 11:33:49 +0000313/// Get a sanitized type id. This just makes sure that the \p ID
314/// is both sanitized and not the "type type" of pre-1.3 bytecode.
315/// @see sanitizeTypeId
316inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000317 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000318 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000319 return getType(ID);
320}
321
322/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000323/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000324/// then calls getType to return the type value.
325inline const Type* BytecodeReader::readSanitizedType() {
326 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000327 if (read_typeid(ID))
328 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000329 return getType(ID);
330}
331
332/// Get the slot number associated with a type accounting for primitive
333/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000334unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
335 if (Ty->isPrimitiveType())
336 return Ty->getTypeID();
337
338 // Scan the compaction table for the type if needed.
339 if (!CompactionTypes.empty()) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000340 std::vector<const Type*>::const_iterator I =
341 find(CompactionTypes.begin(), CompactionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000342
Reid Spencer46b002c2004-07-11 17:28:43 +0000343 if (I == CompactionTypes.end())
344 error("Couldn't find type specified in compaction table!");
345 return Type::FirstDerivedTyID + (&*I - &CompactionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000346 }
347
348 // Check the function level types first...
349 TypeListTy::iterator I = find(FunctionTypes.begin(), FunctionTypes.end(), Ty);
350
351 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000352 return Type::FirstDerivedTyID + ModuleTypes.size() +
353 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000354
355 // Check the module level types now...
356 I = find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
357 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000358 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000359 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000360}
361
Reid Spencer04cde2c2004-07-04 11:33:49 +0000362/// This is just like getType, but when a compaction table is in use, it is
363/// ignored. It also ignores function level types.
364/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000365const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
366 if (Slot < Type::FirstDerivedTyID) {
367 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000368 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000369 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000370 return Ty;
371 }
372 Slot -= Type::FirstDerivedTyID;
373 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000374 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000375 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000376}
377
Reid Spencer04cde2c2004-07-04 11:33:49 +0000378/// This is just like getTypeSlot, but when a compaction table is in use, it
379/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000380unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
381 if (Ty->isPrimitiveType())
382 return Ty->getTypeID();
383 TypeListTy::iterator I = find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000384 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000385 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000386 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000387 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
388}
389
Reid Spencer04cde2c2004-07-04 11:33:49 +0000390/// Retrieve a value of a given type and slot number, possibly creating
391/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000392Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000393 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000394 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000395
Chris Lattner89e02532004-01-18 21:08:15 +0000396 // If there is a compaction table active, it defines the low-level numbers.
397 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000398 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
399 if (Num < CompactionValues[type].size())
400 return CompactionValues[type][Num];
401 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000402 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000403 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000404 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000405
406 // If the type plane was compactified, figure out the global type ID
407 // by adding the derived type ids and the distance.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000408 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000409 const Type *Ty = CompactionTypes[type-Type::FirstDerivedTyID];
410 TypeListTy::iterator I =
Reid Spencer04cde2c2004-07-04 11:33:49 +0000411 find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000412 assert(I != ModuleTypes.end());
413 GlobalTyID = Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner52f86d62004-01-20 00:54:06 +0000414 }
Chris Lattner00950542001-06-06 20:29:01 +0000415
Reid Spencer060d25d2004-06-29 23:29:38 +0000416 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000417 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000418 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000419 --Num;
420 }
421
Chris Lattner52f86d62004-01-20 00:54:06 +0000422 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
423 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000424 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000425 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000426 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000427 }
428
Reid Spencer060d25d2004-06-29 23:29:38 +0000429 if (FunctionValues.size() > type &&
430 FunctionValues[type] &&
431 Num < FunctionValues[type]->size())
432 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000433
Chris Lattner74734132002-08-17 22:01:27 +0000434 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000435
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000436 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000437 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000438 if (I != ForwardReferences.end() && I->first == KeyValue)
439 return I->second; // We have already created this placeholder
440
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000441 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000442 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000443 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000444}
445
Reid Spencer04cde2c2004-07-04 11:33:49 +0000446/// This is just like getValue, but when a compaction table is in use, it
447/// is ignored. Also, no forward references or other fancy features are
448/// supported.
Reid Spencer060d25d2004-06-29 23:29:38 +0000449Value* BytecodeReader::getGlobalTableValue(const Type *Ty, unsigned SlotNo) {
450 // FIXME: getTypeSlot is inefficient!
451 unsigned TyID = getGlobalTableTypeSlot(Ty);
452
453 if (TyID != Type::LabelTyID) {
454 if (SlotNo == 0)
455 return Constant::getNullValue(Ty);
456 --SlotNo;
457 }
458
459 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
460 SlotNo >= ModuleValues[TyID]->size()) {
Reid Spencer24399722004-07-09 22:21:33 +0000461 error("Corrupt compaction table entry!"
462 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Reid Spencer46b002c2004-07-11 17:28:43 +0000463 + utostr(ModuleValues.size()) + ", "
Brian Gaeke0859e522004-07-13 07:37:43 +0000464 + utohexstr(intptr_t((void*)ModuleValues[TyID])) + ", "
Reid Spencer46b002c2004-07-11 17:28:43 +0000465 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000466 }
467 return ModuleValues[TyID]->getOperand(SlotNo);
468}
469
Reid Spencer04cde2c2004-07-04 11:33:49 +0000470/// Just like getValue, except that it returns a null pointer
471/// only on error. It always returns a constant (meaning that if the value is
472/// defined, but is not a constant, that is an error). If the specified
473/// constant hasn't been parsed yet, a placeholder is defined and used.
474/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000475Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
476 if (Value *V = getValue(TypeSlot, Slot, false))
477 if (Constant *C = dyn_cast<Constant>(V))
478 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000479 else
Reid Spencera86037e2004-07-18 00:12:03 +0000480 error("Value for slot " + utostr(Slot) +
481 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000482
483 const Type *Ty = getType(TypeSlot);
484 std::pair<const Type*, unsigned> Key(Ty, Slot);
485 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
486
487 if (I != ConstantFwdRefs.end() && I->first == Key) {
488 return I->second;
489 } else {
490 // Create a placeholder for the constant reference and
491 // keep track of the fact that we have a forward ref to recycle it
Reid Spencer46b002c2004-07-11 17:28:43 +0000492 Constant *C = new ConstantPlaceHolder(Ty, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000493
494 // Keep track of the fact that we have a forward ref to recycle it
495 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
496 return C;
497 }
498}
499
500//===----------------------------------------------------------------------===//
501// IR Construction Methods
502//===----------------------------------------------------------------------===//
503
Reid Spencer04cde2c2004-07-04 11:33:49 +0000504/// As values are created, they are inserted into the appropriate place
505/// with this method. The ValueTable argument must be one of ModuleValues
506/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000507unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
508 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000509 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000510 !hasImplicitNull(type) &&
511 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000512
513 if (ValueTab.size() <= type)
514 ValueTab.resize(type+1);
515
516 if (!ValueTab[type]) ValueTab[type] = new ValueList();
517
518 ValueTab[type]->push_back(Val);
519
520 bool HasOffset = hasImplicitNull(type);
521 return ValueTab[type]->size()-1 + HasOffset;
522}
523
Reid Spencer04cde2c2004-07-04 11:33:49 +0000524/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000525void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000526 const FunctionType *FT = F->getFunctionType();
527 Function::aiterator AI = F->abegin();
528 for (FunctionType::param_iterator It = FT->param_begin();
529 It != FT->param_end(); ++It, ++AI)
530 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
531}
532
533//===----------------------------------------------------------------------===//
534// Bytecode Parsing Methods
535//===----------------------------------------------------------------------===//
536
Reid Spencer04cde2c2004-07-04 11:33:49 +0000537/// This method parses a single instruction. The instruction is
538/// inserted at the end of the \p BB provided. The arguments of
539/// the instruction are provided in the \p Args vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000540void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000541 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000542 BufPtr SaveAt = At;
543
544 // Clear instruction data
545 Oprnds.clear();
546 unsigned iType = 0;
547 unsigned Opcode = 0;
548 unsigned Op = read_uint();
549
550 // bits Instruction format: Common to all formats
551 // --------------------------
552 // 01-00: Opcode type, fixed to 1.
553 // 07-02: Opcode
554 Opcode = (Op >> 2) & 63;
555 Oprnds.resize((Op >> 0) & 03);
556
557 // Extract the operands
558 switch (Oprnds.size()) {
559 case 1:
560 // bits Instruction format:
561 // --------------------------
562 // 19-08: Resulting type plane
563 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
564 //
565 iType = (Op >> 8) & 4095;
566 Oprnds[0] = (Op >> 20) & 4095;
567 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
568 Oprnds.resize(0);
569 break;
570 case 2:
571 // bits Instruction format:
572 // --------------------------
573 // 15-08: Resulting type plane
574 // 23-16: Operand #1
575 // 31-24: Operand #2
576 //
577 iType = (Op >> 8) & 255;
578 Oprnds[0] = (Op >> 16) & 255;
579 Oprnds[1] = (Op >> 24) & 255;
580 break;
581 case 3:
582 // bits Instruction format:
583 // --------------------------
584 // 13-08: Resulting type plane
585 // 19-14: Operand #1
586 // 25-20: Operand #2
587 // 31-26: Operand #3
588 //
589 iType = (Op >> 8) & 63;
590 Oprnds[0] = (Op >> 14) & 63;
591 Oprnds[1] = (Op >> 20) & 63;
592 Oprnds[2] = (Op >> 26) & 63;
593 break;
594 case 0:
595 At -= 4; // Hrm, try this again...
596 Opcode = read_vbr_uint();
597 Opcode >>= 2;
598 iType = read_vbr_uint();
599
600 unsigned NumOprnds = read_vbr_uint();
601 Oprnds.resize(NumOprnds);
602
603 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000604 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000605
606 for (unsigned i = 0; i != NumOprnds; ++i)
607 Oprnds[i] = read_vbr_uint();
608 align32();
609 break;
610 }
611
Reid Spencer04cde2c2004-07-04 11:33:49 +0000612 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000613
Reid Spencer46b002c2004-07-11 17:28:43 +0000614 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000615 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000616
617 // Declare the resulting instruction we'll build.
618 Instruction *Result = 0;
619
620 // Handle binary operators
621 if (Opcode >= Instruction::BinaryOpsBegin &&
622 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
623 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
624 getValue(iType, Oprnds[0]),
625 getValue(iType, Oprnds[1]));
626
627 switch (Opcode) {
628 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000629 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000630 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000631 break;
632 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000633 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000634 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000635 break;
636 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000637 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000638 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000639 break;
640 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000641 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000642 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000643 break;
644 case Instruction::Select:
645 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
646 getValue(iType, Oprnds[1]),
647 getValue(iType, Oprnds[2]));
648 break;
649 case Instruction::PHI: {
650 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000651 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000652
653 PHINode *PN = new PHINode(InstTy);
654 PN->op_reserve(Oprnds.size());
655 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
656 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
657 Result = PN;
658 break;
659 }
660
661 case Instruction::Shl:
662 case Instruction::Shr:
663 Result = new ShiftInst((Instruction::OtherOps)Opcode,
664 getValue(iType, Oprnds[0]),
665 getValue(Type::UByteTyID, Oprnds[1]));
666 break;
667 case Instruction::Ret:
668 if (Oprnds.size() == 0)
669 Result = new ReturnInst();
670 else if (Oprnds.size() == 1)
671 Result = new ReturnInst(getValue(iType, Oprnds[0]));
672 else
Reid Spencer24399722004-07-09 22:21:33 +0000673 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000674 break;
675
676 case Instruction::Br:
677 if (Oprnds.size() == 1)
678 Result = new BranchInst(getBasicBlock(Oprnds[0]));
679 else if (Oprnds.size() == 3)
680 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000681 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000682 else
Reid Spencer24399722004-07-09 22:21:33 +0000683 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000684 break;
685 case Instruction::Switch: {
686 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000687 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000688
689 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
690 getBasicBlock(Oprnds[1]));
691 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
692 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
693 getBasicBlock(Oprnds[i+1]));
694 Result = I;
695 break;
696 }
697
698 case Instruction::Call: {
699 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000700 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000701
702 Value *F = getValue(iType, Oprnds[0]);
703
704 // Check to make sure we have a pointer to function type
705 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000706 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000707 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000708 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000709
710 std::vector<Value *> Params;
711 if (!FTy->isVarArg()) {
712 FunctionType::param_iterator It = FTy->param_begin();
713
714 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
715 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000716 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000717 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
718 }
719 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000720 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000721 } else {
722 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
723
724 unsigned FirstVariableOperand;
725 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000726 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000727
728 // Read all of the fixed arguments
729 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
730 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
731
732 FirstVariableOperand = FTy->getNumParams();
733
734 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
Reid Spencer24399722004-07-09 22:21:33 +0000735 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000736
737 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000738 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000739 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
740 }
741
742 Result = new CallInst(F, Params);
743 break;
744 }
745 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000746 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000747 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000748 Value *F = getValue(iType, Oprnds[0]);
749
750 // Check to make sure we have a pointer to function type
751 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000752 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000753 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000754 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000755 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000756 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000757
758 std::vector<Value *> Params;
759 BasicBlock *Normal, *Except;
760
761 if (!FTy->isVarArg()) {
762 Normal = getBasicBlock(Oprnds[1]);
763 Except = getBasicBlock(Oprnds[2]);
764
765 FunctionType::param_iterator It = FTy->param_begin();
766 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
767 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000768 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000769 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
770 }
771 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000772 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000773 } else {
774 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
775
776 Normal = getBasicBlock(Oprnds[0]);
777 Except = getBasicBlock(Oprnds[1]);
778
779 unsigned FirstVariableArgument = FTy->getNumParams()+2;
780 for (unsigned i = 2; i != FirstVariableArgument; ++i)
781 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
782 Oprnds[i]));
783
784 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000785 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000786
787 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
788 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
789 }
790
791 Result = new InvokeInst(F, Normal, Except, Params);
792 break;
793 }
794 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000795 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000796 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000797 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000798 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000799
800 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
801 Oprnds.size() ? getValue(Type::UIntTyID,
802 Oprnds[0]) : 0);
803 break;
804
805 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000806 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000807 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000808 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000809 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000810
811 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
812 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000813 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000814 break;
815 case Instruction::Free:
816 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000817 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000818 Result = new FreeInst(getValue(iType, Oprnds[0]));
819 break;
820 case Instruction::GetElementPtr: {
821 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000822 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000823
824 std::vector<Value*> Idx;
825
826 const Type *NextTy = InstTy;
827 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
828 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000829 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000830 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000831
832 unsigned ValIdx = Oprnds[i];
833 unsigned IdxTy = 0;
834 if (!hasRestrictedGEPTypes) {
835 // Struct indices are always uints, sequential type indices can be any
836 // of the 32 or 64-bit integer types. The actual choice of type is
837 // encoded in the low two bits of the slot number.
838 if (isa<StructType>(TopTy))
839 IdxTy = Type::UIntTyID;
840 else {
841 switch (ValIdx & 3) {
842 default:
843 case 0: IdxTy = Type::UIntTyID; break;
844 case 1: IdxTy = Type::IntTyID; break;
845 case 2: IdxTy = Type::ULongTyID; break;
846 case 3: IdxTy = Type::LongTyID; break;
847 }
848 ValIdx >>= 2;
849 }
850 } else {
851 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
852 }
853
854 Idx.push_back(getValue(IdxTy, ValIdx));
855
856 // Convert ubyte struct indices into uint struct indices.
857 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
858 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
859 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
860
861 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
862 }
863
864 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
865 break;
866 }
867
868 case 62: // volatile load
869 case Instruction::Load:
870 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000871 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000872 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
873 break;
874
875 case 63: // volatile store
876 case Instruction::Store: {
877 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000878 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000879
880 Value *Ptr = getValue(iType, Oprnds[1]);
881 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
882 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
883 Opcode == 63);
884 break;
885 }
886 case Instruction::Unwind:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000887 if (Oprnds.size() != 0)
Reid Spencer24399722004-07-09 22:21:33 +0000888 error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000889 Result = new UnwindInst();
890 break;
891 } // end switch(Opcode)
892
893 unsigned TypeSlot;
894 if (Result->getType() == InstTy)
895 TypeSlot = iType;
896 else
897 TypeSlot = getTypeSlot(Result->getType());
898
899 insertValue(Result, TypeSlot, FunctionValues);
900 BB->getInstList().push_back(Result);
901}
902
Reid Spencer04cde2c2004-07-04 11:33:49 +0000903/// Get a particular numbered basic block, which might be a forward reference.
904/// This works together with ParseBasicBlock to handle these forward references
905/// in a clean manner. This function is used when constructing phi, br, switch,
906/// and other instructions that reference basic blocks. Blocks are numbered
907/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000908BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000909 // Make sure there is room in the table...
910 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
911
912 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
913 // has already created this block, or if the forward reference has already
914 // been created.
915 if (ParsedBasicBlocks[ID])
916 return ParsedBasicBlocks[ID];
917
918 // Otherwise, the basic block has not yet been created. Do so and add it to
919 // the ParsedBasicBlocks list.
920 return ParsedBasicBlocks[ID] = new BasicBlock();
921}
922
Reid Spencer04cde2c2004-07-04 11:33:49 +0000923/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
924/// This method reads in one of the basicblock packets. This method is not used
925/// for bytecode files after LLVM 1.0
926/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000927BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
928 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000929
930 BasicBlock *BB = 0;
931
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000932 if (ParsedBasicBlocks.size() == BlockNo)
933 ParsedBasicBlocks.push_back(BB = new BasicBlock());
934 else if (ParsedBasicBlocks[BlockNo] == 0)
935 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
936 else
937 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000938
Reid Spencer060d25d2004-06-29 23:29:38 +0000939 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000940 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000941 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000942
Reid Spencer46b002c2004-07-11 17:28:43 +0000943 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000944 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000945}
946
Reid Spencer04cde2c2004-07-04 11:33:49 +0000947/// Parse all of the BasicBlock's & Instruction's in the body of a function.
948/// In post 1.0 bytecode files, we no longer emit basic block individually,
949/// in order to avoid per-basic-block overhead.
950/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000951unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000952 unsigned BlockNo = 0;
953 std::vector<unsigned> Args;
954
Reid Spencer46b002c2004-07-11 17:28:43 +0000955 while (moreInBlock()) {
956 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000957 BasicBlock *BB;
958 if (ParsedBasicBlocks.size() == BlockNo)
959 ParsedBasicBlocks.push_back(BB = new BasicBlock());
960 else if (ParsedBasicBlocks[BlockNo] == 0)
961 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
962 else
963 BB = ParsedBasicBlocks[BlockNo];
964 ++BlockNo;
965 F->getBasicBlockList().push_back(BB);
966
967 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000968 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000969 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000970
971 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000972 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000973
Reid Spencer46b002c2004-07-11 17:28:43 +0000974 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000975 }
976
977 return BlockNo;
978}
979
Reid Spencer04cde2c2004-07-04 11:33:49 +0000980/// Parse a symbol table. This works for both module level and function
981/// level symbol tables. For function level symbol tables, the CurrentFunction
982/// parameter must be non-zero and the ST parameter must correspond to
983/// CurrentFunction's symbol table. For Module level symbol tables, the
984/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +0000985void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000986 SymbolTable *ST) {
987 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000988
Chris Lattner39cacce2003-10-10 05:43:47 +0000989 // Allow efficient basic block lookup by number.
990 std::vector<BasicBlock*> BBMap;
991 if (CurrentFunction)
992 for (Function::iterator I = CurrentFunction->begin(),
993 E = CurrentFunction->end(); I != E; ++I)
994 BBMap.push_back(I);
995
Reid Spencer04cde2c2004-07-04 11:33:49 +0000996 /// In LLVM 1.3 we write types separately from values so
997 /// The types are always first in the symbol table. This is
998 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +0000999 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001000 // Symtab block header: [num entries]
1001 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001002 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001003 // Symtab entry: [def slot #][name]
1004 unsigned slot = read_vbr_uint();
1005 std::string Name = read_str();
1006 const Type* T = getType(slot);
1007 ST->insert(Name, T);
1008 }
1009 }
1010
Reid Spencer46b002c2004-07-11 17:28:43 +00001011 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001012 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001013 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001014 unsigned Typ = 0;
1015 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001016 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001017
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001018 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001019 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001020 unsigned slot = read_vbr_uint();
1021 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001022
Reid Spencer04cde2c2004-07-04 11:33:49 +00001023 // if we're reading a pre 1.3 bytecode file and the type plane
1024 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001025 if (isTypeType) {
1026 const Type* T = getType(slot);
1027 if (T == 0)
1028 error("Failed type look-up for name '" + Name + "'");
1029 ST->insert(Name, T);
1030 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001031 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001032 Value *V = 0;
1033 if (Typ == Type::LabelTyID) {
1034 if (slot < BBMap.size())
1035 V = BBMap[slot];
1036 } else {
1037 V = getValue(Typ, slot, false); // Find mapping...
1038 }
1039 if (V == 0)
1040 error("Failed value look-up for name '" + Name + "'");
1041 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +00001042 }
Chris Lattner00950542001-06-06 20:29:01 +00001043 }
1044 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001045 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001046 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001047}
1048
Reid Spencer04cde2c2004-07-04 11:33:49 +00001049/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001050void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001051 for (unsigned i = 0; i != NumEntries; ++i) {
1052 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001053 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001054 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001055 const Type *Typ = getGlobalTableType(TypeSlot);
1056 CompactionTypes.push_back(Typ);
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001058 }
1059}
1060
1061/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001062void BytecodeReader::ParseCompactionTable() {
1063
Reid Spencer46b002c2004-07-11 17:28:43 +00001064 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001065 if (Handler) Handler->handleCompactionTableBegin();
1066
Reid Spencer46b002c2004-07-11 17:28:43 +00001067 // In LLVM 1.3 Type no longer derives from Value. So,
1068 // we always write them first in the compaction table
1069 // because they can't occupy a "type plane" where the
1070 // Values reside.
1071 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001072 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001073 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001074 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001075
Reid Spencer46b002c2004-07-11 17:28:43 +00001076 // Compaction tables live in separate blocks so we have to loop
1077 // until we've read the whole thing.
1078 while (moreInBlock()) {
1079 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001080 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001081 unsigned Ty = 0;
1082 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001083
Reid Spencer46b002c2004-07-11 17:28:43 +00001084 // Decode the type from value read in. Most compaction table
1085 // planes will have one or two entries in them. If that's the
1086 // case then the length is encoded in the bottom two bits and
1087 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001088 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001089 // In this case, both low-order bits are set (value 3). This
1090 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001091 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001092 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001093 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001094 // In this case, the low-order bits specify the number of entries
1095 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001096 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001097 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001098 NumEntries &= 3;
1099 }
1100
Reid Spencer04cde2c2004-07-04 11:33:49 +00001101 // if we're reading a pre 1.3 bytecode file and the type plane
1102 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001103 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001104 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001105 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001106 // Make sure we have enough room for the plane
Reid Spencer04cde2c2004-07-04 11:33:49 +00001107 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001108 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001109
Reid Spencer46b002c2004-07-11 17:28:43 +00001110 // Make sure the plane is empty or we have some kind of error
Reid Spencer04cde2c2004-07-04 11:33:49 +00001111 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001112 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001113
Reid Spencer46b002c2004-07-11 17:28:43 +00001114 // Notify handler about the plane
1115 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001116
Reid Spencer46b002c2004-07-11 17:28:43 +00001117 // Convert the type slot to a type
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 const Type *Typ = getType(Ty);
Reid Spencer46b002c2004-07-11 17:28:43 +00001119
Reid Spencer060d25d2004-06-29 23:29:38 +00001120 // Push the implicit zero
1121 CompactionValues[Ty].push_back(Constant::getNullValue(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001122
1123 // Read in each of the entries, put them in the compaction table
1124 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001125 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001126 unsigned ValSlot = read_vbr_uint();
1127 Value *V = getGlobalTableValue(Typ, ValSlot);
1128 CompactionValues[Ty].push_back(V);
1129 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot, Typ);
Reid Spencer060d25d2004-06-29 23:29:38 +00001130 }
1131 }
1132 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001133 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001134 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001135}
1136
Reid Spencer46b002c2004-07-11 17:28:43 +00001137// Parse a single type. The typeid is read in first. If its a primitive type
1138// then nothing else needs to be read, we know how to instantiate it. If its
1139// a derived type, then additional data is read to fill out the type
1140// definition.
1141const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001142 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001143 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001144 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001145
1146 const Type *Result = 0;
1147 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1148 return Result;
1149
1150 switch (PrimType) {
1151 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001152 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001153
1154 unsigned NumParams = read_vbr_uint();
1155
1156 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001157 while (NumParams--)
1158 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001159
1160 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1161 if (isVarArg) Params.pop_back();
1162
1163 Result = FunctionType::get(RetType, Params, isVarArg);
1164 break;
1165 }
1166 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001167 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001168 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001169 Result = ArrayType::get(ElementType, NumElements);
1170 break;
1171 }
1172 case Type::StructTyID: {
1173 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001174 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001175 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001176 error("Invalid element type (type type) for structure!");
1177
Reid Spencer060d25d2004-06-29 23:29:38 +00001178 while (Typ) { // List is terminated by void/0 typeid
1179 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001180 if (read_typeid(Typ))
1181 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001182 }
1183
1184 Result = StructType::get(Elements);
1185 break;
1186 }
1187 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001188 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001189 break;
1190 }
1191
1192 case Type::OpaqueTyID: {
1193 Result = OpaqueType::get();
1194 break;
1195 }
1196
1197 default:
Reid Spencer24399722004-07-09 22:21:33 +00001198 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001199 break;
1200 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001201 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001202 return Result;
1203}
1204
Reid Spencer46b002c2004-07-11 17:28:43 +00001205// ParseType - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001206// types. We know that recursive types will only reference the current slab of
1207// values in the type plane, but they can forward reference types before they
1208// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1209// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1210// this ugly problem, we pessimistically insert an opaque type for each type we
1211// are about to read. This means that forward references will resolve to
1212// something and when we reread the type later, we can replace the opaque type
1213// with a new resolved concrete type.
1214//
Reid Spencer46b002c2004-07-11 17:28:43 +00001215void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001216 assert(Tab.size() == 0 && "should not have read type constants in before!");
1217
1218 // Insert a bunch of opaque types to be resolved later...
1219 Tab.reserve(NumEntries);
1220 for (unsigned i = 0; i != NumEntries; ++i)
1221 Tab.push_back(OpaqueType::get());
1222
1223 // Loop through reading all of the types. Forward types will make use of the
1224 // opaque types just inserted.
1225 //
1226 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001227 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001228 const Type* OldTy = Tab[i].get();
1229 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001230 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001231
1232 // Don't directly push the new type on the Tab. Instead we want to replace
1233 // the opaque type we previously inserted with the new concrete value. This
1234 // approach helps with forward references to types. The refinement from the
1235 // abstract (opaque) type to the new type causes all uses of the abstract
1236 // type to use the concrete type (NewTy). This will also cause the opaque
1237 // type to be deleted.
1238 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1239
1240 // This should have replaced the old opaque type with the new type in the
1241 // value table... or with a preexisting type that was already in the system.
1242 // Let's just make sure it did.
1243 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1244 }
1245}
1246
Reid Spencer04cde2c2004-07-04 11:33:49 +00001247/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001248Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001249 // We must check for a ConstantExpr before switching by type because
1250 // a ConstantExpr can be of any type, and has no explicit value.
1251 //
1252 // 0 if not expr; numArgs if is expr
1253 unsigned isExprNumArgs = read_vbr_uint();
1254
1255 if (isExprNumArgs) {
1256 // FIXME: Encoding of constant exprs could be much more compact!
1257 std::vector<Constant*> ArgVec;
1258 ArgVec.reserve(isExprNumArgs);
1259 unsigned Opcode = read_vbr_uint();
1260
1261 // Read the slot number and types of each of the arguments
1262 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1263 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001264 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001265 if (read_typeid(ArgTypeSlot))
1266 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001267
1268 // Get the arg value from its slot if it exists, otherwise a placeholder
1269 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1270 }
1271
1272 // Construct a ConstantExpr of the appropriate kind
1273 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001274 if (Opcode != Instruction::Cast)
1275 error("Only Cast instruction has one argument for ConstantExpr");
1276
Reid Spencer060d25d2004-06-29 23:29:38 +00001277 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001278 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001279 return Result;
1280 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1281 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1282
1283 if (hasRestrictedGEPTypes) {
1284 const Type *BaseTy = ArgVec[0]->getType();
1285 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1286 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1287 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1288 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1289 if (isa<StructType>(*GTI)) {
1290 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001291 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001292 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1293 }
1294 }
1295
1296 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001297 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001298 return Result;
1299 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001300 if (ArgVec.size() != 3)
1301 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001302 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001303 ArgVec[2]);
1304 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001305 return Result;
1306 } else { // All other 2-operand expressions
1307 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001308 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001309 return Result;
1310 }
1311 }
1312
1313 // Ok, not an ConstantExpr. We now know how to read the given type...
1314 const Type *Ty = getType(TypeID);
1315 switch (Ty->getTypeID()) {
1316 case Type::BoolTyID: {
1317 unsigned Val = read_vbr_uint();
1318 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001319 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001320 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001321 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001322 return Result;
1323 }
1324
1325 case Type::UByteTyID: // Unsigned integer types...
1326 case Type::UShortTyID:
1327 case Type::UIntTyID: {
1328 unsigned Val = read_vbr_uint();
1329 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001330 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001331 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001332 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001333 return Result;
1334 }
1335
1336 case Type::ULongTyID: {
1337 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001338 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001339 return Result;
1340 }
1341
1342 case Type::SByteTyID: // Signed integer types...
1343 case Type::ShortTyID:
1344 case Type::IntTyID: {
1345 case Type::LongTyID:
1346 int64_t Val = read_vbr_int64();
1347 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001348 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001349 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001350 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001351 return Result;
1352 }
1353
1354 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001355 float Val;
1356 read_float(Val);
1357 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001358 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001359 return Result;
1360 }
1361
1362 case Type::DoubleTyID: {
1363 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001364 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001365 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001366 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001367 return Result;
1368 }
1369
Reid Spencer060d25d2004-06-29 23:29:38 +00001370 case Type::ArrayTyID: {
1371 const ArrayType *AT = cast<ArrayType>(Ty);
1372 unsigned NumElements = AT->getNumElements();
1373 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1374 std::vector<Constant*> Elements;
1375 Elements.reserve(NumElements);
1376 while (NumElements--) // Read all of the elements of the constant.
1377 Elements.push_back(getConstantValue(TypeSlot,
1378 read_vbr_uint()));
1379 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001380 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001381 return Result;
1382 }
1383
1384 case Type::StructTyID: {
1385 const StructType *ST = cast<StructType>(Ty);
1386
1387 std::vector<Constant *> Elements;
1388 Elements.reserve(ST->getNumElements());
1389 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1390 Elements.push_back(getConstantValue(ST->getElementType(i),
1391 read_vbr_uint()));
1392
1393 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001395 return Result;
1396 }
1397
1398 case Type::PointerTyID: { // ConstantPointerRef value...
1399 const PointerType *PT = cast<PointerType>(Ty);
1400 unsigned Slot = read_vbr_uint();
1401
1402 // Check to see if we have already read this global variable...
1403 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001404 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001405 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1406 if (!GV) error("GlobalValue not in ValueTable!");
1407 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1408 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001410 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001411 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001412 }
1413
1414 default:
Reid Spencer24399722004-07-09 22:21:33 +00001415 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001416 Ty->getDescription());
1417 break;
1418 }
Reid Spencer24399722004-07-09 22:21:33 +00001419 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001420}
1421
Reid Spencer04cde2c2004-07-04 11:33:49 +00001422/// Resolve references for constants. This function resolves the forward
1423/// referenced constants in the ConstantFwdRefs map. It uses the
1424/// replaceAllUsesWith method of Value class to substitute the placeholder
1425/// instance with the actual instance.
Reid Spencer060d25d2004-06-29 23:29:38 +00001426void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001427 ConstantRefsType::iterator I =
1428 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1429 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001430
Chris Lattner29b789b2003-11-19 17:27:18 +00001431 Value *PH = I->second; // Get the placeholder...
1432 PH->replaceAllUsesWith(NewV);
1433 delete PH; // Delete the old placeholder
1434 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001435}
1436
Reid Spencer04cde2c2004-07-04 11:33:49 +00001437/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001438void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1439 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001440 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001441 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001442 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001443 const Type *Ty = getType(Typ);
1444 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001445 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001446
1447 const ArrayType *ATy = cast<ArrayType>(Ty);
1448 if (ATy->getElementType() != Type::SByteTy &&
1449 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001450 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001451
1452 // Read character data. The type tells us how long the string is.
1453 char Data[ATy->getNumElements()];
1454 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001455
Reid Spencer060d25d2004-06-29 23:29:38 +00001456 std::vector<Constant*> Elements(ATy->getNumElements());
1457 if (ATy->getElementType() == Type::SByteTy)
1458 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1459 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1460 else
1461 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1462 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001463
Reid Spencer060d25d2004-06-29 23:29:38 +00001464 // Create the constant, inserting it as needed.
1465 Constant *C = ConstantArray::get(ATy, Elements);
1466 unsigned Slot = insertValue(C, Typ, Tab);
1467 ResolveReferencesToConstant(C, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001468 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001469 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001470}
1471
Reid Spencer04cde2c2004-07-04 11:33:49 +00001472/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001473void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001474 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001475 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001476 if (Handler) Handler->handleGlobalConstantsBegin();
1477
1478 /// In LLVM 1.3 Type does not derive from Value so the types
1479 /// do not occupy a plane. Consequently, we read the types
1480 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001481 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001482 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001483 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001484 }
1485
Reid Spencer46b002c2004-07-11 17:28:43 +00001486 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001487 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001488 unsigned Typ = 0;
1489 bool isTypeType = read_typeid(Typ);
1490
1491 /// In LLVM 1.2 and before, Types were written to the
1492 /// bytecode file in the "Type Type" plane (#12).
1493 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001494 if (isTypeType) {
1495 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001496 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001497 /// Use of Type::VoidTyID is a misnomer. It actually means
1498 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001499 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1500 ParseStringConstants(NumEntries, Tab);
1501 } else {
1502 for (unsigned i = 0; i < NumEntries; ++i) {
1503 Constant *C = ParseConstantValue(Typ);
1504 assert(C && "ParseConstantValue returned NULL!");
1505 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001506
Reid Spencer060d25d2004-06-29 23:29:38 +00001507 // If we are reading a function constant table, make sure that we adjust
1508 // the slot number to be the real global constant number.
1509 //
1510 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1511 ModuleValues[Typ])
1512 Slot += ModuleValues[Typ]->size();
1513 ResolveReferencesToConstant(C, Slot);
1514 }
1515 }
1516 }
1517 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001518 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001519}
Chris Lattner00950542001-06-06 20:29:01 +00001520
Reid Spencer04cde2c2004-07-04 11:33:49 +00001521/// Parse the contents of a function. Note that this function can be
1522/// called lazily by materializeFunction
1523/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001524void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001525
1526 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001527 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1528
Reid Spencer060d25d2004-06-29 23:29:38 +00001529 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001530 switch (LinkageType) {
1531 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1532 case 1: Linkage = GlobalValue::WeakLinkage; break;
1533 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1534 case 3: Linkage = GlobalValue::InternalLinkage; break;
1535 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001536 default:
Reid Spencer24399722004-07-09 22:21:33 +00001537 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001538 Linkage = GlobalValue::InternalLinkage;
1539 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001540 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001541
Reid Spencer46b002c2004-07-11 17:28:43 +00001542 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001543 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001544
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001545 // Keep track of how many basic blocks we have read in...
1546 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001547 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001548
Reid Spencer060d25d2004-06-29 23:29:38 +00001549 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001550 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001551 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001552 BufPtr OldAt = At;
1553 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001554
1555 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001556 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001557 if (!InsertedArguments) {
1558 // Insert arguments into the value table before we parse the first basic
1559 // block in the function, but after we potentially read in the
1560 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001561 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001562 InsertedArguments = true;
1563 }
1564
Reid Spencer04cde2c2004-07-04 11:33:49 +00001565 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001566 break;
1567
Reid Spencerad89bd62004-07-25 18:07:36 +00001568 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001569 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001570 break;
1571
Chris Lattner00950542001-06-06 20:29:01 +00001572 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001573 if (!InsertedArguments) {
1574 // Insert arguments into the value table before we parse the first basic
1575 // block in the function, but after we potentially read in the
1576 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001577 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001578 InsertedArguments = true;
1579 }
1580
Reid Spencer060d25d2004-06-29 23:29:38 +00001581 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001582 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001583 break;
1584 }
1585
Reid Spencerad89bd62004-07-25 18:07:36 +00001586 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001587 // Insert arguments into the value table before we parse the instruction
1588 // list for the function, but after we potentially read in the compaction
1589 // table.
1590 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001591 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001592 InsertedArguments = true;
1593 }
1594
Reid Spencer060d25d2004-06-29 23:29:38 +00001595 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001596 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001597 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001598 break;
1599 }
1600
Reid Spencerad89bd62004-07-25 18:07:36 +00001601 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001602 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001603 break;
1604
1605 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001606 At += Size;
1607 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001608 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001609 break;
1610 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001611 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001612
Misha Brukman12c29d12003-09-22 23:38:23 +00001613 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001614 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001615 }
1616
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001617 // Make sure there were no references to non-existant basic blocks.
1618 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001619 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001620
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001621 ParsedBasicBlocks.clear();
1622
Chris Lattner97330cf2003-10-09 23:10:14 +00001623 // Resolve forward references. Replace any uses of a forward reference value
1624 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001625
Chris Lattner97330cf2003-10-09 23:10:14 +00001626 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1627 // number of operands. PHI nodes often have forward references, and can also
1628 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001629 //
1630 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1631 // should be simplified back to using it!
1632 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001633 std::map<Value*, Value*> ForwardRefMapping;
1634 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1635 I = ForwardReferences.begin(), E = ForwardReferences.end();
1636 I != E; ++I)
1637 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1638 false);
1639
1640 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1641 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1642 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1643 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
1644 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1645 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1646 }
1647
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001648 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001649 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1650 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001651 Value *PlaceHolder = I->second;
1652 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001653
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001654 // Now that all the uses are gone, delete the placeholder...
1655 // If we couldn't find a def (error case), then leak a little
1656 // memory, because otherwise we can't remove all uses!
1657 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001658 }
Chris Lattner00950542001-06-06 20:29:01 +00001659
Misha Brukman12c29d12003-09-22 23:38:23 +00001660 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001661 FunctionTypes.clear();
1662 CompactionTypes.clear();
1663 CompactionValues.clear();
1664 freeTable(FunctionValues);
1665
Reid Spencer04cde2c2004-07-04 11:33:49 +00001666 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001667}
1668
Reid Spencer04cde2c2004-07-04 11:33:49 +00001669/// This function parses LLVM functions lazily. It obtains the type of the
1670/// function and records where the body of the function is in the bytecode
1671/// buffer. The caller can then use the ParseNextFunction and
1672/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001673void BytecodeReader::ParseFunctionLazily() {
1674 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001675 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001676
Reid Spencer060d25d2004-06-29 23:29:38 +00001677 Function *Func = FunctionSignatureList.back();
1678 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001679
Reid Spencer060d25d2004-06-29 23:29:38 +00001680 // Save the information for future reading of the function
1681 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001682
Reid Spencer060d25d2004-06-29 23:29:38 +00001683 // Pretend we've `parsed' this function
1684 At = BlockEnd;
1685}
Chris Lattner89e02532004-01-18 21:08:15 +00001686
Reid Spencer04cde2c2004-07-04 11:33:49 +00001687/// The ParserFunction method lazily parses one function. Use this method to
1688/// casue the parser to parse a specific function in the module. Note that
1689/// this will remove the function from what is to be included by
1690/// ParseAllFunctionBodies.
1691/// @see ParseAllFunctionBodies
1692/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001693void BytecodeReader::ParseFunction(Function* Func) {
1694 // Find {start, end} pointers and slot in the map. If not there, we're done.
1695 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001696
Reid Spencer060d25d2004-06-29 23:29:38 +00001697 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001698 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001699 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001700 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001701 }
1702
Reid Spencer060d25d2004-06-29 23:29:38 +00001703 BlockStart = At = Fi->second.Buf;
1704 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001705 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001706
1707 LazyFunctionLoadMap.erase(Fi);
1708
Reid Spencer46b002c2004-07-11 17:28:43 +00001709 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001710}
1711
Reid Spencer04cde2c2004-07-04 11:33:49 +00001712/// The ParseAllFunctionBodies method parses through all the previously
1713/// unparsed functions in the bytecode file. If you want to completely parse
1714/// a bytecode file, this method should be called after Parsebytecode because
1715/// Parsebytecode only records the locations in the bytecode file of where
1716/// the function definitions are located. This function uses that information
1717/// to materialize the functions.
1718/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001719void BytecodeReader::ParseAllFunctionBodies() {
1720 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1721 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001722
Reid Spencer46b002c2004-07-11 17:28:43 +00001723 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001724 Function* Func = Fi->first;
1725 BlockStart = At = Fi->second.Buf;
1726 BlockEnd = Fi->second.EndBuf;
1727 this->ParseFunctionBody(Func);
1728 ++Fi;
1729 }
1730}
Chris Lattner89e02532004-01-18 21:08:15 +00001731
Reid Spencer04cde2c2004-07-04 11:33:49 +00001732/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001733void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001734 // Read the number of types
1735 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001736
1737 // Ignore the type plane identifier for types if the bc file is pre 1.3
1738 if (hasTypeDerivedFromValue)
1739 read_vbr_uint();
1740
Reid Spencer46b002c2004-07-11 17:28:43 +00001741 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001742}
1743
Reid Spencer04cde2c2004-07-04 11:33:49 +00001744/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001745void BytecodeReader::ParseModuleGlobalInfo() {
1746
Reid Spencer04cde2c2004-07-04 11:33:49 +00001747 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001748
Chris Lattner70cc3392001-09-10 07:58:01 +00001749 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001750 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001751 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001752 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1753 // Linkage, bit4+ = slot#
1754 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001755 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001756 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001757 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001758 bool isConstant = VarType & 1;
1759 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001760 GlobalValue::LinkageTypes Linkage;
1761
Chris Lattnerc08912f2004-01-14 16:44:44 +00001762 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001763 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1764 case 1: Linkage = GlobalValue::WeakLinkage; break;
1765 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1766 case 3: Linkage = GlobalValue::InternalLinkage; break;
1767 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001768 default:
Reid Spencer24399722004-07-09 22:21:33 +00001769 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001770 Linkage = GlobalValue::InternalLinkage;
1771 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001772 }
1773
1774 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001775 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001776 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001777 }
1778
Reid Spencer46b002c2004-07-11 17:28:43 +00001779 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001780 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001781 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001782
Chris Lattner52e20b02003-03-19 20:54:26 +00001783 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001784
Chris Lattner70cc3392001-09-10 07:58:01 +00001785 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001786 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001787 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001788 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001789
Reid Spencer060d25d2004-06-29 23:29:38 +00001790 unsigned initSlot = 0;
1791 if (hasInitializer) {
1792 initSlot = read_vbr_uint();
1793 GlobalInits.push_back(std::make_pair(GV, initSlot));
1794 }
1795
1796 // Notify handler about the global value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001797 if (Handler) Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001798
1799 // Get next item
1800 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001801 }
1802
Chris Lattner52e20b02003-03-19 20:54:26 +00001803 // Read the function objects for all of the functions that are coming
Reid Spencer04cde2c2004-07-04 11:33:49 +00001804 unsigned FnSignature = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001805 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001806 error("Invalid function type (type type) found");
1807
Chris Lattner74734132002-08-17 22:01:27 +00001808 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1809 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +00001810 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001811 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001812 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001813 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001814 // FIXME: what should Ty be if handler continues?
1815 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001816
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001817 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001818 const FunctionType* FTy =
1819 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001820
Reid Spencer060d25d2004-06-29 23:29:38 +00001821 // Insert the place hodler
1822 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001823 "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001824 insertValue(Func, FnSignature, ModuleValues);
Chris Lattner00950542001-06-06 20:29:01 +00001825
Reid Spencer060d25d2004-06-29 23:29:38 +00001826 // Save this for later so we know type of lazily instantiated functions
Chris Lattner29b789b2003-11-19 17:27:18 +00001827 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001828
Reid Spencer04cde2c2004-07-04 11:33:49 +00001829 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001830
1831 // Get Next function signature
Reid Spencer46b002c2004-07-11 17:28:43 +00001832 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001833 error("Invalid function type (type type) found");
Chris Lattner00950542001-06-06 20:29:01 +00001834 }
1835
Chris Lattner74734132002-08-17 22:01:27 +00001836 // Now that the function signature list is set up, reverse it so that we can
1837 // remove elements efficiently from the back of the vector.
1838 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001839
Reid Spencerad89bd62004-07-25 18:07:36 +00001840 // If this bytecode format has dependent library information in it ..
1841 if (!hasNoDependentLibraries) {
1842 // Read in the number of dependent library items that follow
1843 unsigned num_dep_libs = read_vbr_uint();
1844 std::string dep_lib;
1845 while( num_dep_libs-- ) {
1846 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001847 TheModule->addLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001848 }
1849
1850 // Read target triple and place into the module
1851 std::string triple = read_str();
1852 TheModule->setTargetTriple(triple);
1853 }
1854
1855 if (hasInconsistentModuleGlobalInfo)
1856 align32();
1857
Chris Lattner00950542001-06-06 20:29:01 +00001858 // This is for future proofing... in the future extra fields may be added that
1859 // we don't understand, so we transparently ignore them.
1860 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001861 At = BlockEnd;
1862
Reid Spencer04cde2c2004-07-04 11:33:49 +00001863 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001864}
1865
Reid Spencer04cde2c2004-07-04 11:33:49 +00001866/// Parse the version information and decode it by setting flags on the
1867/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001868void BytecodeReader::ParseVersionInfo() {
1869 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001870
1871 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001872 Module::Endianness Endianness;
1873 Module::PointerSize PointerSize;
1874 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1875 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1876
1877 bool hasNoEndianness = Version & 4;
1878 bool hasNoPointerSize = Version & 8;
1879
1880 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001881
1882 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001883 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001884 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001885 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001886 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001887 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001888 has32BitTypes = false;
1889 hasNoDependentLibraries = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001890
1891 switch (RevisionNum) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001892 case 0: // LLVM 1.0, 1.1 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001893 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001894 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001895 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001896
Reid Spencerad89bd62004-07-25 18:07:36 +00001897
Chris Lattner80b97342004-01-17 23:25:43 +00001898 // FALL THROUGH
Chris Lattnerc08912f2004-01-14 16:44:44 +00001899 case 1: // LLVM 1.2 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001900 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001901
1902 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1903 // included the size for the alignment at the end, where the rest of the
1904 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001905
1906 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1907 // structures and longs for sequential types.
1908 hasRestrictedGEPTypes = true;
1909
Reid Spencer04cde2c2004-07-04 11:33:49 +00001910 // LLVM 1.2 and before had the Type class derive from Value class. This
1911 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1912 // written differently because Types can no longer be part of the
1913 // type planes for Values.
1914 hasTypeDerivedFromValue = true;
1915
Chris Lattner5fa428f2004-04-05 01:27:26 +00001916 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001917
1918 case 2: /// 1.2.5 (mid-release) version
1919
1920 /// LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1921 /// especially for small files where the 8 bytes per block is a large fraction
1922 /// of the total block size. In LLVM 1.3, the block type and length are
1923 /// compressed into a single 32-bit unsigned integer. 27 bits for length, 5
1924 /// bits for block type.
1925 hasLongBlockHeaders = true;
1926
Reid Spencerad89bd62004-07-25 18:07:36 +00001927 /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
1928 /// this has been reduced to vbr_uint24. It shouldn't make much difference
1929 /// since we haven't run into a module with > 24 million types, but for safety
1930 /// the 24-bit restriction has been enforced in 1.3 to free some bits in
1931 /// various places and to ensure consistency.
1932 has32BitTypes = true;
1933
1934 /// LLVM 1.2 and earlier did not provide a target triple nor a list of
1935 /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
1936 /// features, for use in future versions of LLVM.
1937 hasNoDependentLibraries = true;
1938
1939 // FALL THROUGH
1940 case 3: // LLVM 1.3 release version
Chris Lattnerc08912f2004-01-14 16:44:44 +00001941 break;
1942
Chris Lattner036b8aa2003-03-06 17:55:45 +00001943 default:
Reid Spencer24399722004-07-09 22:21:33 +00001944 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00001945 }
1946
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001947 if (hasNoEndianness) Endianness = Module::AnyEndianness;
1948 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00001949
Brian Gaekefe2102b2004-07-14 20:33:13 +00001950 TheModule->setEndianness(Endianness);
1951 TheModule->setPointerSize(PointerSize);
1952
Reid Spencer46b002c2004-07-11 17:28:43 +00001953 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001954}
1955
Reid Spencer04cde2c2004-07-04 11:33:49 +00001956/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001957void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001958 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001959
Reid Spencer060d25d2004-06-29 23:29:38 +00001960 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001961
1962 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001963 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00001964 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001965
Reid Spencer060d25d2004-06-29 23:29:38 +00001966 bool SeenModuleGlobalInfo = false;
1967 bool SeenGlobalTypePlane = false;
1968 BufPtr MyEnd = BlockEnd;
1969 while (At < MyEnd) {
1970 BufPtr OldAt = At;
1971 read_block(Type, Size);
1972
Chris Lattner00950542001-06-06 20:29:01 +00001973 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001974
Reid Spencerad89bd62004-07-25 18:07:36 +00001975 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001976 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001977 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001978
1979 ParseGlobalTypes();
1980 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001981 break;
1982
Reid Spencerad89bd62004-07-25 18:07:36 +00001983 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001984 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001985 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001986 ParseModuleGlobalInfo();
1987 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001988 break;
1989
Reid Spencerad89bd62004-07-25 18:07:36 +00001990 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001991 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001992 break;
1993
Reid Spencerad89bd62004-07-25 18:07:36 +00001994 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001995 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001996 break;
Chris Lattner00950542001-06-06 20:29:01 +00001997
Reid Spencerad89bd62004-07-25 18:07:36 +00001998 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001999 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002000 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002001
Chris Lattner00950542001-06-06 20:29:01 +00002002 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002003 At += Size;
2004 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002005 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002006 }
Chris Lattner00950542001-06-06 20:29:01 +00002007 break;
2008 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002009 BlockEnd = MyEnd;
2010 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002011 }
2012
Chris Lattner52e20b02003-03-19 20:54:26 +00002013 // After the module constant pool has been read, we can safely initialize
2014 // global variables...
2015 while (!GlobalInits.empty()) {
2016 GlobalVariable *GV = GlobalInits.back().first;
2017 unsigned Slot = GlobalInits.back().second;
2018 GlobalInits.pop_back();
2019
2020 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002021 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002022
2023 const llvm::PointerType* GVType = GV->getType();
2024 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002025 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002026 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002027 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002028 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002029 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002030 } else
Reid Spencer24399722004-07-09 22:21:33 +00002031 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002032 }
2033
Reid Spencer060d25d2004-06-29 23:29:38 +00002034 /// Make sure we pulled them all out. If we didn't then there's a declaration
2035 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002036 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002037 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002038}
2039
Reid Spencer04cde2c2004-07-04 11:33:49 +00002040/// This function completely parses a bytecode buffer given by the \p Buf
2041/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002042void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2043 const std::string &ModuleID,
2044 bool processFunctions) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002045
Reid Spencer060d25d2004-06-29 23:29:38 +00002046 try {
2047 At = MemStart = BlockStart = Buf;
2048 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002049
Reid Spencer060d25d2004-06-29 23:29:38 +00002050 // Create the module
2051 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002052
Reid Spencer04cde2c2004-07-04 11:33:49 +00002053 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002054
2055 // Read and check signature...
2056 unsigned Sig = read_uint();
2057 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
Reid Spencer24399722004-07-09 22:21:33 +00002058 error("Invalid bytecode signature: " + utostr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002059 }
2060
Reid Spencer060d25d2004-06-29 23:29:38 +00002061 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002062 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002063
Reid Spencerad89bd62004-07-25 18:07:36 +00002064 // Get the module block and size and verify. This is handled specially
2065 // because the module block/size is always written in long format. Other
2066 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002067 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002068 Type = read_uint();
2069 Size = read_uint();
2070 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002071 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002072 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002073 }
Reid Spencer46b002c2004-07-11 17:28:43 +00002074 if (At + Size != MemEnd) {
Reid Spencer24399722004-07-09 22:21:33 +00002075 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002076 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002077 }
2078
2079 // Parse the module contents
2080 this->ParseModule();
2081
Reid Spencer060d25d2004-06-29 23:29:38 +00002082 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002083 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002084 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002085
Reid Spencer5c15fe52004-07-05 00:57:50 +00002086 // Process all the function bodies now, if requested
Reid Spencer46b002c2004-07-11 17:28:43 +00002087 if (processFunctions)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002088 ParseAllFunctionBodies();
2089
2090 // Tell the handler we're done with the module
2091 if (Handler)
2092 Handler->handleModuleEnd(ModuleID);
2093
2094 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002095 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002096
Reid Spencer46b002c2004-07-11 17:28:43 +00002097 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002098 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002099 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002100 delete TheModule;
2101 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002102 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002103 } catch (...) {
2104 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002105 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002106 freeState();
2107 delete TheModule;
2108 TheModule = 0;
2109 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002110 }
Chris Lattner00950542001-06-06 20:29:01 +00002111}
Reid Spencer060d25d2004-06-29 23:29:38 +00002112
2113//===----------------------------------------------------------------------===//
2114//=== Default Implementations of Handler Methods
2115//===----------------------------------------------------------------------===//
2116
2117BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002118
2119// vim: sw=2