blob: 4d1ee41242b5a4706827af734c71356b3ad3c665 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
12// Note that this library should be as fast as possible, reentrant, and
13// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000023#include "llvm/Instructions.h"
24#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000026#include "llvm/Support/GetElementPtrTypeIterator.h"
Misha Brukman12c29d12003-09-22 23:38:23 +000027#include "Support/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000028#include <sstream>
29
Chris Lattner29b789b2003-11-19 17:27:18 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Reid Spencer46b002c2004-07-11 17:28:43 +000032namespace {
33
Reid Spencer060d25d2004-06-29 23:29:38 +000034/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000035/// as a placeholder for the actual definition for forward constants defs.
36class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer060d25d2004-06-29 23:29:38 +000037 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +000038 ConstantPlaceHolder(); // DO NOT IMPLEMENT
39 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000040public:
Reid Spencer46b002c2004-07-11 17:28:43 +000041 ConstantPlaceHolder(const Type *Ty, unsigned id)
42 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
43 ID(id) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000044 unsigned getID() { return ID; }
45};
Chris Lattner9e460f22003-10-04 20:00:03 +000046
Reid Spencer46b002c2004-07-11 17:28:43 +000047}
Reid Spencer060d25d2004-06-29 23:29:38 +000048
Reid Spencer24399722004-07-09 22:21:33 +000049// Provide some details on error
50inline void BytecodeReader::error(std::string err) {
51 err += " (Vers=" ;
52 err += itostr(RevisionNum) ;
53 err += ", Pos=" ;
54 err += itostr(At-MemStart);
55 err += ")";
56 throw err;
57}
58
Reid Spencer060d25d2004-06-29 23:29:38 +000059//===----------------------------------------------------------------------===//
60// Bytecode Reading Methods
61//===----------------------------------------------------------------------===//
62
Reid Spencer04cde2c2004-07-04 11:33:49 +000063/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000064inline bool BytecodeReader::moreInBlock() {
65 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000066}
67
Reid Spencer04cde2c2004-07-04 11:33:49 +000068/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000069inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000070 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000071 error(std::string("Attempt to read past the end of ") + block_name + " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000072}
Chris Lattner36392bc2003-10-08 21:18:57 +000073
Reid Spencer04cde2c2004-07-04 11:33:49 +000074/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000075inline void BytecodeReader::align32() {
76 BufPtr Save = At;
77 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
Reid Spencer46b002c2004-07-11 17:28:43 +000078 if (At > Save)
79 if (Handler) Handler->handleAlignment(At - Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000080 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000081 error("Ran out of data while aligning!");
Reid Spencer060d25d2004-06-29 23:29:38 +000082}
83
Reid Spencer04cde2c2004-07-04 11:33:49 +000084/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000085inline unsigned BytecodeReader::read_uint() {
86 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000087 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000088 At += 4;
89 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
90}
91
Reid Spencer04cde2c2004-07-04 11:33:49 +000092/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000093inline unsigned BytecodeReader::read_vbr_uint() {
94 unsigned Shift = 0;
95 unsigned Result = 0;
96 BufPtr Save = At;
97
98 do {
99 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000100 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000101 Result |= (unsigned)((*At++) & 0x7F) << Shift;
102 Shift += 7;
103 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000104 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000105 return Result;
106}
107
Reid Spencer04cde2c2004-07-04 11:33:49 +0000108/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000109inline uint64_t BytecodeReader::read_vbr_uint64() {
110 unsigned Shift = 0;
111 uint64_t Result = 0;
112 BufPtr Save = At;
113
114 do {
115 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000116 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000117 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
118 Shift += 7;
119 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000120 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000121 return Result;
122}
123
Reid Spencer04cde2c2004-07-04 11:33:49 +0000124/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000125inline int64_t BytecodeReader::read_vbr_int64() {
126 uint64_t R = read_vbr_uint64();
127 if (R & 1) {
128 if (R != 1)
129 return -(int64_t)(R >> 1);
130 else // There is no such thing as -0 with integers. "-0" really means
131 // 0x8000000000000000.
132 return 1LL << 63;
133 } else
134 return (int64_t)(R >> 1);
135}
136
Reid Spencer04cde2c2004-07-04 11:33:49 +0000137/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000138inline std::string BytecodeReader::read_str() {
139 unsigned Size = read_vbr_uint();
140 const unsigned char *OldAt = At;
141 At += Size;
142 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000143 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000144 return std::string((char*)OldAt, Size);
145}
146
Reid Spencer04cde2c2004-07-04 11:33:49 +0000147/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000148inline void BytecodeReader::read_data(void *Ptr, void *End) {
149 unsigned char *Start = (unsigned char *)Ptr;
150 unsigned Amount = (unsigned char *)End - Start;
151 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000152 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000153 std::copy(At, At+Amount, Start);
154 At += Amount;
155}
156
Reid Spencer46b002c2004-07-11 17:28:43 +0000157/// Read a float value in little-endian order
158inline void BytecodeReader::read_float(float& FloatVal) {
159 /// FIXME: This is a broken implementation! It reads
160 /// it in a platform-specific endianess. Need to make
161 /// it little endian always.
162 read_data(&FloatVal, &FloatVal+1);
163}
164
165/// Read a double value in little-endian order
166inline void BytecodeReader::read_double(double& DoubleVal) {
167 /// FIXME: This is a broken implementation! It reads
168 /// it in a platform-specific endianess. Need to make
169 /// it little endian always.
170 read_data(&DoubleVal, &DoubleVal+1);
171}
172
Reid Spencer04cde2c2004-07-04 11:33:49 +0000173/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000174inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
175 Type = read_uint();
176 Size = read_uint();
177 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000178 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000179 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000180 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000181 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000182}
183
184
185/// In LLVM 1.2 and before, Types were derived from Value and so they were
186/// written as part of the type planes along with any other Value. In LLVM
187/// 1.3 this changed so that Type does not derive from Value. Consequently,
188/// the BytecodeReader's containers for Values can't contain Types because
189/// there's no inheritance relationship. This means that the "Type Type"
190/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
191/// whenever a bytecode construct must have both types and values together,
192/// the types are always read/written first and then the Values. Furthermore
193/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
194/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
195/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
196/// For LLVM 1.2 and before, this function will decrement the type id by
197/// one to account for the missing Type::TypeTyID enumerator if the value is
198/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
199/// function returns true, otherwise false. This helps detect situations
200/// where the pre 1.3 bytecode is indicating that what follows is a type.
201/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000202inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
203 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
204 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000205 TypeId = Type::VoidTyID; // sanitize it
206 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000207 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000208 --TypeId; // shift all planes down because type type plane is missing
209 }
210 return false;
211}
212
213/// Reads a vbr uint to read in a type id and does the necessary
214/// conversion on it by calling sanitizeTypeId.
215/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
216/// @see sanitizeTypeId
217inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
218 TypeId = read_vbr_uint();
219 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000220}
221
222//===----------------------------------------------------------------------===//
223// IR Lookup Methods
224//===----------------------------------------------------------------------===//
225
Reid Spencer04cde2c2004-07-04 11:33:49 +0000226/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000227inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000228 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000229 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000230 return TyID >= Type::FirstDerivedTyID;
231}
232
Reid Spencer04cde2c2004-07-04 11:33:49 +0000233/// Obtain a type given a typeid and account for things like compaction tables,
234/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000235const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000236 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000237 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000238 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000239
240 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000241 ID -= Type::FirstDerivedTyID;
242
Reid Spencer060d25d2004-06-29 23:29:38 +0000243 if (!CompactionTypes.empty()) {
244 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000245 error("Type ID out of range for compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000246 return CompactionTypes[ID];
Chris Lattner89e02532004-01-18 21:08:15 +0000247 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000248
249 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000250 if (ID < ModuleTypes.size())
251 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000252
Reid Spencer46b002c2004-07-11 17:28:43 +0000253 // Nope, is it a function-level type?
254 ID -= ModuleTypes.size();
255 if (ID < FunctionTypes.size())
256 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000257
Reid Spencer46b002c2004-07-11 17:28:43 +0000258 error("Illegal type reference!");
259 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000260}
261
Reid Spencer04cde2c2004-07-04 11:33:49 +0000262/// Get a sanitized type id. This just makes sure that the \p ID
263/// is both sanitized and not the "type type" of pre-1.3 bytecode.
264/// @see sanitizeTypeId
265inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000266 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000267 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000268 return getType(ID);
269}
270
271/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000272/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000273/// then calls getType to return the type value.
274inline const Type* BytecodeReader::readSanitizedType() {
275 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000276 if (read_typeid(ID))
277 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000278 return getType(ID);
279}
280
281/// Get the slot number associated with a type accounting for primitive
282/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000283unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
284 if (Ty->isPrimitiveType())
285 return Ty->getTypeID();
286
287 // Scan the compaction table for the type if needed.
288 if (!CompactionTypes.empty()) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000289 std::vector<const Type*>::const_iterator I =
290 find(CompactionTypes.begin(), CompactionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000291
Reid Spencer46b002c2004-07-11 17:28:43 +0000292 if (I == CompactionTypes.end())
293 error("Couldn't find type specified in compaction table!");
294 return Type::FirstDerivedTyID + (&*I - &CompactionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000295 }
296
297 // Check the function level types first...
298 TypeListTy::iterator I = find(FunctionTypes.begin(), FunctionTypes.end(), Ty);
299
300 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000301 return Type::FirstDerivedTyID + ModuleTypes.size() +
302 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000303
304 // Check the module level types now...
305 I = find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
306 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000307 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000308 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000309}
310
Reid Spencer04cde2c2004-07-04 11:33:49 +0000311/// This is just like getType, but when a compaction table is in use, it is
312/// ignored. It also ignores function level types.
313/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000314const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
315 if (Slot < Type::FirstDerivedTyID) {
316 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000317 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000318 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000319 return Ty;
320 }
321 Slot -= Type::FirstDerivedTyID;
322 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000323 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000324 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000325}
326
Reid Spencer04cde2c2004-07-04 11:33:49 +0000327/// This is just like getTypeSlot, but when a compaction table is in use, it
328/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000329unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
330 if (Ty->isPrimitiveType())
331 return Ty->getTypeID();
332 TypeListTy::iterator I = find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000333 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000334 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000335 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000336 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
337}
338
Reid Spencer04cde2c2004-07-04 11:33:49 +0000339/// Retrieve a value of a given type and slot number, possibly creating
340/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000341Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000342 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000343 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000344
Chris Lattner89e02532004-01-18 21:08:15 +0000345 // If there is a compaction table active, it defines the low-level numbers.
346 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000347 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
348 if (Num < CompactionValues[type].size())
349 return CompactionValues[type][Num];
350 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000351 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000352 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000353 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000354
355 // If the type plane was compactified, figure out the global type ID
356 // by adding the derived type ids and the distance.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000357 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000358 const Type *Ty = CompactionTypes[type-Type::FirstDerivedTyID];
359 TypeListTy::iterator I =
Reid Spencer04cde2c2004-07-04 11:33:49 +0000360 find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000361 assert(I != ModuleTypes.end());
362 GlobalTyID = Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner52f86d62004-01-20 00:54:06 +0000363 }
Chris Lattner00950542001-06-06 20:29:01 +0000364
Reid Spencer060d25d2004-06-29 23:29:38 +0000365 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000366 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000367 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000368 --Num;
369 }
370
Chris Lattner52f86d62004-01-20 00:54:06 +0000371 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
372 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000373 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000374 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000375 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000376 }
377
Reid Spencer060d25d2004-06-29 23:29:38 +0000378 if (FunctionValues.size() > type &&
379 FunctionValues[type] &&
380 Num < FunctionValues[type]->size())
381 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000382
Chris Lattner74734132002-08-17 22:01:27 +0000383 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000384
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000385 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000386 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000387 if (I != ForwardReferences.end() && I->first == KeyValue)
388 return I->second; // We have already created this placeholder
389
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000390 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000391 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000392 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000393}
394
Reid Spencer04cde2c2004-07-04 11:33:49 +0000395/// This is just like getValue, but when a compaction table is in use, it
396/// is ignored. Also, no forward references or other fancy features are
397/// supported.
Reid Spencer060d25d2004-06-29 23:29:38 +0000398Value* BytecodeReader::getGlobalTableValue(const Type *Ty, unsigned SlotNo) {
399 // FIXME: getTypeSlot is inefficient!
400 unsigned TyID = getGlobalTableTypeSlot(Ty);
401
402 if (TyID != Type::LabelTyID) {
403 if (SlotNo == 0)
404 return Constant::getNullValue(Ty);
405 --SlotNo;
406 }
407
408 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
409 SlotNo >= ModuleValues[TyID]->size()) {
Reid Spencer24399722004-07-09 22:21:33 +0000410 error("Corrupt compaction table entry!"
411 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Reid Spencer46b002c2004-07-11 17:28:43 +0000412 + utostr(ModuleValues.size()) + ", "
Brian Gaeke0859e522004-07-13 07:37:43 +0000413 + utohexstr(intptr_t((void*)ModuleValues[TyID])) + ", "
Reid Spencer46b002c2004-07-11 17:28:43 +0000414 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000415 }
416 return ModuleValues[TyID]->getOperand(SlotNo);
417}
418
Reid Spencer04cde2c2004-07-04 11:33:49 +0000419/// Just like getValue, except that it returns a null pointer
420/// only on error. It always returns a constant (meaning that if the value is
421/// defined, but is not a constant, that is an error). If the specified
422/// constant hasn't been parsed yet, a placeholder is defined and used.
423/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000424Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
425 if (Value *V = getValue(TypeSlot, Slot, false))
426 if (Constant *C = dyn_cast<Constant>(V))
427 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000428 else
Reid Spencera86037e2004-07-18 00:12:03 +0000429 error("Value for slot " + utostr(Slot) +
430 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000431
432 const Type *Ty = getType(TypeSlot);
433 std::pair<const Type*, unsigned> Key(Ty, Slot);
434 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
435
436 if (I != ConstantFwdRefs.end() && I->first == Key) {
437 return I->second;
438 } else {
439 // Create a placeholder for the constant reference and
440 // keep track of the fact that we have a forward ref to recycle it
Reid Spencer46b002c2004-07-11 17:28:43 +0000441 Constant *C = new ConstantPlaceHolder(Ty, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000442
443 // Keep track of the fact that we have a forward ref to recycle it
444 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
445 return C;
446 }
447}
448
449//===----------------------------------------------------------------------===//
450// IR Construction Methods
451//===----------------------------------------------------------------------===//
452
Reid Spencer04cde2c2004-07-04 11:33:49 +0000453/// As values are created, they are inserted into the appropriate place
454/// with this method. The ValueTable argument must be one of ModuleValues
455/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000456unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
457 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000458 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000459 !hasImplicitNull(type) &&
460 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000461
462 if (ValueTab.size() <= type)
463 ValueTab.resize(type+1);
464
465 if (!ValueTab[type]) ValueTab[type] = new ValueList();
466
467 ValueTab[type]->push_back(Val);
468
469 bool HasOffset = hasImplicitNull(type);
470 return ValueTab[type]->size()-1 + HasOffset;
471}
472
Reid Spencer04cde2c2004-07-04 11:33:49 +0000473/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000474void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000475 const FunctionType *FT = F->getFunctionType();
476 Function::aiterator AI = F->abegin();
477 for (FunctionType::param_iterator It = FT->param_begin();
478 It != FT->param_end(); ++It, ++AI)
479 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
480}
481
482//===----------------------------------------------------------------------===//
483// Bytecode Parsing Methods
484//===----------------------------------------------------------------------===//
485
Reid Spencer04cde2c2004-07-04 11:33:49 +0000486/// This method parses a single instruction. The instruction is
487/// inserted at the end of the \p BB provided. The arguments of
488/// the instruction are provided in the \p Args vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000489void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000490 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000491 BufPtr SaveAt = At;
492
493 // Clear instruction data
494 Oprnds.clear();
495 unsigned iType = 0;
496 unsigned Opcode = 0;
497 unsigned Op = read_uint();
498
499 // bits Instruction format: Common to all formats
500 // --------------------------
501 // 01-00: Opcode type, fixed to 1.
502 // 07-02: Opcode
503 Opcode = (Op >> 2) & 63;
504 Oprnds.resize((Op >> 0) & 03);
505
506 // Extract the operands
507 switch (Oprnds.size()) {
508 case 1:
509 // bits Instruction format:
510 // --------------------------
511 // 19-08: Resulting type plane
512 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
513 //
514 iType = (Op >> 8) & 4095;
515 Oprnds[0] = (Op >> 20) & 4095;
516 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
517 Oprnds.resize(0);
518 break;
519 case 2:
520 // bits Instruction format:
521 // --------------------------
522 // 15-08: Resulting type plane
523 // 23-16: Operand #1
524 // 31-24: Operand #2
525 //
526 iType = (Op >> 8) & 255;
527 Oprnds[0] = (Op >> 16) & 255;
528 Oprnds[1] = (Op >> 24) & 255;
529 break;
530 case 3:
531 // bits Instruction format:
532 // --------------------------
533 // 13-08: Resulting type plane
534 // 19-14: Operand #1
535 // 25-20: Operand #2
536 // 31-26: Operand #3
537 //
538 iType = (Op >> 8) & 63;
539 Oprnds[0] = (Op >> 14) & 63;
540 Oprnds[1] = (Op >> 20) & 63;
541 Oprnds[2] = (Op >> 26) & 63;
542 break;
543 case 0:
544 At -= 4; // Hrm, try this again...
545 Opcode = read_vbr_uint();
546 Opcode >>= 2;
547 iType = read_vbr_uint();
548
549 unsigned NumOprnds = read_vbr_uint();
550 Oprnds.resize(NumOprnds);
551
552 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000553 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000554
555 for (unsigned i = 0; i != NumOprnds; ++i)
556 Oprnds[i] = read_vbr_uint();
557 align32();
558 break;
559 }
560
Reid Spencer04cde2c2004-07-04 11:33:49 +0000561 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000562
Reid Spencer46b002c2004-07-11 17:28:43 +0000563 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000564 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000565
566 // Declare the resulting instruction we'll build.
567 Instruction *Result = 0;
568
569 // Handle binary operators
570 if (Opcode >= Instruction::BinaryOpsBegin &&
571 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
572 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
573 getValue(iType, Oprnds[0]),
574 getValue(iType, Oprnds[1]));
575
576 switch (Opcode) {
577 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000578 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000579 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000580 break;
581 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000582 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000583 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000584 break;
585 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000586 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000587 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000588 break;
589 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000590 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000591 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000592 break;
593 case Instruction::Select:
594 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
595 getValue(iType, Oprnds[1]),
596 getValue(iType, Oprnds[2]));
597 break;
598 case Instruction::PHI: {
599 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000600 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000601
602 PHINode *PN = new PHINode(InstTy);
603 PN->op_reserve(Oprnds.size());
604 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
605 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
606 Result = PN;
607 break;
608 }
609
610 case Instruction::Shl:
611 case Instruction::Shr:
612 Result = new ShiftInst((Instruction::OtherOps)Opcode,
613 getValue(iType, Oprnds[0]),
614 getValue(Type::UByteTyID, Oprnds[1]));
615 break;
616 case Instruction::Ret:
617 if (Oprnds.size() == 0)
618 Result = new ReturnInst();
619 else if (Oprnds.size() == 1)
620 Result = new ReturnInst(getValue(iType, Oprnds[0]));
621 else
Reid Spencer24399722004-07-09 22:21:33 +0000622 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000623 break;
624
625 case Instruction::Br:
626 if (Oprnds.size() == 1)
627 Result = new BranchInst(getBasicBlock(Oprnds[0]));
628 else if (Oprnds.size() == 3)
629 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000630 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000631 else
Reid Spencer24399722004-07-09 22:21:33 +0000632 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000633 break;
634 case Instruction::Switch: {
635 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000636 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000637
638 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
639 getBasicBlock(Oprnds[1]));
640 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
641 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
642 getBasicBlock(Oprnds[i+1]));
643 Result = I;
644 break;
645 }
646
647 case Instruction::Call: {
648 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000649 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000650
651 Value *F = getValue(iType, Oprnds[0]);
652
653 // Check to make sure we have a pointer to function type
654 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000655 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000656 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000657 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000658
659 std::vector<Value *> Params;
660 if (!FTy->isVarArg()) {
661 FunctionType::param_iterator It = FTy->param_begin();
662
663 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
664 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000665 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000666 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
667 }
668 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000669 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000670 } else {
671 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
672
673 unsigned FirstVariableOperand;
674 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000675 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000676
677 // Read all of the fixed arguments
678 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
679 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
680
681 FirstVariableOperand = FTy->getNumParams();
682
683 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
Reid Spencer24399722004-07-09 22:21:33 +0000684 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000685
686 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000687 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000688 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
689 }
690
691 Result = new CallInst(F, Params);
692 break;
693 }
694 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000695 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000696 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000697 Value *F = getValue(iType, Oprnds[0]);
698
699 // Check to make sure we have a pointer to function type
700 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000701 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000702 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000703 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000704 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000705 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000706
707 std::vector<Value *> Params;
708 BasicBlock *Normal, *Except;
709
710 if (!FTy->isVarArg()) {
711 Normal = getBasicBlock(Oprnds[1]);
712 Except = getBasicBlock(Oprnds[2]);
713
714 FunctionType::param_iterator It = FTy->param_begin();
715 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
716 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000717 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000718 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
719 }
720 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000721 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000722 } else {
723 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
724
725 Normal = getBasicBlock(Oprnds[0]);
726 Except = getBasicBlock(Oprnds[1]);
727
728 unsigned FirstVariableArgument = FTy->getNumParams()+2;
729 for (unsigned i = 2; i != FirstVariableArgument; ++i)
730 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
731 Oprnds[i]));
732
733 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000734 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000735
736 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
737 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
738 }
739
740 Result = new InvokeInst(F, Normal, Except, Params);
741 break;
742 }
743 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000744 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000745 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000746 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000747 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000748
749 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
750 Oprnds.size() ? getValue(Type::UIntTyID,
751 Oprnds[0]) : 0);
752 break;
753
754 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000755 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000756 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000757 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000758 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000759
760 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
761 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000762 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000763 break;
764 case Instruction::Free:
765 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000766 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000767 Result = new FreeInst(getValue(iType, Oprnds[0]));
768 break;
769 case Instruction::GetElementPtr: {
770 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000771 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000772
773 std::vector<Value*> Idx;
774
775 const Type *NextTy = InstTy;
776 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
777 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000778 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000779 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000780
781 unsigned ValIdx = Oprnds[i];
782 unsigned IdxTy = 0;
783 if (!hasRestrictedGEPTypes) {
784 // Struct indices are always uints, sequential type indices can be any
785 // of the 32 or 64-bit integer types. The actual choice of type is
786 // encoded in the low two bits of the slot number.
787 if (isa<StructType>(TopTy))
788 IdxTy = Type::UIntTyID;
789 else {
790 switch (ValIdx & 3) {
791 default:
792 case 0: IdxTy = Type::UIntTyID; break;
793 case 1: IdxTy = Type::IntTyID; break;
794 case 2: IdxTy = Type::ULongTyID; break;
795 case 3: IdxTy = Type::LongTyID; break;
796 }
797 ValIdx >>= 2;
798 }
799 } else {
800 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
801 }
802
803 Idx.push_back(getValue(IdxTy, ValIdx));
804
805 // Convert ubyte struct indices into uint struct indices.
806 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
807 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
808 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
809
810 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
811 }
812
813 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
814 break;
815 }
816
817 case 62: // volatile load
818 case Instruction::Load:
819 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000820 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000821 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
822 break;
823
824 case 63: // volatile store
825 case Instruction::Store: {
826 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000827 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000828
829 Value *Ptr = getValue(iType, Oprnds[1]);
830 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
831 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
832 Opcode == 63);
833 break;
834 }
835 case Instruction::Unwind:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000836 if (Oprnds.size() != 0)
Reid Spencer24399722004-07-09 22:21:33 +0000837 error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000838 Result = new UnwindInst();
839 break;
840 } // end switch(Opcode)
841
842 unsigned TypeSlot;
843 if (Result->getType() == InstTy)
844 TypeSlot = iType;
845 else
846 TypeSlot = getTypeSlot(Result->getType());
847
848 insertValue(Result, TypeSlot, FunctionValues);
849 BB->getInstList().push_back(Result);
850}
851
Reid Spencer04cde2c2004-07-04 11:33:49 +0000852/// Get a particular numbered basic block, which might be a forward reference.
853/// This works together with ParseBasicBlock to handle these forward references
854/// in a clean manner. This function is used when constructing phi, br, switch,
855/// and other instructions that reference basic blocks. Blocks are numbered
856/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000857BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000858 // Make sure there is room in the table...
859 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
860
861 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
862 // has already created this block, or if the forward reference has already
863 // been created.
864 if (ParsedBasicBlocks[ID])
865 return ParsedBasicBlocks[ID];
866
867 // Otherwise, the basic block has not yet been created. Do so and add it to
868 // the ParsedBasicBlocks list.
869 return ParsedBasicBlocks[ID] = new BasicBlock();
870}
871
Reid Spencer04cde2c2004-07-04 11:33:49 +0000872/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
873/// This method reads in one of the basicblock packets. This method is not used
874/// for bytecode files after LLVM 1.0
875/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000876BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
877 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000878
879 BasicBlock *BB = 0;
880
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000881 if (ParsedBasicBlocks.size() == BlockNo)
882 ParsedBasicBlocks.push_back(BB = new BasicBlock());
883 else if (ParsedBasicBlocks[BlockNo] == 0)
884 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
885 else
886 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000887
Reid Spencer060d25d2004-06-29 23:29:38 +0000888 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000889 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000890 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000891
Reid Spencer46b002c2004-07-11 17:28:43 +0000892 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000893 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000894}
895
Reid Spencer04cde2c2004-07-04 11:33:49 +0000896/// Parse all of the BasicBlock's & Instruction's in the body of a function.
897/// In post 1.0 bytecode files, we no longer emit basic block individually,
898/// in order to avoid per-basic-block overhead.
899/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000900unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000901 unsigned BlockNo = 0;
902 std::vector<unsigned> Args;
903
Reid Spencer46b002c2004-07-11 17:28:43 +0000904 while (moreInBlock()) {
905 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000906 BasicBlock *BB;
907 if (ParsedBasicBlocks.size() == BlockNo)
908 ParsedBasicBlocks.push_back(BB = new BasicBlock());
909 else if (ParsedBasicBlocks[BlockNo] == 0)
910 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
911 else
912 BB = ParsedBasicBlocks[BlockNo];
913 ++BlockNo;
914 F->getBasicBlockList().push_back(BB);
915
916 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000917 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000918 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000919
920 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000921 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000922
Reid Spencer46b002c2004-07-11 17:28:43 +0000923 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000924 }
925
926 return BlockNo;
927}
928
Reid Spencer04cde2c2004-07-04 11:33:49 +0000929/// Parse a symbol table. This works for both module level and function
930/// level symbol tables. For function level symbol tables, the CurrentFunction
931/// parameter must be non-zero and the ST parameter must correspond to
932/// CurrentFunction's symbol table. For Module level symbol tables, the
933/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +0000934void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000935 SymbolTable *ST) {
936 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000937
Chris Lattner39cacce2003-10-10 05:43:47 +0000938 // Allow efficient basic block lookup by number.
939 std::vector<BasicBlock*> BBMap;
940 if (CurrentFunction)
941 for (Function::iterator I = CurrentFunction->begin(),
942 E = CurrentFunction->end(); I != E; ++I)
943 BBMap.push_back(I);
944
Reid Spencer04cde2c2004-07-04 11:33:49 +0000945 /// In LLVM 1.3 we write types separately from values so
946 /// The types are always first in the symbol table. This is
947 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +0000948 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000949 // Symtab block header: [num entries]
950 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +0000951 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000952 // Symtab entry: [def slot #][name]
953 unsigned slot = read_vbr_uint();
954 std::string Name = read_str();
955 const Type* T = getType(slot);
956 ST->insert(Name, T);
957 }
958 }
959
Reid Spencer46b002c2004-07-11 17:28:43 +0000960 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000961 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000962 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000963 unsigned Typ = 0;
964 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +0000965 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +0000966
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000967 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000968 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000969 unsigned slot = read_vbr_uint();
970 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +0000971
Reid Spencer04cde2c2004-07-04 11:33:49 +0000972 // if we're reading a pre 1.3 bytecode file and the type plane
973 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +0000974 if (isTypeType) {
975 const Type* T = getType(slot);
976 if (T == 0)
977 error("Failed type look-up for name '" + Name + "'");
978 ST->insert(Name, T);
979 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +0000980 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +0000981 Value *V = 0;
982 if (Typ == Type::LabelTyID) {
983 if (slot < BBMap.size())
984 V = BBMap[slot];
985 } else {
986 V = getValue(Typ, slot, false); // Find mapping...
987 }
988 if (V == 0)
989 error("Failed value look-up for name '" + Name + "'");
990 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +0000991 }
Chris Lattner00950542001-06-06 20:29:01 +0000992 }
993 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000994 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000995 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000996}
997
Reid Spencer04cde2c2004-07-04 11:33:49 +0000998/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +0000999void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001000 for (unsigned i = 0; i != NumEntries; ++i) {
1001 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001002 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001003 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001004 const Type *Typ = getGlobalTableType(TypeSlot);
1005 CompactionTypes.push_back(Typ);
Reid Spencer46b002c2004-07-11 17:28:43 +00001006 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001007 }
1008}
1009
1010/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001011void BytecodeReader::ParseCompactionTable() {
1012
Reid Spencer46b002c2004-07-11 17:28:43 +00001013 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001014 if (Handler) Handler->handleCompactionTableBegin();
1015
Reid Spencer46b002c2004-07-11 17:28:43 +00001016 // In LLVM 1.3 Type no longer derives from Value. So,
1017 // we always write them first in the compaction table
1018 // because they can't occupy a "type plane" where the
1019 // Values reside.
1020 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001021 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001022 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001023 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001024
Reid Spencer46b002c2004-07-11 17:28:43 +00001025 // Compaction tables live in separate blocks so we have to loop
1026 // until we've read the whole thing.
1027 while (moreInBlock()) {
1028 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001029 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001030 unsigned Ty = 0;
1031 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001032
Reid Spencer46b002c2004-07-11 17:28:43 +00001033 // Decode the type from value read in. Most compaction table
1034 // planes will have one or two entries in them. If that's the
1035 // case then the length is encoded in the bottom two bits and
1036 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001037 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001038 // In this case, both low-order bits are set (value 3). This
1039 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001040 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001041 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001042 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001043 // In this case, the low-order bits specify the number of entries
1044 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001045 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001046 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001047 NumEntries &= 3;
1048 }
1049
Reid Spencer04cde2c2004-07-04 11:33:49 +00001050 // if we're reading a pre 1.3 bytecode file and the type plane
1051 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001052 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001053 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001054 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001055 // Make sure we have enough room for the plane
Reid Spencer04cde2c2004-07-04 11:33:49 +00001056 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001058
Reid Spencer46b002c2004-07-11 17:28:43 +00001059 // Make sure the plane is empty or we have some kind of error
Reid Spencer04cde2c2004-07-04 11:33:49 +00001060 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001061 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001062
Reid Spencer46b002c2004-07-11 17:28:43 +00001063 // Notify handler about the plane
1064 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001065
Reid Spencer46b002c2004-07-11 17:28:43 +00001066 // Convert the type slot to a type
Reid Spencer060d25d2004-06-29 23:29:38 +00001067 const Type *Typ = getType(Ty);
Reid Spencer46b002c2004-07-11 17:28:43 +00001068
Reid Spencer060d25d2004-06-29 23:29:38 +00001069 // Push the implicit zero
1070 CompactionValues[Ty].push_back(Constant::getNullValue(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001071
1072 // Read in each of the entries, put them in the compaction table
1073 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001074 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001075 unsigned ValSlot = read_vbr_uint();
1076 Value *V = getGlobalTableValue(Typ, ValSlot);
1077 CompactionValues[Ty].push_back(V);
1078 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot, Typ);
Reid Spencer060d25d2004-06-29 23:29:38 +00001079 }
1080 }
1081 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001082 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001083 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001084}
1085
Reid Spencer46b002c2004-07-11 17:28:43 +00001086// Parse a single type. The typeid is read in first. If its a primitive type
1087// then nothing else needs to be read, we know how to instantiate it. If its
1088// a derived type, then additional data is read to fill out the type
1089// definition.
1090const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001091 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001092 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001093 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001094
1095 const Type *Result = 0;
1096 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1097 return Result;
1098
1099 switch (PrimType) {
1100 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001101 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001102
1103 unsigned NumParams = read_vbr_uint();
1104
1105 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001106 while (NumParams--)
1107 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001108
1109 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1110 if (isVarArg) Params.pop_back();
1111
1112 Result = FunctionType::get(RetType, Params, isVarArg);
1113 break;
1114 }
1115 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001116 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001117 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 Result = ArrayType::get(ElementType, NumElements);
1119 break;
1120 }
1121 case Type::StructTyID: {
1122 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001123 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001124 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001125 error("Invalid element type (type type) for structure!");
1126
Reid Spencer060d25d2004-06-29 23:29:38 +00001127 while (Typ) { // List is terminated by void/0 typeid
1128 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001129 if (read_typeid(Typ))
1130 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001131 }
1132
1133 Result = StructType::get(Elements);
1134 break;
1135 }
1136 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001137 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001138 break;
1139 }
1140
1141 case Type::OpaqueTyID: {
1142 Result = OpaqueType::get();
1143 break;
1144 }
1145
1146 default:
Reid Spencer24399722004-07-09 22:21:33 +00001147 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001148 break;
1149 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001150 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001151 return Result;
1152}
1153
Reid Spencer46b002c2004-07-11 17:28:43 +00001154// ParseType - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001155// types. We know that recursive types will only reference the current slab of
1156// values in the type plane, but they can forward reference types before they
1157// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1158// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1159// this ugly problem, we pessimistically insert an opaque type for each type we
1160// are about to read. This means that forward references will resolve to
1161// something and when we reread the type later, we can replace the opaque type
1162// with a new resolved concrete type.
1163//
Reid Spencer46b002c2004-07-11 17:28:43 +00001164void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001165 assert(Tab.size() == 0 && "should not have read type constants in before!");
1166
1167 // Insert a bunch of opaque types to be resolved later...
1168 Tab.reserve(NumEntries);
1169 for (unsigned i = 0; i != NumEntries; ++i)
1170 Tab.push_back(OpaqueType::get());
1171
1172 // Loop through reading all of the types. Forward types will make use of the
1173 // opaque types just inserted.
1174 //
1175 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001176 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001177 const Type* OldTy = Tab[i].get();
1178 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001179 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001180
1181 // Don't directly push the new type on the Tab. Instead we want to replace
1182 // the opaque type we previously inserted with the new concrete value. This
1183 // approach helps with forward references to types. The refinement from the
1184 // abstract (opaque) type to the new type causes all uses of the abstract
1185 // type to use the concrete type (NewTy). This will also cause the opaque
1186 // type to be deleted.
1187 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1188
1189 // This should have replaced the old opaque type with the new type in the
1190 // value table... or with a preexisting type that was already in the system.
1191 // Let's just make sure it did.
1192 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1193 }
1194}
1195
Reid Spencer04cde2c2004-07-04 11:33:49 +00001196/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001197Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001198 // We must check for a ConstantExpr before switching by type because
1199 // a ConstantExpr can be of any type, and has no explicit value.
1200 //
1201 // 0 if not expr; numArgs if is expr
1202 unsigned isExprNumArgs = read_vbr_uint();
1203
1204 if (isExprNumArgs) {
1205 // FIXME: Encoding of constant exprs could be much more compact!
1206 std::vector<Constant*> ArgVec;
1207 ArgVec.reserve(isExprNumArgs);
1208 unsigned Opcode = read_vbr_uint();
1209
1210 // Read the slot number and types of each of the arguments
1211 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1212 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001213 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001214 if (read_typeid(ArgTypeSlot))
1215 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001216
1217 // Get the arg value from its slot if it exists, otherwise a placeholder
1218 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1219 }
1220
1221 // Construct a ConstantExpr of the appropriate kind
1222 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001223 if (Opcode != Instruction::Cast)
1224 error("Only Cast instruction has one argument for ConstantExpr");
1225
Reid Spencer060d25d2004-06-29 23:29:38 +00001226 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001227 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001228 return Result;
1229 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1230 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1231
1232 if (hasRestrictedGEPTypes) {
1233 const Type *BaseTy = ArgVec[0]->getType();
1234 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1235 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1236 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1237 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1238 if (isa<StructType>(*GTI)) {
1239 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001240 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001241 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1242 }
1243 }
1244
1245 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001246 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001247 return Result;
1248 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001249 if (ArgVec.size() != 3)
1250 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001251 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001252 ArgVec[2]);
1253 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001254 return Result;
1255 } else { // All other 2-operand expressions
1256 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001257 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001258 return Result;
1259 }
1260 }
1261
1262 // Ok, not an ConstantExpr. We now know how to read the given type...
1263 const Type *Ty = getType(TypeID);
1264 switch (Ty->getTypeID()) {
1265 case Type::BoolTyID: {
1266 unsigned Val = read_vbr_uint();
1267 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001268 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001269 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001270 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001271 return Result;
1272 }
1273
1274 case Type::UByteTyID: // Unsigned integer types...
1275 case Type::UShortTyID:
1276 case Type::UIntTyID: {
1277 unsigned Val = read_vbr_uint();
1278 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001279 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001280 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001281 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001282 return Result;
1283 }
1284
1285 case Type::ULongTyID: {
1286 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001287 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001288 return Result;
1289 }
1290
1291 case Type::SByteTyID: // Signed integer types...
1292 case Type::ShortTyID:
1293 case Type::IntTyID: {
1294 case Type::LongTyID:
1295 int64_t Val = read_vbr_int64();
1296 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001297 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001298 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001299 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001300 return Result;
1301 }
1302
1303 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001304 float Val;
1305 read_float(Val);
1306 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001307 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001308 return Result;
1309 }
1310
1311 case Type::DoubleTyID: {
1312 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001313 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001314 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001315 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001316 return Result;
1317 }
1318
Reid Spencer060d25d2004-06-29 23:29:38 +00001319 case Type::ArrayTyID: {
1320 const ArrayType *AT = cast<ArrayType>(Ty);
1321 unsigned NumElements = AT->getNumElements();
1322 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1323 std::vector<Constant*> Elements;
1324 Elements.reserve(NumElements);
1325 while (NumElements--) // Read all of the elements of the constant.
1326 Elements.push_back(getConstantValue(TypeSlot,
1327 read_vbr_uint()));
1328 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001329 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001330 return Result;
1331 }
1332
1333 case Type::StructTyID: {
1334 const StructType *ST = cast<StructType>(Ty);
1335
1336 std::vector<Constant *> Elements;
1337 Elements.reserve(ST->getNumElements());
1338 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1339 Elements.push_back(getConstantValue(ST->getElementType(i),
1340 read_vbr_uint()));
1341
1342 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001343 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001344 return Result;
1345 }
1346
1347 case Type::PointerTyID: { // ConstantPointerRef value...
1348 const PointerType *PT = cast<PointerType>(Ty);
1349 unsigned Slot = read_vbr_uint();
1350
1351 // Check to see if we have already read this global variable...
1352 Value *Val = getValue(TypeID, Slot, false);
1353 GlobalValue *GV;
1354 if (Val) {
1355 if (!(GV = dyn_cast<GlobalValue>(Val)))
Reid Spencera86037e2004-07-18 00:12:03 +00001356 error("GlobalValue not in ValueTable!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001357 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001358 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001359 }
1360
Reid Spencera86037e2004-07-18 00:12:03 +00001361 if (Handler) Handler->handleConstantPointer(PT, Slot, GV );
1362 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001363 }
1364
1365 default:
Reid Spencer24399722004-07-09 22:21:33 +00001366 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001367 Ty->getDescription());
1368 break;
1369 }
Reid Spencer24399722004-07-09 22:21:33 +00001370 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001371}
1372
Reid Spencer04cde2c2004-07-04 11:33:49 +00001373/// Resolve references for constants. This function resolves the forward
1374/// referenced constants in the ConstantFwdRefs map. It uses the
1375/// replaceAllUsesWith method of Value class to substitute the placeholder
1376/// instance with the actual instance.
Reid Spencer060d25d2004-06-29 23:29:38 +00001377void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001378 ConstantRefsType::iterator I =
1379 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1380 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001381
Chris Lattner29b789b2003-11-19 17:27:18 +00001382 Value *PH = I->second; // Get the placeholder...
1383 PH->replaceAllUsesWith(NewV);
1384 delete PH; // Delete the old placeholder
1385 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001386}
1387
Reid Spencer04cde2c2004-07-04 11:33:49 +00001388/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001389void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1390 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001391 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001392 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001393 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001394 const Type *Ty = getType(Typ);
1395 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001396 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001397
1398 const ArrayType *ATy = cast<ArrayType>(Ty);
1399 if (ATy->getElementType() != Type::SByteTy &&
1400 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001401 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001402
1403 // Read character data. The type tells us how long the string is.
1404 char Data[ATy->getNumElements()];
1405 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001406
Reid Spencer060d25d2004-06-29 23:29:38 +00001407 std::vector<Constant*> Elements(ATy->getNumElements());
1408 if (ATy->getElementType() == Type::SByteTy)
1409 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1410 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1411 else
1412 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1413 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001414
Reid Spencer060d25d2004-06-29 23:29:38 +00001415 // Create the constant, inserting it as needed.
1416 Constant *C = ConstantArray::get(ATy, Elements);
1417 unsigned Slot = insertValue(C, Typ, Tab);
1418 ResolveReferencesToConstant(C, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001419 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001420 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001421}
1422
Reid Spencer04cde2c2004-07-04 11:33:49 +00001423/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001424void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001425 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001426 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001427 if (Handler) Handler->handleGlobalConstantsBegin();
1428
1429 /// In LLVM 1.3 Type does not derive from Value so the types
1430 /// do not occupy a plane. Consequently, we read the types
1431 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001432 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001433 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001434 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001435 }
1436
Reid Spencer46b002c2004-07-11 17:28:43 +00001437 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001438 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001439 unsigned Typ = 0;
1440 bool isTypeType = read_typeid(Typ);
1441
1442 /// In LLVM 1.2 and before, Types were written to the
1443 /// bytecode file in the "Type Type" plane (#12).
1444 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001445 if (isTypeType) {
1446 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001447 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001448 /// Use of Type::VoidTyID is a misnomer. It actually means
1449 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001450 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1451 ParseStringConstants(NumEntries, Tab);
1452 } else {
1453 for (unsigned i = 0; i < NumEntries; ++i) {
1454 Constant *C = ParseConstantValue(Typ);
1455 assert(C && "ParseConstantValue returned NULL!");
1456 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001457
Reid Spencer060d25d2004-06-29 23:29:38 +00001458 // If we are reading a function constant table, make sure that we adjust
1459 // the slot number to be the real global constant number.
1460 //
1461 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1462 ModuleValues[Typ])
1463 Slot += ModuleValues[Typ]->size();
1464 ResolveReferencesToConstant(C, Slot);
1465 }
1466 }
1467 }
1468 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001469 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001470}
Chris Lattner00950542001-06-06 20:29:01 +00001471
Reid Spencer04cde2c2004-07-04 11:33:49 +00001472/// Parse the contents of a function. Note that this function can be
1473/// called lazily by materializeFunction
1474/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001475void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001476
1477 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001478 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1479
Reid Spencer060d25d2004-06-29 23:29:38 +00001480 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001481 switch (LinkageType) {
1482 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1483 case 1: Linkage = GlobalValue::WeakLinkage; break;
1484 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1485 case 3: Linkage = GlobalValue::InternalLinkage; break;
1486 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001487 default:
Reid Spencer24399722004-07-09 22:21:33 +00001488 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001489 Linkage = GlobalValue::InternalLinkage;
1490 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001491 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001492
Reid Spencer46b002c2004-07-11 17:28:43 +00001493 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001494 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001495
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001496 // Keep track of how many basic blocks we have read in...
1497 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001498 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001499
Reid Spencer060d25d2004-06-29 23:29:38 +00001500 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001501 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001502 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001503 BufPtr OldAt = At;
1504 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001505
1506 switch (Type) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001507 case BytecodeFormat::ConstantPool:
Chris Lattner89e02532004-01-18 21:08:15 +00001508 if (!InsertedArguments) {
1509 // Insert arguments into the value table before we parse the first basic
1510 // block in the function, but after we potentially read in the
1511 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001512 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001513 InsertedArguments = true;
1514 }
1515
Reid Spencer04cde2c2004-07-04 11:33:49 +00001516 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001517 break;
1518
Chris Lattner89e02532004-01-18 21:08:15 +00001519 case BytecodeFormat::CompactionTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001520 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001521 break;
1522
Chris Lattner00950542001-06-06 20:29:01 +00001523 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001524 if (!InsertedArguments) {
1525 // Insert arguments into the value table before we parse the first basic
1526 // block in the function, but after we potentially read in the
1527 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001528 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001529 InsertedArguments = true;
1530 }
1531
Reid Spencer060d25d2004-06-29 23:29:38 +00001532 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001533 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001534 break;
1535 }
1536
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001537 case BytecodeFormat::InstructionList: {
Chris Lattner89e02532004-01-18 21:08:15 +00001538 // Insert arguments into the value table before we parse the instruction
1539 // list for the function, but after we potentially read in the compaction
1540 // table.
1541 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001542 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001543 InsertedArguments = true;
1544 }
1545
Reid Spencer060d25d2004-06-29 23:29:38 +00001546 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001547 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001548 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001549 break;
1550 }
1551
Chris Lattner29b789b2003-11-19 17:27:18 +00001552 case BytecodeFormat::SymbolTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001553 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001554 break;
1555
1556 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001557 At += Size;
1558 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001559 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001560 break;
1561 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001562 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001563
Misha Brukman12c29d12003-09-22 23:38:23 +00001564 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001565 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001566 }
1567
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001568 // Make sure there were no references to non-existant basic blocks.
1569 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001570 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001571
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001572 ParsedBasicBlocks.clear();
1573
Chris Lattner97330cf2003-10-09 23:10:14 +00001574 // Resolve forward references. Replace any uses of a forward reference value
1575 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001576
Chris Lattner97330cf2003-10-09 23:10:14 +00001577 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1578 // number of operands. PHI nodes often have forward references, and can also
1579 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001580 //
1581 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1582 // should be simplified back to using it!
1583 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001584 std::map<Value*, Value*> ForwardRefMapping;
1585 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1586 I = ForwardReferences.begin(), E = ForwardReferences.end();
1587 I != E; ++I)
1588 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1589 false);
1590
1591 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1592 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1593 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1594 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
1595 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1596 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1597 }
1598
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001599 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001600 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1601 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001602 Value *PlaceHolder = I->second;
1603 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001604
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001605 // Now that all the uses are gone, delete the placeholder...
1606 // If we couldn't find a def (error case), then leak a little
1607 // memory, because otherwise we can't remove all uses!
1608 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001609 }
Chris Lattner00950542001-06-06 20:29:01 +00001610
Misha Brukman12c29d12003-09-22 23:38:23 +00001611 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001612 FunctionTypes.clear();
1613 CompactionTypes.clear();
1614 CompactionValues.clear();
1615 freeTable(FunctionValues);
1616
Reid Spencer04cde2c2004-07-04 11:33:49 +00001617 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001618}
1619
Reid Spencer04cde2c2004-07-04 11:33:49 +00001620/// This function parses LLVM functions lazily. It obtains the type of the
1621/// function and records where the body of the function is in the bytecode
1622/// buffer. The caller can then use the ParseNextFunction and
1623/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001624void BytecodeReader::ParseFunctionLazily() {
1625 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001626 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001627
Reid Spencer060d25d2004-06-29 23:29:38 +00001628 Function *Func = FunctionSignatureList.back();
1629 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001630
Reid Spencer060d25d2004-06-29 23:29:38 +00001631 // Save the information for future reading of the function
1632 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001633
Reid Spencer060d25d2004-06-29 23:29:38 +00001634 // Pretend we've `parsed' this function
1635 At = BlockEnd;
1636}
Chris Lattner89e02532004-01-18 21:08:15 +00001637
Reid Spencer04cde2c2004-07-04 11:33:49 +00001638/// The ParserFunction method lazily parses one function. Use this method to
1639/// casue the parser to parse a specific function in the module. Note that
1640/// this will remove the function from what is to be included by
1641/// ParseAllFunctionBodies.
1642/// @see ParseAllFunctionBodies
1643/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001644void BytecodeReader::ParseFunction(Function* Func) {
1645 // Find {start, end} pointers and slot in the map. If not there, we're done.
1646 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001647
Reid Spencer060d25d2004-06-29 23:29:38 +00001648 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001649 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001650 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001651 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001652 }
1653
Reid Spencer060d25d2004-06-29 23:29:38 +00001654 BlockStart = At = Fi->second.Buf;
1655 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001656 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001657
1658 LazyFunctionLoadMap.erase(Fi);
1659
Reid Spencer46b002c2004-07-11 17:28:43 +00001660 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001661}
1662
Reid Spencer04cde2c2004-07-04 11:33:49 +00001663/// The ParseAllFunctionBodies method parses through all the previously
1664/// unparsed functions in the bytecode file. If you want to completely parse
1665/// a bytecode file, this method should be called after Parsebytecode because
1666/// Parsebytecode only records the locations in the bytecode file of where
1667/// the function definitions are located. This function uses that information
1668/// to materialize the functions.
1669/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001670void BytecodeReader::ParseAllFunctionBodies() {
1671 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1672 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001673
Reid Spencer46b002c2004-07-11 17:28:43 +00001674 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001675 Function* Func = Fi->first;
1676 BlockStart = At = Fi->second.Buf;
1677 BlockEnd = Fi->second.EndBuf;
1678 this->ParseFunctionBody(Func);
1679 ++Fi;
1680 }
1681}
Chris Lattner89e02532004-01-18 21:08:15 +00001682
Reid Spencer04cde2c2004-07-04 11:33:49 +00001683/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001684void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001685 // Read the number of types
1686 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001687
1688 // Ignore the type plane identifier for types if the bc file is pre 1.3
1689 if (hasTypeDerivedFromValue)
1690 read_vbr_uint();
1691
Reid Spencer46b002c2004-07-11 17:28:43 +00001692 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001693}
1694
Reid Spencer04cde2c2004-07-04 11:33:49 +00001695/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001696void BytecodeReader::ParseModuleGlobalInfo() {
1697
Reid Spencer04cde2c2004-07-04 11:33:49 +00001698 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001699
Chris Lattner70cc3392001-09-10 07:58:01 +00001700 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001701 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001702 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001703 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1704 // Linkage, bit4+ = slot#
1705 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001706 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001707 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001708 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001709 bool isConstant = VarType & 1;
1710 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001711 GlobalValue::LinkageTypes Linkage;
1712
Chris Lattnerc08912f2004-01-14 16:44:44 +00001713 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001714 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1715 case 1: Linkage = GlobalValue::WeakLinkage; break;
1716 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1717 case 3: Linkage = GlobalValue::InternalLinkage; break;
1718 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001719 default:
Reid Spencer24399722004-07-09 22:21:33 +00001720 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001721 Linkage = GlobalValue::InternalLinkage;
1722 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001723 }
1724
1725 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001726 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001727 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001728 }
1729
Reid Spencer46b002c2004-07-11 17:28:43 +00001730 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001731 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001732 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001733
Chris Lattner52e20b02003-03-19 20:54:26 +00001734 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001735
Chris Lattner70cc3392001-09-10 07:58:01 +00001736 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001737 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001738 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001739 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001740
Reid Spencer060d25d2004-06-29 23:29:38 +00001741 unsigned initSlot = 0;
1742 if (hasInitializer) {
1743 initSlot = read_vbr_uint();
1744 GlobalInits.push_back(std::make_pair(GV, initSlot));
1745 }
1746
1747 // Notify handler about the global value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001748 if (Handler) Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001749
1750 // Get next item
1751 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001752 }
1753
Chris Lattner52e20b02003-03-19 20:54:26 +00001754 // Read the function objects for all of the functions that are coming
Reid Spencer04cde2c2004-07-04 11:33:49 +00001755 unsigned FnSignature = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001756 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001757 error("Invalid function type (type type) found");
1758
Chris Lattner74734132002-08-17 22:01:27 +00001759 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1760 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +00001761 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001762 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001763 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001764 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001765 // FIXME: what should Ty be if handler continues?
1766 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001767
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001768 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001769 const FunctionType* FTy =
1770 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001771
Reid Spencer060d25d2004-06-29 23:29:38 +00001772 // Insert the place hodler
1773 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001774 "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001775 insertValue(Func, FnSignature, ModuleValues);
Chris Lattner00950542001-06-06 20:29:01 +00001776
Reid Spencer060d25d2004-06-29 23:29:38 +00001777 // Save this for later so we know type of lazily instantiated functions
Chris Lattner29b789b2003-11-19 17:27:18 +00001778 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001779
Reid Spencer04cde2c2004-07-04 11:33:49 +00001780 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001781
1782 // Get Next function signature
Reid Spencer46b002c2004-07-11 17:28:43 +00001783 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001784 error("Invalid function type (type type) found");
Chris Lattner00950542001-06-06 20:29:01 +00001785 }
1786
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001787 if (hasInconsistentModuleGlobalInfo)
Reid Spencer060d25d2004-06-29 23:29:38 +00001788 align32();
Chris Lattner74734132002-08-17 22:01:27 +00001789
1790 // Now that the function signature list is set up, reverse it so that we can
1791 // remove elements efficiently from the back of the vector.
1792 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001793
1794 // This is for future proofing... in the future extra fields may be added that
1795 // we don't understand, so we transparently ignore them.
1796 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001797 At = BlockEnd;
1798
Reid Spencer04cde2c2004-07-04 11:33:49 +00001799 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001800}
1801
Reid Spencer04cde2c2004-07-04 11:33:49 +00001802/// Parse the version information and decode it by setting flags on the
1803/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001804void BytecodeReader::ParseVersionInfo() {
1805 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001806
1807 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001808 Module::Endianness Endianness;
1809 Module::PointerSize PointerSize;
1810 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1811 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1812
1813 bool hasNoEndianness = Version & 4;
1814 bool hasNoPointerSize = Version & 8;
1815
1816 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001817
1818 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001819 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001820 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001821 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001822 hasTypeDerivedFromValue = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001823
1824 switch (RevisionNum) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001825 case 0: // LLVM 1.0, 1.1 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001826 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001827 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001828 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001829
Chris Lattner80b97342004-01-17 23:25:43 +00001830 // FALL THROUGH
Chris Lattnerc08912f2004-01-14 16:44:44 +00001831 case 1: // LLVM 1.2 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001832 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001833
1834 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1835 // included the size for the alignment at the end, where the rest of the
1836 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001837
1838 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1839 // structures and longs for sequential types.
1840 hasRestrictedGEPTypes = true;
1841
Reid Spencer04cde2c2004-07-04 11:33:49 +00001842 // LLVM 1.2 and before had the Type class derive from Value class. This
1843 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1844 // written differently because Types can no longer be part of the
1845 // type planes for Values.
1846 hasTypeDerivedFromValue = true;
1847
Chris Lattner5fa428f2004-04-05 01:27:26 +00001848 // FALL THROUGH
1849 case 2: // LLVM 1.3 release version
Chris Lattnerc08912f2004-01-14 16:44:44 +00001850 break;
1851
Chris Lattner036b8aa2003-03-06 17:55:45 +00001852 default:
Reid Spencer24399722004-07-09 22:21:33 +00001853 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00001854 }
1855
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001856 if (hasNoEndianness) Endianness = Module::AnyEndianness;
1857 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00001858
Brian Gaekefe2102b2004-07-14 20:33:13 +00001859 TheModule->setEndianness(Endianness);
1860 TheModule->setPointerSize(PointerSize);
1861
Reid Spencer46b002c2004-07-11 17:28:43 +00001862 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001863}
1864
Reid Spencer04cde2c2004-07-04 11:33:49 +00001865/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001866void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001867 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001868
Reid Spencer060d25d2004-06-29 23:29:38 +00001869 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001870
1871 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001872 ParseVersionInfo();
1873 align32(); /// FIXME: Is this redundant? VI is first and 4 bytes!
Chris Lattner00950542001-06-06 20:29:01 +00001874
Reid Spencer060d25d2004-06-29 23:29:38 +00001875 bool SeenModuleGlobalInfo = false;
1876 bool SeenGlobalTypePlane = false;
1877 BufPtr MyEnd = BlockEnd;
1878 while (At < MyEnd) {
1879 BufPtr OldAt = At;
1880 read_block(Type, Size);
1881
Chris Lattner00950542001-06-06 20:29:01 +00001882 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001883
Chris Lattner52e20b02003-03-19 20:54:26 +00001884 case BytecodeFormat::GlobalTypePlane:
Reid Spencer46b002c2004-07-11 17:28:43 +00001885 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001886 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001887
1888 ParseGlobalTypes();
1889 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001890 break;
1891
Reid Spencer060d25d2004-06-29 23:29:38 +00001892 case BytecodeFormat::ModuleGlobalInfo:
Reid Spencer46b002c2004-07-11 17:28:43 +00001893 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001894 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001895 ParseModuleGlobalInfo();
1896 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001897 break;
1898
Chris Lattner1d670cc2001-09-07 16:37:43 +00001899 case BytecodeFormat::ConstantPool:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001900 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001901 break;
1902
Reid Spencer060d25d2004-06-29 23:29:38 +00001903 case BytecodeFormat::Function:
1904 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001905 break;
Chris Lattner00950542001-06-06 20:29:01 +00001906
1907 case BytecodeFormat::SymbolTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001908 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001909 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001910
Chris Lattner00950542001-06-06 20:29:01 +00001911 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001912 At += Size;
1913 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001914 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001915 }
Chris Lattner00950542001-06-06 20:29:01 +00001916 break;
1917 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001918 BlockEnd = MyEnd;
1919 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001920 }
1921
Chris Lattner52e20b02003-03-19 20:54:26 +00001922 // After the module constant pool has been read, we can safely initialize
1923 // global variables...
1924 while (!GlobalInits.empty()) {
1925 GlobalVariable *GV = GlobalInits.back().first;
1926 unsigned Slot = GlobalInits.back().second;
1927 GlobalInits.pop_back();
1928
1929 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001930 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001931
1932 const llvm::PointerType* GVType = GV->getType();
1933 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001934 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00001935 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001936 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001937 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001938 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001939 } else
Reid Spencer24399722004-07-09 22:21:33 +00001940 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001941 }
1942
Reid Spencer060d25d2004-06-29 23:29:38 +00001943 /// Make sure we pulled them all out. If we didn't then there's a declaration
1944 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001945 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001946 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001947}
1948
Reid Spencer04cde2c2004-07-04 11:33:49 +00001949/// This function completely parses a bytecode buffer given by the \p Buf
1950/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00001951void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
1952 const std::string &ModuleID,
1953 bool processFunctions) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001954
Reid Spencer060d25d2004-06-29 23:29:38 +00001955 try {
1956 At = MemStart = BlockStart = Buf;
1957 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001958
Reid Spencer060d25d2004-06-29 23:29:38 +00001959 // Create the module
1960 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00001961
Reid Spencer04cde2c2004-07-04 11:33:49 +00001962 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00001963
1964 // Read and check signature...
1965 unsigned Sig = read_uint();
1966 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
Reid Spencer24399722004-07-09 22:21:33 +00001967 error("Invalid bytecode signature: " + utostr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00001968 }
1969
1970
1971 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00001972 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00001973
1974 // Get the module block and size and verify
1975 unsigned Type, Size;
1976 read_block(Type, Size);
Reid Spencer46b002c2004-07-11 17:28:43 +00001977 if (Type != BytecodeFormat::Module) {
Reid Spencer24399722004-07-09 22:21:33 +00001978 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00001979 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00001980 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001981 if (At + Size != MemEnd) {
Reid Spencer24399722004-07-09 22:21:33 +00001982 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00001983 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00001984 }
1985
1986 // Parse the module contents
1987 this->ParseModule();
1988
Reid Spencer060d25d2004-06-29 23:29:38 +00001989 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00001990 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00001991 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001992
Reid Spencer5c15fe52004-07-05 00:57:50 +00001993 // Process all the function bodies now, if requested
Reid Spencer46b002c2004-07-11 17:28:43 +00001994 if (processFunctions)
Reid Spencer5c15fe52004-07-05 00:57:50 +00001995 ParseAllFunctionBodies();
1996
1997 // Tell the handler we're done with the module
1998 if (Handler)
1999 Handler->handleModuleEnd(ModuleID);
2000
2001 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002002 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002003
Reid Spencer46b002c2004-07-11 17:28:43 +00002004 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002005 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002006 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002007 delete TheModule;
2008 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002009 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002010 } catch (...) {
2011 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002012 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002013 freeState();
2014 delete TheModule;
2015 TheModule = 0;
2016 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002017 }
Chris Lattner00950542001-06-06 20:29:01 +00002018}
Reid Spencer060d25d2004-06-29 23:29:38 +00002019
2020//===----------------------------------------------------------------------===//
2021//=== Default Implementations of Handler Methods
2022//===----------------------------------------------------------------------===//
2023
2024BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002025
2026// vim: sw=2