blob: a9dbe9d54550155a2684ceb48ac5017339bf4af9 [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>
Chris Lattner29b789b2003-11-19 17:27:18 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Reid Spencer46b002c2004-07-11 17:28:43 +000031namespace {
32
Reid Spencer060d25d2004-06-29 23:29:38 +000033/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000034/// as a placeholder for the actual definition for forward constants defs.
35class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer060d25d2004-06-29 23:29:38 +000036 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +000037 ConstantPlaceHolder(); // DO NOT IMPLEMENT
38 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000039public:
Reid Spencer46b002c2004-07-11 17:28:43 +000040 ConstantPlaceHolder(const Type *Ty, unsigned id)
41 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
42 ID(id) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000043 unsigned getID() { return ID; }
44};
Chris Lattner9e460f22003-10-04 20:00:03 +000045
Reid Spencer46b002c2004-07-11 17:28:43 +000046}
Reid Spencer060d25d2004-06-29 23:29:38 +000047
Reid Spencer24399722004-07-09 22:21:33 +000048// Provide some details on error
49inline void BytecodeReader::error(std::string err) {
50 err += " (Vers=" ;
51 err += itostr(RevisionNum) ;
52 err += ", Pos=" ;
53 err += itostr(At-MemStart);
54 err += ")";
55 throw err;
56}
57
Reid Spencer060d25d2004-06-29 23:29:38 +000058//===----------------------------------------------------------------------===//
59// Bytecode Reading Methods
60//===----------------------------------------------------------------------===//
61
Reid Spencer04cde2c2004-07-04 11:33:49 +000062/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000063inline bool BytecodeReader::moreInBlock() {
64 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000065}
66
Reid Spencer04cde2c2004-07-04 11:33:49 +000067/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000068inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000069 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000070 error(std::string("Attempt to read past the end of ") + block_name + " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000071}
Chris Lattner36392bc2003-10-08 21:18:57 +000072
Reid Spencer04cde2c2004-07-04 11:33:49 +000073/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000074inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000075 if (hasAlignment) {
76 BufPtr Save = At;
77 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
78 if (At > Save)
79 if (Handler) Handler->handleAlignment(At - Save);
80 if (At > BlockEnd)
81 error("Ran out of data while aligning!");
82 }
Reid Spencer060d25d2004-06-29 23:29:38 +000083}
84
Reid Spencer04cde2c2004-07-04 11:33:49 +000085/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000086inline unsigned BytecodeReader::read_uint() {
87 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000088 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000089 At += 4;
90 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
91}
92
Reid Spencer04cde2c2004-07-04 11:33:49 +000093/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000094inline unsigned BytecodeReader::read_vbr_uint() {
95 unsigned Shift = 0;
96 unsigned Result = 0;
97 BufPtr Save = At;
98
99 do {
100 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000101 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000102 Result |= (unsigned)((*At++) & 0x7F) << Shift;
103 Shift += 7;
104 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000105 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 return Result;
107}
108
Reid Spencer04cde2c2004-07-04 11:33:49 +0000109/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000110inline uint64_t BytecodeReader::read_vbr_uint64() {
111 unsigned Shift = 0;
112 uint64_t Result = 0;
113 BufPtr Save = At;
114
115 do {
116 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000117 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000118 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
119 Shift += 7;
120 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000121 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000122 return Result;
123}
124
Reid Spencer04cde2c2004-07-04 11:33:49 +0000125/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000126inline int64_t BytecodeReader::read_vbr_int64() {
127 uint64_t R = read_vbr_uint64();
128 if (R & 1) {
129 if (R != 1)
130 return -(int64_t)(R >> 1);
131 else // There is no such thing as -0 with integers. "-0" really means
132 // 0x8000000000000000.
133 return 1LL << 63;
134 } else
135 return (int64_t)(R >> 1);
136}
137
Reid Spencer04cde2c2004-07-04 11:33:49 +0000138/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000139inline std::string BytecodeReader::read_str() {
140 unsigned Size = read_vbr_uint();
141 const unsigned char *OldAt = At;
142 At += Size;
143 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000144 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000145 return std::string((char*)OldAt, Size);
146}
147
Reid Spencer04cde2c2004-07-04 11:33:49 +0000148/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000149inline void BytecodeReader::read_data(void *Ptr, void *End) {
150 unsigned char *Start = (unsigned char *)Ptr;
151 unsigned Amount = (unsigned char *)End - Start;
152 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000153 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000154 std::copy(At, At+Amount, Start);
155 At += Amount;
156}
157
Reid Spencer46b002c2004-07-11 17:28:43 +0000158/// Read a float value in little-endian order
159inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000160 /// FIXME: This isn't optimal, it has size problems on some platforms
161 /// where FP is not IEEE.
162 union {
163 float f;
164 uint32_t i;
165 } FloatUnion;
166 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
167 At+=sizeof(uint32_t);
168 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000169}
170
171/// Read a double value in little-endian order
172inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000173 /// FIXME: This isn't optimal, it has size problems on some platforms
174 /// where FP is not IEEE.
175 union {
176 double d;
177 uint64_t i;
178 } DoubleUnion;
Chris Lattner1d785162004-07-25 23:15:44 +0000179 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
180 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Reid Spencerada16182004-07-25 21:36:26 +0000181 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
182 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
183 At+=sizeof(uint64_t);
184 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000185}
186
Reid Spencer04cde2c2004-07-04 11:33:49 +0000187/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000188inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000189 if ( hasLongBlockHeaders ) {
190 Type = read_uint();
191 Size = read_uint();
192 switch (Type) {
193 case BytecodeFormat::Reserved_DoNotUse :
194 error("Reserved_DoNotUse used as Module Type?");
195 Type = BytecodeFormat::Module; break;
196 case BytecodeFormat::Module:
197 Type = BytecodeFormat::ModuleBlockID; break;
198 case BytecodeFormat::Function:
199 Type = BytecodeFormat::FunctionBlockID; break;
200 case BytecodeFormat::ConstantPool:
201 Type = BytecodeFormat::ConstantPoolBlockID; break;
202 case BytecodeFormat::SymbolTable:
203 Type = BytecodeFormat::SymbolTableBlockID; break;
204 case BytecodeFormat::ModuleGlobalInfo:
205 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
206 case BytecodeFormat::GlobalTypePlane:
207 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
208 case BytecodeFormat::InstructionList:
209 Type = BytecodeFormat::InstructionListBlockID; break;
210 case BytecodeFormat::CompactionTable:
211 Type = BytecodeFormat::CompactionTableBlockID; break;
212 case BytecodeFormat::BasicBlock:
213 /// This block type isn't used after version 1.1. However, we have to
214 /// still allow the value in case this is an old bc format file.
215 /// We just let its value creep thru.
216 break;
217 default:
218 error("Invalid module type found: " + utostr(Type));
219 break;
220 }
221 } else {
222 Size = read_uint();
223 Type = Size & 0x1F; // mask low order five bits
224 Size >>= 5; // get rid of five low order bits, leaving high 27
225 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000226 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000227 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000228 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000229 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000230 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000231}
232
233
234/// In LLVM 1.2 and before, Types were derived from Value and so they were
235/// written as part of the type planes along with any other Value. In LLVM
236/// 1.3 this changed so that Type does not derive from Value. Consequently,
237/// the BytecodeReader's containers for Values can't contain Types because
238/// there's no inheritance relationship. This means that the "Type Type"
239/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
240/// whenever a bytecode construct must have both types and values together,
241/// the types are always read/written first and then the Values. Furthermore
242/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
243/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
244/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
245/// For LLVM 1.2 and before, this function will decrement the type id by
246/// one to account for the missing Type::TypeTyID enumerator if the value is
247/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
248/// function returns true, otherwise false. This helps detect situations
249/// where the pre 1.3 bytecode is indicating that what follows is a type.
250/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000251inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
252 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
253 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000254 TypeId = Type::VoidTyID; // sanitize it
255 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000256 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000257 --TypeId; // shift all planes down because type type plane is missing
258 }
259 return false;
260}
261
262/// Reads a vbr uint to read in a type id and does the necessary
263/// conversion on it by calling sanitizeTypeId.
264/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
265/// @see sanitizeTypeId
266inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
267 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000268 if ( !has32BitTypes )
269 if ( TypeId == 0x00FFFFFF )
270 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000271 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000272}
273
274//===----------------------------------------------------------------------===//
275// IR Lookup Methods
276//===----------------------------------------------------------------------===//
277
Reid Spencer04cde2c2004-07-04 11:33:49 +0000278/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000279inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000280 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000281 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000282 return TyID >= Type::FirstDerivedTyID;
283}
284
Reid Spencer04cde2c2004-07-04 11:33:49 +0000285/// Obtain a type given a typeid and account for things like compaction tables,
286/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000287const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000288 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000289 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000290 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000291
292 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000293 ID -= Type::FirstDerivedTyID;
294
Reid Spencer060d25d2004-06-29 23:29:38 +0000295 if (!CompactionTypes.empty()) {
296 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000297 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000298 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000299 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000300
301 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000302 if (ID < ModuleTypes.size())
303 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000304
Reid Spencer46b002c2004-07-11 17:28:43 +0000305 // Nope, is it a function-level type?
306 ID -= ModuleTypes.size();
307 if (ID < FunctionTypes.size())
308 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000309
Reid Spencer46b002c2004-07-11 17:28:43 +0000310 error("Illegal type reference!");
311 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000312}
313
Reid Spencer04cde2c2004-07-04 11:33:49 +0000314/// Get a sanitized type id. This just makes sure that the \p ID
315/// is both sanitized and not the "type type" of pre-1.3 bytecode.
316/// @see sanitizeTypeId
317inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000318 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000319 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000320 return getType(ID);
321}
322
323/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000324/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000325/// then calls getType to return the type value.
326inline const Type* BytecodeReader::readSanitizedType() {
327 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000328 if (read_typeid(ID))
329 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000330 return getType(ID);
331}
332
333/// Get the slot number associated with a type accounting for primitive
334/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000335unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
336 if (Ty->isPrimitiveType())
337 return Ty->getTypeID();
338
339 // Scan the compaction table for the type if needed.
340 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000341 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
342 if (CompactionTypes[i].first == Ty)
343 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000344
Chris Lattner45b5dd22004-08-03 23:41:28 +0000345 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000346 }
347
348 // Check the function level types first...
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
Chris Lattner45b5dd22004-08-03 23:41:28 +0000406 // If the type plane was compactified, figure out the global type ID by
407 // adding the derived type ids and the distance.
408 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
409 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000410
Reid Spencer060d25d2004-06-29 23:29:38 +0000411 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000412 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000413 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000414 --Num;
415 }
416
Chris Lattner52f86d62004-01-20 00:54:06 +0000417 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
418 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000419 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000420 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000421 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000422 }
423
Reid Spencer060d25d2004-06-29 23:29:38 +0000424 if (FunctionValues.size() > type &&
425 FunctionValues[type] &&
426 Num < FunctionValues[type]->size())
427 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000428
Chris Lattner74734132002-08-17 22:01:27 +0000429 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000430
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000431 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000432 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000433 if (I != ForwardReferences.end() && I->first == KeyValue)
434 return I->second; // We have already created this placeholder
435
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000436 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000437 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000438 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000439}
440
Reid Spencer04cde2c2004-07-04 11:33:49 +0000441/// This is just like getValue, but when a compaction table is in use, it
442/// is ignored. Also, no forward references or other fancy features are
443/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000444Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
445 if (SlotNo == 0)
446 return Constant::getNullValue(getType(TyID));
447
448 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
449 TyID -= Type::FirstDerivedTyID;
450 if (TyID >= CompactionTypes.size())
451 error("Type ID out of range for compaction table!");
452 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000453 }
454
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000455 --SlotNo;
456
Reid Spencer060d25d2004-06-29 23:29:38 +0000457 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
458 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000459 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
460 error("Corrupt compaction table entry!"
461 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
462 + utostr(ModuleValues.size()));
463 else
464 error("Corrupt compaction table entry!"
465 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
466 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000467 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
468 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000469 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000470 }
471 return ModuleValues[TyID]->getOperand(SlotNo);
472}
473
Reid Spencer04cde2c2004-07-04 11:33:49 +0000474/// Just like getValue, except that it returns a null pointer
475/// only on error. It always returns a constant (meaning that if the value is
476/// defined, but is not a constant, that is an error). If the specified
477/// constant hasn't been parsed yet, a placeholder is defined and used.
478/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000479Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
480 if (Value *V = getValue(TypeSlot, Slot, false))
481 if (Constant *C = dyn_cast<Constant>(V))
482 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000483 else
Reid Spencera86037e2004-07-18 00:12:03 +0000484 error("Value for slot " + utostr(Slot) +
485 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000486
487 const Type *Ty = getType(TypeSlot);
488 std::pair<const Type*, unsigned> Key(Ty, Slot);
489 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
490
491 if (I != ConstantFwdRefs.end() && I->first == Key) {
492 return I->second;
493 } else {
494 // Create a placeholder for the constant reference and
495 // keep track of the fact that we have a forward ref to recycle it
Reid Spencer46b002c2004-07-11 17:28:43 +0000496 Constant *C = new ConstantPlaceHolder(Ty, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000497
498 // Keep track of the fact that we have a forward ref to recycle it
499 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
500 return C;
501 }
502}
503
504//===----------------------------------------------------------------------===//
505// IR Construction Methods
506//===----------------------------------------------------------------------===//
507
Reid Spencer04cde2c2004-07-04 11:33:49 +0000508/// As values are created, they are inserted into the appropriate place
509/// with this method. The ValueTable argument must be one of ModuleValues
510/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000511unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
512 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000513 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000514 !hasImplicitNull(type) &&
515 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000516
517 if (ValueTab.size() <= type)
518 ValueTab.resize(type+1);
519
520 if (!ValueTab[type]) ValueTab[type] = new ValueList();
521
522 ValueTab[type]->push_back(Val);
523
524 bool HasOffset = hasImplicitNull(type);
525 return ValueTab[type]->size()-1 + HasOffset;
526}
527
Reid Spencer04cde2c2004-07-04 11:33:49 +0000528/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000529void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000530 const FunctionType *FT = F->getFunctionType();
531 Function::aiterator AI = F->abegin();
532 for (FunctionType::param_iterator It = FT->param_begin();
533 It != FT->param_end(); ++It, ++AI)
534 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
535}
536
537//===----------------------------------------------------------------------===//
538// Bytecode Parsing Methods
539//===----------------------------------------------------------------------===//
540
Reid Spencer04cde2c2004-07-04 11:33:49 +0000541/// This method parses a single instruction. The instruction is
542/// inserted at the end of the \p BB provided. The arguments of
543/// the instruction are provided in the \p Args vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000544void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000545 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000546 BufPtr SaveAt = At;
547
548 // Clear instruction data
549 Oprnds.clear();
550 unsigned iType = 0;
551 unsigned Opcode = 0;
552 unsigned Op = read_uint();
553
554 // bits Instruction format: Common to all formats
555 // --------------------------
556 // 01-00: Opcode type, fixed to 1.
557 // 07-02: Opcode
558 Opcode = (Op >> 2) & 63;
559 Oprnds.resize((Op >> 0) & 03);
560
561 // Extract the operands
562 switch (Oprnds.size()) {
563 case 1:
564 // bits Instruction format:
565 // --------------------------
566 // 19-08: Resulting type plane
567 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
568 //
569 iType = (Op >> 8) & 4095;
570 Oprnds[0] = (Op >> 20) & 4095;
571 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
572 Oprnds.resize(0);
573 break;
574 case 2:
575 // bits Instruction format:
576 // --------------------------
577 // 15-08: Resulting type plane
578 // 23-16: Operand #1
579 // 31-24: Operand #2
580 //
581 iType = (Op >> 8) & 255;
582 Oprnds[0] = (Op >> 16) & 255;
583 Oprnds[1] = (Op >> 24) & 255;
584 break;
585 case 3:
586 // bits Instruction format:
587 // --------------------------
588 // 13-08: Resulting type plane
589 // 19-14: Operand #1
590 // 25-20: Operand #2
591 // 31-26: Operand #3
592 //
593 iType = (Op >> 8) & 63;
594 Oprnds[0] = (Op >> 14) & 63;
595 Oprnds[1] = (Op >> 20) & 63;
596 Oprnds[2] = (Op >> 26) & 63;
597 break;
598 case 0:
599 At -= 4; // Hrm, try this again...
600 Opcode = read_vbr_uint();
601 Opcode >>= 2;
602 iType = read_vbr_uint();
603
604 unsigned NumOprnds = read_vbr_uint();
605 Oprnds.resize(NumOprnds);
606
607 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000608 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000609
610 for (unsigned i = 0; i != NumOprnds; ++i)
611 Oprnds[i] = read_vbr_uint();
612 align32();
613 break;
614 }
615
Reid Spencer04cde2c2004-07-04 11:33:49 +0000616 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000617
Reid Spencer46b002c2004-07-11 17:28:43 +0000618 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000619 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000620
621 // Declare the resulting instruction we'll build.
622 Instruction *Result = 0;
623
624 // Handle binary operators
625 if (Opcode >= Instruction::BinaryOpsBegin &&
626 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
627 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
628 getValue(iType, Oprnds[0]),
629 getValue(iType, Oprnds[1]));
630
631 switch (Opcode) {
632 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000633 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000634 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000635 break;
636 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000637 Result = new VAArgInst(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::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000641 Result = new VANextInst(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::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000645 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000646 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000647 break;
648 case Instruction::Select:
649 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
650 getValue(iType, Oprnds[1]),
651 getValue(iType, Oprnds[2]));
652 break;
653 case Instruction::PHI: {
654 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000655 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000656
657 PHINode *PN = new PHINode(InstTy);
658 PN->op_reserve(Oprnds.size());
659 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
660 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
661 Result = PN;
662 break;
663 }
664
665 case Instruction::Shl:
666 case Instruction::Shr:
667 Result = new ShiftInst((Instruction::OtherOps)Opcode,
668 getValue(iType, Oprnds[0]),
669 getValue(Type::UByteTyID, Oprnds[1]));
670 break;
671 case Instruction::Ret:
672 if (Oprnds.size() == 0)
673 Result = new ReturnInst();
674 else if (Oprnds.size() == 1)
675 Result = new ReturnInst(getValue(iType, Oprnds[0]));
676 else
Reid Spencer24399722004-07-09 22:21:33 +0000677 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000678 break;
679
680 case Instruction::Br:
681 if (Oprnds.size() == 1)
682 Result = new BranchInst(getBasicBlock(Oprnds[0]));
683 else if (Oprnds.size() == 3)
684 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000685 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000686 else
Reid Spencer24399722004-07-09 22:21:33 +0000687 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000688 break;
689 case Instruction::Switch: {
690 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000691 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000692
693 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
694 getBasicBlock(Oprnds[1]));
695 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
696 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
697 getBasicBlock(Oprnds[i+1]));
698 Result = I;
699 break;
700 }
701
702 case Instruction::Call: {
703 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000704 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000705
706 Value *F = getValue(iType, Oprnds[0]);
707
708 // Check to make sure we have a pointer to function type
709 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000710 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000711 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000712 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000713
714 std::vector<Value *> Params;
715 if (!FTy->isVarArg()) {
716 FunctionType::param_iterator It = FTy->param_begin();
717
718 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
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 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
722 }
723 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000724 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000725 } else {
726 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
727
728 unsigned FirstVariableOperand;
729 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000730 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000731
732 // Read all of the fixed arguments
733 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
734 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
735
736 FirstVariableOperand = FTy->getNumParams();
737
738 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
Reid Spencer24399722004-07-09 22:21:33 +0000739 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000740
741 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000742 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000743 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
744 }
745
746 Result = new CallInst(F, Params);
747 break;
748 }
749 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000750 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000751 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000752 Value *F = getValue(iType, Oprnds[0]);
753
754 // Check to make sure we have a pointer to function type
755 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000756 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000757 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000758 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000759 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000760 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000761
762 std::vector<Value *> Params;
763 BasicBlock *Normal, *Except;
764
765 if (!FTy->isVarArg()) {
766 Normal = getBasicBlock(Oprnds[1]);
767 Except = getBasicBlock(Oprnds[2]);
768
769 FunctionType::param_iterator It = FTy->param_begin();
770 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
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 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
774 }
775 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000776 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000777 } else {
778 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
779
780 Normal = getBasicBlock(Oprnds[0]);
781 Except = getBasicBlock(Oprnds[1]);
782
783 unsigned FirstVariableArgument = FTy->getNumParams()+2;
784 for (unsigned i = 2; i != FirstVariableArgument; ++i)
785 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
786 Oprnds[i]));
787
788 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000789 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000790
791 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
792 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
793 }
794
795 Result = new InvokeInst(F, Normal, Except, Params);
796 break;
797 }
798 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000799 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000800 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000801 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000802 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000803
804 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
805 Oprnds.size() ? getValue(Type::UIntTyID,
806 Oprnds[0]) : 0);
807 break;
808
809 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000810 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000811 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000812 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000813 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000814
815 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
816 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000817 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000818 break;
819 case Instruction::Free:
820 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000821 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000822 Result = new FreeInst(getValue(iType, Oprnds[0]));
823 break;
824 case Instruction::GetElementPtr: {
825 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000826 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000827
828 std::vector<Value*> Idx;
829
830 const Type *NextTy = InstTy;
831 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
832 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000833 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000834 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000835
836 unsigned ValIdx = Oprnds[i];
837 unsigned IdxTy = 0;
838 if (!hasRestrictedGEPTypes) {
839 // Struct indices are always uints, sequential type indices can be any
840 // of the 32 or 64-bit integer types. The actual choice of type is
841 // encoded in the low two bits of the slot number.
842 if (isa<StructType>(TopTy))
843 IdxTy = Type::UIntTyID;
844 else {
845 switch (ValIdx & 3) {
846 default:
847 case 0: IdxTy = Type::UIntTyID; break;
848 case 1: IdxTy = Type::IntTyID; break;
849 case 2: IdxTy = Type::ULongTyID; break;
850 case 3: IdxTy = Type::LongTyID; break;
851 }
852 ValIdx >>= 2;
853 }
854 } else {
855 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
856 }
857
858 Idx.push_back(getValue(IdxTy, ValIdx));
859
860 // Convert ubyte struct indices into uint struct indices.
861 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
862 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
863 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
864
865 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
866 }
867
868 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
869 break;
870 }
871
872 case 62: // volatile load
873 case Instruction::Load:
874 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000875 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000876 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
877 break;
878
879 case 63: // volatile store
880 case Instruction::Store: {
881 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000882 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000883
884 Value *Ptr = getValue(iType, Oprnds[1]);
885 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
886 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
887 Opcode == 63);
888 break;
889 }
890 case Instruction::Unwind:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000891 if (Oprnds.size() != 0)
Reid Spencer24399722004-07-09 22:21:33 +0000892 error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000893 Result = new UnwindInst();
894 break;
895 } // end switch(Opcode)
896
897 unsigned TypeSlot;
898 if (Result->getType() == InstTy)
899 TypeSlot = iType;
900 else
901 TypeSlot = getTypeSlot(Result->getType());
902
903 insertValue(Result, TypeSlot, FunctionValues);
904 BB->getInstList().push_back(Result);
905}
906
Reid Spencer04cde2c2004-07-04 11:33:49 +0000907/// Get a particular numbered basic block, which might be a forward reference.
908/// This works together with ParseBasicBlock to handle these forward references
909/// in a clean manner. This function is used when constructing phi, br, switch,
910/// and other instructions that reference basic blocks. Blocks are numbered
911/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000912BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000913 // Make sure there is room in the table...
914 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
915
916 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
917 // has already created this block, or if the forward reference has already
918 // been created.
919 if (ParsedBasicBlocks[ID])
920 return ParsedBasicBlocks[ID];
921
922 // Otherwise, the basic block has not yet been created. Do so and add it to
923 // the ParsedBasicBlocks list.
924 return ParsedBasicBlocks[ID] = new BasicBlock();
925}
926
Reid Spencer04cde2c2004-07-04 11:33:49 +0000927/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
928/// This method reads in one of the basicblock packets. This method is not used
929/// for bytecode files after LLVM 1.0
930/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000931BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
932 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000933
934 BasicBlock *BB = 0;
935
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000936 if (ParsedBasicBlocks.size() == BlockNo)
937 ParsedBasicBlocks.push_back(BB = new BasicBlock());
938 else if (ParsedBasicBlocks[BlockNo] == 0)
939 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
940 else
941 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000942
Reid Spencer060d25d2004-06-29 23:29:38 +0000943 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000944 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000945 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000946
Reid Spencer46b002c2004-07-11 17:28:43 +0000947 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000948 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000949}
950
Reid Spencer04cde2c2004-07-04 11:33:49 +0000951/// Parse all of the BasicBlock's & Instruction's in the body of a function.
952/// In post 1.0 bytecode files, we no longer emit basic block individually,
953/// in order to avoid per-basic-block overhead.
954/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000955unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000956 unsigned BlockNo = 0;
957 std::vector<unsigned> Args;
958
Reid Spencer46b002c2004-07-11 17:28:43 +0000959 while (moreInBlock()) {
960 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000961 BasicBlock *BB;
962 if (ParsedBasicBlocks.size() == BlockNo)
963 ParsedBasicBlocks.push_back(BB = new BasicBlock());
964 else if (ParsedBasicBlocks[BlockNo] == 0)
965 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
966 else
967 BB = ParsedBasicBlocks[BlockNo];
968 ++BlockNo;
969 F->getBasicBlockList().push_back(BB);
970
971 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000972 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000973 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000974
975 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000976 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000977
Reid Spencer46b002c2004-07-11 17:28:43 +0000978 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000979 }
980
981 return BlockNo;
982}
983
Reid Spencer04cde2c2004-07-04 11:33:49 +0000984/// Parse a symbol table. This works for both module level and function
985/// level symbol tables. For function level symbol tables, the CurrentFunction
986/// parameter must be non-zero and the ST parameter must correspond to
987/// CurrentFunction's symbol table. For Module level symbol tables, the
988/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +0000989void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000990 SymbolTable *ST) {
991 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000992
Chris Lattner39cacce2003-10-10 05:43:47 +0000993 // Allow efficient basic block lookup by number.
994 std::vector<BasicBlock*> BBMap;
995 if (CurrentFunction)
996 for (Function::iterator I = CurrentFunction->begin(),
997 E = CurrentFunction->end(); I != E; ++I)
998 BBMap.push_back(I);
999
Reid Spencer04cde2c2004-07-04 11:33:49 +00001000 /// In LLVM 1.3 we write types separately from values so
1001 /// The types are always first in the symbol table. This is
1002 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001003 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001004 // Symtab block header: [num entries]
1005 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001006 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001007 // Symtab entry: [def slot #][name]
1008 unsigned slot = read_vbr_uint();
1009 std::string Name = read_str();
1010 const Type* T = getType(slot);
1011 ST->insert(Name, T);
1012 }
1013 }
1014
Reid Spencer46b002c2004-07-11 17:28:43 +00001015 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001016 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001017 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001018 unsigned Typ = 0;
1019 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001020 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001021
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001022 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001023 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001024 unsigned slot = read_vbr_uint();
1025 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001026
Reid Spencer04cde2c2004-07-04 11:33:49 +00001027 // if we're reading a pre 1.3 bytecode file and the type plane
1028 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001029 if (isTypeType) {
1030 const Type* T = getType(slot);
1031 if (T == 0)
1032 error("Failed type look-up for name '" + Name + "'");
1033 ST->insert(Name, T);
1034 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001035 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001036 Value *V = 0;
1037 if (Typ == Type::LabelTyID) {
1038 if (slot < BBMap.size())
1039 V = BBMap[slot];
1040 } else {
1041 V = getValue(Typ, slot, false); // Find mapping...
1042 }
1043 if (V == 0)
1044 error("Failed value look-up for name '" + Name + "'");
1045 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +00001046 }
Chris Lattner00950542001-06-06 20:29:01 +00001047 }
1048 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001049 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001050 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001051}
1052
Reid Spencer04cde2c2004-07-04 11:33:49 +00001053/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001054void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001055 for (unsigned i = 0; i != NumEntries; ++i) {
1056 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001058 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001059 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001060 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001061 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001062 }
1063}
1064
1065/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001066void BytecodeReader::ParseCompactionTable() {
1067
Reid Spencer46b002c2004-07-11 17:28:43 +00001068 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001069 if (Handler) Handler->handleCompactionTableBegin();
1070
Reid Spencer46b002c2004-07-11 17:28:43 +00001071 // In LLVM 1.3 Type no longer derives from Value. So,
1072 // we always write them first in the compaction table
1073 // because they can't occupy a "type plane" where the
1074 // Values reside.
1075 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001076 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001077 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001078 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001079
Reid Spencer46b002c2004-07-11 17:28:43 +00001080 // Compaction tables live in separate blocks so we have to loop
1081 // until we've read the whole thing.
1082 while (moreInBlock()) {
1083 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001084 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001085 unsigned Ty = 0;
1086 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001087
Reid Spencer46b002c2004-07-11 17:28:43 +00001088 // Decode the type from value read in. Most compaction table
1089 // planes will have one or two entries in them. If that's the
1090 // case then the length is encoded in the bottom two bits and
1091 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001092 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001093 // In this case, both low-order bits are set (value 3). This
1094 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001095 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001096 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001097 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001098 // In this case, the low-order bits specify the number of entries
1099 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001100 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001101 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001102 NumEntries &= 3;
1103 }
1104
Reid Spencer04cde2c2004-07-04 11:33:49 +00001105 // if we're reading a pre 1.3 bytecode file and the type plane
1106 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001107 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001108 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001109 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001110 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001111 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001112 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001113
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001114 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001115 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001116 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001117
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001118 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001119 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001120
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001121 // Push the implicit zero.
1122 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001123
1124 // Read in each of the entries, put them in the compaction table
1125 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001126 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001127 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001128 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001129 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001130 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001131 }
1132 }
1133 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001134 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001135 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001136}
1137
Reid Spencer46b002c2004-07-11 17:28:43 +00001138// Parse a single type. The typeid is read in first. If its a primitive type
1139// then nothing else needs to be read, we know how to instantiate it. If its
1140// a derived type, then additional data is read to fill out the type
1141// definition.
1142const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001143 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001144 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001145 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001146
1147 const Type *Result = 0;
1148 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1149 return Result;
1150
1151 switch (PrimType) {
1152 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001153 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001154
1155 unsigned NumParams = read_vbr_uint();
1156
1157 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001158 while (NumParams--)
1159 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001160
1161 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1162 if (isVarArg) Params.pop_back();
1163
1164 Result = FunctionType::get(RetType, Params, isVarArg);
1165 break;
1166 }
1167 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001168 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001169 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001170 Result = ArrayType::get(ElementType, NumElements);
1171 break;
1172 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001173 case Type::PackedTyID: {
1174 const Type *ElementType = readSanitizedType();
1175 unsigned NumElements = read_vbr_uint();
1176 Result = PackedType::get(ElementType, NumElements);
1177 break;
1178 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001179 case Type::StructTyID: {
1180 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001181 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001182 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001183 error("Invalid element type (type type) for structure!");
1184
Reid Spencer060d25d2004-06-29 23:29:38 +00001185 while (Typ) { // List is terminated by void/0 typeid
1186 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001187 if (read_typeid(Typ))
1188 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001189 }
1190
1191 Result = StructType::get(Elements);
1192 break;
1193 }
1194 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001195 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001196 break;
1197 }
1198
1199 case Type::OpaqueTyID: {
1200 Result = OpaqueType::get();
1201 break;
1202 }
1203
1204 default:
Reid Spencer24399722004-07-09 22:21:33 +00001205 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001206 break;
1207 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001208 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001209 return Result;
1210}
1211
Reid Spencer46b002c2004-07-11 17:28:43 +00001212// ParseType - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001213// types. We know that recursive types will only reference the current slab of
1214// values in the type plane, but they can forward reference types before they
1215// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1216// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1217// this ugly problem, we pessimistically insert an opaque type for each type we
1218// are about to read. This means that forward references will resolve to
1219// something and when we reread the type later, we can replace the opaque type
1220// with a new resolved concrete type.
1221//
Reid Spencer46b002c2004-07-11 17:28:43 +00001222void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001223 assert(Tab.size() == 0 && "should not have read type constants in before!");
1224
1225 // Insert a bunch of opaque types to be resolved later...
1226 Tab.reserve(NumEntries);
1227 for (unsigned i = 0; i != NumEntries; ++i)
1228 Tab.push_back(OpaqueType::get());
1229
1230 // Loop through reading all of the types. Forward types will make use of the
1231 // opaque types just inserted.
1232 //
1233 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001234 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001235 const Type* OldTy = Tab[i].get();
1236 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001237 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001238
1239 // Don't directly push the new type on the Tab. Instead we want to replace
1240 // the opaque type we previously inserted with the new concrete value. This
1241 // approach helps with forward references to types. The refinement from the
1242 // abstract (opaque) type to the new type causes all uses of the abstract
1243 // type to use the concrete type (NewTy). This will also cause the opaque
1244 // type to be deleted.
1245 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1246
1247 // This should have replaced the old opaque type with the new type in the
1248 // value table... or with a preexisting type that was already in the system.
1249 // Let's just make sure it did.
1250 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1251 }
1252}
1253
Reid Spencer04cde2c2004-07-04 11:33:49 +00001254/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001255Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001256 // We must check for a ConstantExpr before switching by type because
1257 // a ConstantExpr can be of any type, and has no explicit value.
1258 //
1259 // 0 if not expr; numArgs if is expr
1260 unsigned isExprNumArgs = read_vbr_uint();
1261
1262 if (isExprNumArgs) {
1263 // FIXME: Encoding of constant exprs could be much more compact!
1264 std::vector<Constant*> ArgVec;
1265 ArgVec.reserve(isExprNumArgs);
1266 unsigned Opcode = read_vbr_uint();
1267
1268 // Read the slot number and types of each of the arguments
1269 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1270 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001271 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001272 if (read_typeid(ArgTypeSlot))
1273 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001274
1275 // Get the arg value from its slot if it exists, otherwise a placeholder
1276 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1277 }
1278
1279 // Construct a ConstantExpr of the appropriate kind
1280 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001281 if (Opcode != Instruction::Cast)
1282 error("Only Cast instruction has one argument for ConstantExpr");
1283
Reid Spencer060d25d2004-06-29 23:29:38 +00001284 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001285 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001286 return Result;
1287 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1288 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1289
1290 if (hasRestrictedGEPTypes) {
1291 const Type *BaseTy = ArgVec[0]->getType();
1292 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1293 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1294 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1295 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1296 if (isa<StructType>(*GTI)) {
1297 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001298 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001299 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1300 }
1301 }
1302
1303 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001304 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001305 return Result;
1306 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001307 if (ArgVec.size() != 3)
1308 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001309 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001310 ArgVec[2]);
1311 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001312 return Result;
1313 } else { // All other 2-operand expressions
1314 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001315 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001316 return Result;
1317 }
1318 }
1319
1320 // Ok, not an ConstantExpr. We now know how to read the given type...
1321 const Type *Ty = getType(TypeID);
1322 switch (Ty->getTypeID()) {
1323 case Type::BoolTyID: {
1324 unsigned Val = read_vbr_uint();
1325 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001326 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001327 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001328 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001329 return Result;
1330 }
1331
1332 case Type::UByteTyID: // Unsigned integer types...
1333 case Type::UShortTyID:
1334 case Type::UIntTyID: {
1335 unsigned Val = read_vbr_uint();
1336 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001337 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001338 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001339 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001340 return Result;
1341 }
1342
1343 case Type::ULongTyID: {
1344 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001345 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001346 return Result;
1347 }
1348
1349 case Type::SByteTyID: // Signed integer types...
1350 case Type::ShortTyID:
1351 case Type::IntTyID: {
1352 case Type::LongTyID:
1353 int64_t Val = read_vbr_int64();
1354 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001355 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001356 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001357 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001358 return Result;
1359 }
1360
1361 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001362 float Val;
1363 read_float(Val);
1364 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001365 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001366 return Result;
1367 }
1368
1369 case Type::DoubleTyID: {
1370 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001371 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001372 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001373 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001374 return Result;
1375 }
1376
Reid Spencer060d25d2004-06-29 23:29:38 +00001377 case Type::ArrayTyID: {
1378 const ArrayType *AT = cast<ArrayType>(Ty);
1379 unsigned NumElements = AT->getNumElements();
1380 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1381 std::vector<Constant*> Elements;
1382 Elements.reserve(NumElements);
1383 while (NumElements--) // Read all of the elements of the constant.
1384 Elements.push_back(getConstantValue(TypeSlot,
1385 read_vbr_uint()));
1386 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001387 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001388 return Result;
1389 }
1390
1391 case Type::StructTyID: {
1392 const StructType *ST = cast<StructType>(Ty);
1393
1394 std::vector<Constant *> Elements;
1395 Elements.reserve(ST->getNumElements());
1396 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1397 Elements.push_back(getConstantValue(ST->getElementType(i),
1398 read_vbr_uint()));
1399
1400 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001401 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001402 return Result;
1403 }
1404
Brian Gaeke715c90b2004-08-20 06:00:58 +00001405 case Type::PackedTyID: {
1406 const PackedType *PT = cast<PackedType>(Ty);
1407 unsigned NumElements = PT->getNumElements();
1408 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1409 std::vector<Constant*> Elements;
1410 Elements.reserve(NumElements);
1411 while (NumElements--) // Read all of the elements of the constant.
1412 Elements.push_back(getConstantValue(TypeSlot,
1413 read_vbr_uint()));
1414 Constant* Result = ConstantPacked::get(PT, Elements);
1415 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1416 return Result;
1417 }
1418
Reid Spencer060d25d2004-06-29 23:29:38 +00001419 case Type::PointerTyID: { // ConstantPointerRef value...
1420 const PointerType *PT = cast<PointerType>(Ty);
1421 unsigned Slot = read_vbr_uint();
1422
1423 // Check to see if we have already read this global variable...
1424 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001425 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001426 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1427 if (!GV) error("GlobalValue not in ValueTable!");
1428 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1429 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001430 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001431 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001432 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001433 }
1434
1435 default:
Reid Spencer24399722004-07-09 22:21:33 +00001436 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001437 Ty->getDescription());
1438 break;
1439 }
Reid Spencer24399722004-07-09 22:21:33 +00001440 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001441}
1442
Reid Spencer04cde2c2004-07-04 11:33:49 +00001443/// Resolve references for constants. This function resolves the forward
1444/// referenced constants in the ConstantFwdRefs map. It uses the
1445/// replaceAllUsesWith method of Value class to substitute the placeholder
1446/// instance with the actual instance.
Reid Spencer060d25d2004-06-29 23:29:38 +00001447void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001448 ConstantRefsType::iterator I =
1449 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1450 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001451
Chris Lattner29b789b2003-11-19 17:27:18 +00001452 Value *PH = I->second; // Get the placeholder...
1453 PH->replaceAllUsesWith(NewV);
1454 delete PH; // Delete the old placeholder
1455 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001456}
1457
Reid Spencer04cde2c2004-07-04 11:33:49 +00001458/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001459void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1460 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001461 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001462 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001463 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001464 const Type *Ty = getType(Typ);
1465 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001466 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001467
1468 const ArrayType *ATy = cast<ArrayType>(Ty);
1469 if (ATy->getElementType() != Type::SByteTy &&
1470 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001471 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001472
1473 // Read character data. The type tells us how long the string is.
1474 char Data[ATy->getNumElements()];
1475 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001476
Reid Spencer060d25d2004-06-29 23:29:38 +00001477 std::vector<Constant*> Elements(ATy->getNumElements());
1478 if (ATy->getElementType() == Type::SByteTy)
1479 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1480 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1481 else
1482 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1483 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001484
Reid Spencer060d25d2004-06-29 23:29:38 +00001485 // Create the constant, inserting it as needed.
1486 Constant *C = ConstantArray::get(ATy, Elements);
1487 unsigned Slot = insertValue(C, Typ, Tab);
1488 ResolveReferencesToConstant(C, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001489 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001490 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001491}
1492
Reid Spencer04cde2c2004-07-04 11:33:49 +00001493/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001494void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001495 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001496 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001497 if (Handler) Handler->handleGlobalConstantsBegin();
1498
1499 /// In LLVM 1.3 Type does not derive from Value so the types
1500 /// do not occupy a plane. Consequently, we read the types
1501 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001502 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001503 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001504 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001505 }
1506
Reid Spencer46b002c2004-07-11 17:28:43 +00001507 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001508 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001509 unsigned Typ = 0;
1510 bool isTypeType = read_typeid(Typ);
1511
1512 /// In LLVM 1.2 and before, Types were written to the
1513 /// bytecode file in the "Type Type" plane (#12).
1514 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001515 if (isTypeType) {
1516 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001517 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001518 /// Use of Type::VoidTyID is a misnomer. It actually means
1519 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001520 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1521 ParseStringConstants(NumEntries, Tab);
1522 } else {
1523 for (unsigned i = 0; i < NumEntries; ++i) {
1524 Constant *C = ParseConstantValue(Typ);
1525 assert(C && "ParseConstantValue returned NULL!");
1526 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001527
Reid Spencer060d25d2004-06-29 23:29:38 +00001528 // If we are reading a function constant table, make sure that we adjust
1529 // the slot number to be the real global constant number.
1530 //
1531 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1532 ModuleValues[Typ])
1533 Slot += ModuleValues[Typ]->size();
1534 ResolveReferencesToConstant(C, Slot);
1535 }
1536 }
1537 }
1538 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001539 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001540}
Chris Lattner00950542001-06-06 20:29:01 +00001541
Reid Spencer04cde2c2004-07-04 11:33:49 +00001542/// Parse the contents of a function. Note that this function can be
1543/// called lazily by materializeFunction
1544/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001545void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001546
1547 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001548 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1549
Reid Spencer060d25d2004-06-29 23:29:38 +00001550 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001551 switch (LinkageType) {
1552 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1553 case 1: Linkage = GlobalValue::WeakLinkage; break;
1554 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1555 case 3: Linkage = GlobalValue::InternalLinkage; break;
1556 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001557 default:
Reid Spencer24399722004-07-09 22:21:33 +00001558 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001559 Linkage = GlobalValue::InternalLinkage;
1560 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001561 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001562
Reid Spencer46b002c2004-07-11 17:28:43 +00001563 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001564 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001565
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001566 // Keep track of how many basic blocks we have read in...
1567 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001568 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001569
Reid Spencer060d25d2004-06-29 23:29:38 +00001570 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001571 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001572 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001573 BufPtr OldAt = At;
1574 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001575
1576 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001577 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001578 if (!InsertedArguments) {
1579 // Insert arguments into the value table before we parse the first basic
1580 // block in the function, but after we potentially read in the
1581 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001582 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001583 InsertedArguments = true;
1584 }
1585
Reid Spencer04cde2c2004-07-04 11:33:49 +00001586 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001587 break;
1588
Reid Spencerad89bd62004-07-25 18:07:36 +00001589 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001590 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001591 break;
1592
Chris Lattner00950542001-06-06 20:29:01 +00001593 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001594 if (!InsertedArguments) {
1595 // Insert arguments into the value table before we parse the first basic
1596 // block in the function, but after we potentially read in the
1597 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001598 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001599 InsertedArguments = true;
1600 }
1601
Reid Spencer060d25d2004-06-29 23:29:38 +00001602 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001603 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001604 break;
1605 }
1606
Reid Spencerad89bd62004-07-25 18:07:36 +00001607 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001608 // Insert arguments into the value table before we parse the instruction
1609 // list for the function, but after we potentially read in the compaction
1610 // table.
1611 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001612 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001613 InsertedArguments = true;
1614 }
1615
Reid Spencer060d25d2004-06-29 23:29:38 +00001616 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001617 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001618 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001619 break;
1620 }
1621
Reid Spencerad89bd62004-07-25 18:07:36 +00001622 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001623 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001624 break;
1625
1626 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001627 At += Size;
1628 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001629 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001630 break;
1631 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001632 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001633
Misha Brukman12c29d12003-09-22 23:38:23 +00001634 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001635 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001636 }
1637
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001638 // Make sure there were no references to non-existant basic blocks.
1639 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001640 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001641
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001642 ParsedBasicBlocks.clear();
1643
Chris Lattner97330cf2003-10-09 23:10:14 +00001644 // Resolve forward references. Replace any uses of a forward reference value
1645 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001646
Chris Lattner97330cf2003-10-09 23:10:14 +00001647 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1648 // number of operands. PHI nodes often have forward references, and can also
1649 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001650 //
1651 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1652 // should be simplified back to using it!
1653 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001654 std::map<Value*, Value*> ForwardRefMapping;
1655 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1656 I = ForwardReferences.begin(), E = ForwardReferences.end();
1657 I != E; ++I)
1658 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1659 false);
1660
1661 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1662 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1663 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1664 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
1665 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1666 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1667 }
1668
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001669 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001670 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1671 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001672 Value *PlaceHolder = I->second;
1673 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001674
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001675 // Now that all the uses are gone, delete the placeholder...
1676 // If we couldn't find a def (error case), then leak a little
1677 // memory, because otherwise we can't remove all uses!
1678 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001679 }
Chris Lattner00950542001-06-06 20:29:01 +00001680
Misha Brukman12c29d12003-09-22 23:38:23 +00001681 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001682 FunctionTypes.clear();
1683 CompactionTypes.clear();
1684 CompactionValues.clear();
1685 freeTable(FunctionValues);
1686
Reid Spencer04cde2c2004-07-04 11:33:49 +00001687 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001688}
1689
Reid Spencer04cde2c2004-07-04 11:33:49 +00001690/// This function parses LLVM functions lazily. It obtains the type of the
1691/// function and records where the body of the function is in the bytecode
1692/// buffer. The caller can then use the ParseNextFunction and
1693/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001694void BytecodeReader::ParseFunctionLazily() {
1695 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001696 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001697
Reid Spencer060d25d2004-06-29 23:29:38 +00001698 Function *Func = FunctionSignatureList.back();
1699 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001700
Reid Spencer060d25d2004-06-29 23:29:38 +00001701 // Save the information for future reading of the function
1702 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001703
Reid Spencer060d25d2004-06-29 23:29:38 +00001704 // Pretend we've `parsed' this function
1705 At = BlockEnd;
1706}
Chris Lattner89e02532004-01-18 21:08:15 +00001707
Reid Spencer04cde2c2004-07-04 11:33:49 +00001708/// The ParserFunction method lazily parses one function. Use this method to
1709/// casue the parser to parse a specific function in the module. Note that
1710/// this will remove the function from what is to be included by
1711/// ParseAllFunctionBodies.
1712/// @see ParseAllFunctionBodies
1713/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001714void BytecodeReader::ParseFunction(Function* Func) {
1715 // Find {start, end} pointers and slot in the map. If not there, we're done.
1716 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001717
Reid Spencer060d25d2004-06-29 23:29:38 +00001718 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001719 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001720 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001721 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001722 }
1723
Reid Spencer060d25d2004-06-29 23:29:38 +00001724 BlockStart = At = Fi->second.Buf;
1725 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001726 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001727
1728 LazyFunctionLoadMap.erase(Fi);
1729
Reid Spencer46b002c2004-07-11 17:28:43 +00001730 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001731}
1732
Reid Spencer04cde2c2004-07-04 11:33:49 +00001733/// The ParseAllFunctionBodies method parses through all the previously
1734/// unparsed functions in the bytecode file. If you want to completely parse
1735/// a bytecode file, this method should be called after Parsebytecode because
1736/// Parsebytecode only records the locations in the bytecode file of where
1737/// the function definitions are located. This function uses that information
1738/// to materialize the functions.
1739/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001740void BytecodeReader::ParseAllFunctionBodies() {
1741 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1742 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001743
Reid Spencer46b002c2004-07-11 17:28:43 +00001744 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001745 Function* Func = Fi->first;
1746 BlockStart = At = Fi->second.Buf;
1747 BlockEnd = Fi->second.EndBuf;
1748 this->ParseFunctionBody(Func);
1749 ++Fi;
1750 }
1751}
Chris Lattner89e02532004-01-18 21:08:15 +00001752
Reid Spencer04cde2c2004-07-04 11:33:49 +00001753/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001754void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001755 // Read the number of types
1756 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001757
1758 // Ignore the type plane identifier for types if the bc file is pre 1.3
1759 if (hasTypeDerivedFromValue)
1760 read_vbr_uint();
1761
Reid Spencer46b002c2004-07-11 17:28:43 +00001762 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001763}
1764
Reid Spencer04cde2c2004-07-04 11:33:49 +00001765/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001766void BytecodeReader::ParseModuleGlobalInfo() {
1767
Reid Spencer04cde2c2004-07-04 11:33:49 +00001768 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001769
Chris Lattner70cc3392001-09-10 07:58:01 +00001770 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001771 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001772 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001773 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1774 // Linkage, bit4+ = slot#
1775 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001776 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001777 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001778 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001779 bool isConstant = VarType & 1;
1780 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001781 GlobalValue::LinkageTypes Linkage;
1782
Chris Lattnerc08912f2004-01-14 16:44:44 +00001783 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001784 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1785 case 1: Linkage = GlobalValue::WeakLinkage; break;
1786 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1787 case 3: Linkage = GlobalValue::InternalLinkage; break;
1788 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001789 default:
Reid Spencer24399722004-07-09 22:21:33 +00001790 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001791 Linkage = GlobalValue::InternalLinkage;
1792 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001793 }
1794
1795 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001796 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001797 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001798 }
1799
Reid Spencer46b002c2004-07-11 17:28:43 +00001800 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001801 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001802 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001803
Chris Lattner52e20b02003-03-19 20:54:26 +00001804 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001805
Chris Lattner70cc3392001-09-10 07:58:01 +00001806 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001807 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001808 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001809 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001810
Reid Spencer060d25d2004-06-29 23:29:38 +00001811 unsigned initSlot = 0;
1812 if (hasInitializer) {
1813 initSlot = read_vbr_uint();
1814 GlobalInits.push_back(std::make_pair(GV, initSlot));
1815 }
1816
1817 // Notify handler about the global value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001818 if (Handler) Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001819
1820 // Get next item
1821 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001822 }
1823
Chris Lattner52e20b02003-03-19 20:54:26 +00001824 // Read the function objects for all of the functions that are coming
Reid Spencer04cde2c2004-07-04 11:33:49 +00001825 unsigned FnSignature = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001826 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001827 error("Invalid function type (type type) found");
1828
Chris Lattner74734132002-08-17 22:01:27 +00001829 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1830 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +00001831 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001832 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001833 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001834 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001835 // FIXME: what should Ty be if handler continues?
1836 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001837
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001838 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001839 const FunctionType* FTy =
1840 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001841
Reid Spencer060d25d2004-06-29 23:29:38 +00001842 // Insert the place hodler
1843 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001844 "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001845 insertValue(Func, FnSignature, ModuleValues);
Chris Lattner00950542001-06-06 20:29:01 +00001846
Reid Spencer060d25d2004-06-29 23:29:38 +00001847 // Save this for later so we know type of lazily instantiated functions
Chris Lattner29b789b2003-11-19 17:27:18 +00001848 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001849
Reid Spencer04cde2c2004-07-04 11:33:49 +00001850 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001851
1852 // Get Next function signature
Reid Spencer46b002c2004-07-11 17:28:43 +00001853 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001854 error("Invalid function type (type type) found");
Chris Lattner00950542001-06-06 20:29:01 +00001855 }
1856
Chris Lattner74734132002-08-17 22:01:27 +00001857 // Now that the function signature list is set up, reverse it so that we can
1858 // remove elements efficiently from the back of the vector.
1859 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001860
Reid Spencerad89bd62004-07-25 18:07:36 +00001861 // If this bytecode format has dependent library information in it ..
1862 if (!hasNoDependentLibraries) {
1863 // Read in the number of dependent library items that follow
1864 unsigned num_dep_libs = read_vbr_uint();
1865 std::string dep_lib;
1866 while( num_dep_libs-- ) {
1867 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001868 TheModule->addLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001869 }
1870
1871 // Read target triple and place into the module
1872 std::string triple = read_str();
1873 TheModule->setTargetTriple(triple);
1874 }
1875
1876 if (hasInconsistentModuleGlobalInfo)
1877 align32();
1878
Chris Lattner00950542001-06-06 20:29:01 +00001879 // This is for future proofing... in the future extra fields may be added that
1880 // we don't understand, so we transparently ignore them.
1881 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001882 At = BlockEnd;
1883
Reid Spencer04cde2c2004-07-04 11:33:49 +00001884 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001885}
1886
Reid Spencer04cde2c2004-07-04 11:33:49 +00001887/// Parse the version information and decode it by setting flags on the
1888/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001889void BytecodeReader::ParseVersionInfo() {
1890 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001891
1892 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001893 Module::Endianness Endianness;
1894 Module::PointerSize PointerSize;
1895 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1896 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1897
1898 bool hasNoEndianness = Version & 4;
1899 bool hasNoPointerSize = Version & 8;
1900
1901 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001902
1903 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001904 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001905 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001906 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001907 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001908 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001909 has32BitTypes = false;
1910 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00001911 hasAlignment = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001912
1913 switch (RevisionNum) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001914 case 0: // LLVM 1.0, 1.1 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001915 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001916 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001917 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001918
Reid Spencerad89bd62004-07-25 18:07:36 +00001919
Chris Lattner80b97342004-01-17 23:25:43 +00001920 // FALL THROUGH
Chris Lattnerc08912f2004-01-14 16:44:44 +00001921 case 1: // LLVM 1.2 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001922 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001923
1924 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1925 // included the size for the alignment at the end, where the rest of the
1926 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001927
1928 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1929 // structures and longs for sequential types.
1930 hasRestrictedGEPTypes = true;
1931
Reid Spencer04cde2c2004-07-04 11:33:49 +00001932 // LLVM 1.2 and before had the Type class derive from Value class. This
1933 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1934 // written differently because Types can no longer be part of the
1935 // type planes for Values.
1936 hasTypeDerivedFromValue = true;
1937
Chris Lattner5fa428f2004-04-05 01:27:26 +00001938 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001939
1940 case 2: /// 1.2.5 (mid-release) version
1941
1942 /// LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1943 /// especially for small files where the 8 bytes per block is a large fraction
1944 /// of the total block size. In LLVM 1.3, the block type and length are
1945 /// compressed into a single 32-bit unsigned integer. 27 bits for length, 5
1946 /// bits for block type.
1947 hasLongBlockHeaders = true;
1948
Reid Spencerad89bd62004-07-25 18:07:36 +00001949 /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
1950 /// this has been reduced to vbr_uint24. It shouldn't make much difference
1951 /// since we haven't run into a module with > 24 million types, but for safety
1952 /// the 24-bit restriction has been enforced in 1.3 to free some bits in
1953 /// various places and to ensure consistency.
1954 has32BitTypes = true;
1955
1956 /// LLVM 1.2 and earlier did not provide a target triple nor a list of
1957 /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
1958 /// features, for use in future versions of LLVM.
1959 hasNoDependentLibraries = true;
1960
1961 // FALL THROUGH
1962 case 3: // LLVM 1.3 release version
Reid Spencer38d54be2004-08-17 07:45:14 +00001963 /// LLVM 1.3 and earlier caused alignment bytes to be written on some block
1964 /// boundaries and at the end of some strings. In extreme cases (e.g. lots
1965 /// of GEP references to a constant array), this can increase the file size
1966 /// by 30% or more. In version 1.4 alignment is done away with completely.
1967 hasAlignment = true;
1968
1969 // FALL THROUGH
1970 case 4:
Chris Lattnerc08912f2004-01-14 16:44:44 +00001971 break;
1972
Chris Lattner036b8aa2003-03-06 17:55:45 +00001973 default:
Reid Spencer24399722004-07-09 22:21:33 +00001974 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00001975 }
1976
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001977 if (hasNoEndianness) Endianness = Module::AnyEndianness;
1978 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00001979
Brian Gaekefe2102b2004-07-14 20:33:13 +00001980 TheModule->setEndianness(Endianness);
1981 TheModule->setPointerSize(PointerSize);
1982
Reid Spencer46b002c2004-07-11 17:28:43 +00001983 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001984}
1985
Reid Spencer04cde2c2004-07-04 11:33:49 +00001986/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001987void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001988 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001989
Reid Spencer060d25d2004-06-29 23:29:38 +00001990 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001991
1992 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001993 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00001994 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001995
Reid Spencer060d25d2004-06-29 23:29:38 +00001996 bool SeenModuleGlobalInfo = false;
1997 bool SeenGlobalTypePlane = false;
1998 BufPtr MyEnd = BlockEnd;
1999 while (At < MyEnd) {
2000 BufPtr OldAt = At;
2001 read_block(Type, Size);
2002
Chris Lattner00950542001-06-06 20:29:01 +00002003 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002004
Reid Spencerad89bd62004-07-25 18:07:36 +00002005 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002006 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002007 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002008
2009 ParseGlobalTypes();
2010 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002011 break;
2012
Reid Spencerad89bd62004-07-25 18:07:36 +00002013 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002014 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002015 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002016 ParseModuleGlobalInfo();
2017 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002018 break;
2019
Reid Spencerad89bd62004-07-25 18:07:36 +00002020 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002021 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002022 break;
2023
Reid Spencerad89bd62004-07-25 18:07:36 +00002024 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002025 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002026 break;
Chris Lattner00950542001-06-06 20:29:01 +00002027
Reid Spencerad89bd62004-07-25 18:07:36 +00002028 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002029 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002030 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002031
Chris Lattner00950542001-06-06 20:29:01 +00002032 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002033 At += Size;
2034 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002035 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002036 }
Chris Lattner00950542001-06-06 20:29:01 +00002037 break;
2038 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002039 BlockEnd = MyEnd;
2040 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002041 }
2042
Chris Lattner52e20b02003-03-19 20:54:26 +00002043 // After the module constant pool has been read, we can safely initialize
2044 // global variables...
2045 while (!GlobalInits.empty()) {
2046 GlobalVariable *GV = GlobalInits.back().first;
2047 unsigned Slot = GlobalInits.back().second;
2048 GlobalInits.pop_back();
2049
2050 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002051 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002052
2053 const llvm::PointerType* GVType = GV->getType();
2054 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002055 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002056 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002057 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002058 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002059 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002060 } else
Reid Spencer24399722004-07-09 22:21:33 +00002061 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002062 }
2063
Reid Spencer060d25d2004-06-29 23:29:38 +00002064 /// Make sure we pulled them all out. If we didn't then there's a declaration
2065 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002066 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002067 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002068}
2069
Reid Spencer04cde2c2004-07-04 11:33:49 +00002070/// This function completely parses a bytecode buffer given by the \p Buf
2071/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002072void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2073 const std::string &ModuleID,
2074 bool processFunctions) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002075
Reid Spencer060d25d2004-06-29 23:29:38 +00002076 try {
2077 At = MemStart = BlockStart = Buf;
2078 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002079
Reid Spencer060d25d2004-06-29 23:29:38 +00002080 // Create the module
2081 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002082
Reid Spencer04cde2c2004-07-04 11:33:49 +00002083 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002084
2085 // Read and check signature...
2086 unsigned Sig = read_uint();
2087 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
Reid Spencer24399722004-07-09 22:21:33 +00002088 error("Invalid bytecode signature: " + utostr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002089 }
2090
Reid Spencer060d25d2004-06-29 23:29:38 +00002091 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002092 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002093
Reid Spencerad89bd62004-07-25 18:07:36 +00002094 // Get the module block and size and verify. This is handled specially
2095 // because the module block/size is always written in long format. Other
2096 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002097 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002098 Type = read_uint();
2099 Size = read_uint();
2100 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002101 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002102 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002103 }
Reid Spencer46b002c2004-07-11 17:28:43 +00002104 if (At + Size != MemEnd) {
Reid Spencer24399722004-07-09 22:21:33 +00002105 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002106 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002107 }
2108
2109 // Parse the module contents
2110 this->ParseModule();
2111
Reid Spencer060d25d2004-06-29 23:29:38 +00002112 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002113 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002114 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002115
Reid Spencer5c15fe52004-07-05 00:57:50 +00002116 // Process all the function bodies now, if requested
Reid Spencer46b002c2004-07-11 17:28:43 +00002117 if (processFunctions)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002118 ParseAllFunctionBodies();
2119
2120 // Tell the handler we're done with the module
2121 if (Handler)
2122 Handler->handleModuleEnd(ModuleID);
2123
2124 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002125 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002126
Reid Spencer46b002c2004-07-11 17:28:43 +00002127 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002128 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002129 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002130 delete TheModule;
2131 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002132 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002133 } catch (...) {
2134 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002135 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002136 freeState();
2137 delete TheModule;
2138 TheModule = 0;
2139 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002140 }
Chris Lattner00950542001-06-06 20:29:01 +00002141}
Reid Spencer060d25d2004-06-29 23:29:38 +00002142
2143//===----------------------------------------------------------------------===//
2144//=== Default Implementations of Handler Methods
2145//===----------------------------------------------------------------------===//
2146
2147BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002148
2149// vim: sw=2