blob: 8e46083082f9a6632f75066406ce4db96cc12116 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// 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"
Jeff Cohene1337212004-12-20 03:23:46 +000022#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000024#include "llvm/Instructions.h"
25#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000028#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000031#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Reid Spencer46b002c2004-07-11 17:28:43 +000034namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000035 /// @brief A class for maintaining the slot number definition
36 /// as a placeholder for the actual definition for forward constants defs.
37 class ConstantPlaceHolder : public ConstantExpr {
38 ConstantPlaceHolder(); // DO NOT IMPLEMENT
39 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
40 public:
Chris Lattner61323322005-01-31 01:11:13 +000041 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000042 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000043 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
44 Op(UndefValue::get(Type::IntTy), this) {
45 }
Chris Lattnercad28bd2005-01-29 00:36:19 +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)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000071 error(std::string("Attempt to read past the end of ") + block_name +
72 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000073}
Chris Lattner36392bc2003-10-08 21:18:57 +000074
Reid Spencer04cde2c2004-07-04 11:33:49 +000075/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000076inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000077 if (hasAlignment) {
78 BufPtr Save = At;
79 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000080 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000081 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000082 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000083 error("Ran out of data while aligning!");
84 }
Reid Spencer060d25d2004-06-29 23:29:38 +000085}
86
Reid Spencer04cde2c2004-07-04 11:33:49 +000087/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000088inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000089 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000090 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000091 At += 4;
92 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
93}
94
Reid Spencer04cde2c2004-07-04 11:33:49 +000095/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000096inline unsigned BytecodeReader::read_vbr_uint() {
97 unsigned Shift = 0;
98 unsigned Result = 0;
99 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000100
Reid Spencer060d25d2004-06-29 23:29:38 +0000101 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000102 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000103 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000104 Result |= (unsigned)((*At++) & 0x7F) << Shift;
105 Shift += 7;
106 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000107 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000108 return Result;
109}
110
Reid Spencer04cde2c2004-07-04 11:33:49 +0000111/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000112inline uint64_t BytecodeReader::read_vbr_uint64() {
113 unsigned Shift = 0;
114 uint64_t Result = 0;
115 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000116
Reid Spencer060d25d2004-06-29 23:29:38 +0000117 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000118 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000119 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000120 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
121 Shift += 7;
122 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000123 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000124 return Result;
125}
126
Reid Spencer04cde2c2004-07-04 11:33:49 +0000127/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000128inline int64_t BytecodeReader::read_vbr_int64() {
129 uint64_t R = read_vbr_uint64();
130 if (R & 1) {
131 if (R != 1)
132 return -(int64_t)(R >> 1);
133 else // There is no such thing as -0 with integers. "-0" really means
134 // 0x8000000000000000.
135 return 1LL << 63;
136 } else
137 return (int64_t)(R >> 1);
138}
139
Reid Spencer04cde2c2004-07-04 11:33:49 +0000140/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000141inline std::string BytecodeReader::read_str() {
142 unsigned Size = read_vbr_uint();
143 const unsigned char *OldAt = At;
144 At += Size;
145 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000146 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000147 return std::string((char*)OldAt, Size);
148}
149
Reid Spencer04cde2c2004-07-04 11:33:49 +0000150/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000151inline void BytecodeReader::read_data(void *Ptr, void *End) {
152 unsigned char *Start = (unsigned char *)Ptr;
153 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000154 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000155 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000156 std::copy(At, At+Amount, Start);
157 At += Amount;
158}
159
Reid Spencer46b002c2004-07-11 17:28:43 +0000160/// Read a float value in little-endian order
161inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000162 /// FIXME: This isn't optimal, it has size problems on some platforms
163 /// where FP is not IEEE.
164 union {
165 float f;
166 uint32_t i;
167 } FloatUnion;
168 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
169 At+=sizeof(uint32_t);
170 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000171}
172
173/// Read a double value in little-endian order
174inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000175 /// FIXME: This isn't optimal, it has size problems on some platforms
176 /// where FP is not IEEE.
177 union {
178 double d;
179 uint64_t i;
180 } DoubleUnion;
Misha Brukman8a96c532005-04-21 21:44:41 +0000181 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
Chris Lattner1d785162004-07-25 23:15:44 +0000182 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Misha Brukman8a96c532005-04-21 21:44:41 +0000183 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
Reid Spencerada16182004-07-25 21:36:26 +0000184 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
185 At+=sizeof(uint64_t);
186 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000187}
188
Reid Spencer04cde2c2004-07-04 11:33:49 +0000189/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000190inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000191 if ( hasLongBlockHeaders ) {
192 Type = read_uint();
193 Size = read_uint();
194 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000195 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000196 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000197 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000198 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000199 Type = BytecodeFormat::ModuleBlockID; break;
200 case BytecodeFormat::Function:
201 Type = BytecodeFormat::FunctionBlockID; break;
202 case BytecodeFormat::ConstantPool:
203 Type = BytecodeFormat::ConstantPoolBlockID; break;
204 case BytecodeFormat::SymbolTable:
205 Type = BytecodeFormat::SymbolTableBlockID; break;
206 case BytecodeFormat::ModuleGlobalInfo:
207 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
208 case BytecodeFormat::GlobalTypePlane:
209 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
210 case BytecodeFormat::InstructionList:
211 Type = BytecodeFormat::InstructionListBlockID; break;
212 case BytecodeFormat::CompactionTable:
213 Type = BytecodeFormat::CompactionTableBlockID; break;
214 case BytecodeFormat::BasicBlock:
215 /// This block type isn't used after version 1.1. However, we have to
216 /// still allow the value in case this is an old bc format file.
217 /// We just let its value creep thru.
218 break;
219 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000220 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000221 break;
222 }
223 } else {
224 Size = read_uint();
225 Type = Size & 0x1F; // mask low order five bits
226 Size >>= 5; // get rid of five low order bits, leaving high 27
227 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000228 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000229 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000230 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000231 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000232 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000233}
234
235
236/// In LLVM 1.2 and before, Types were derived from Value and so they were
237/// written as part of the type planes along with any other Value. In LLVM
238/// 1.3 this changed so that Type does not derive from Value. Consequently,
239/// the BytecodeReader's containers for Values can't contain Types because
240/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000241/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
242/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000243/// the types are always read/written first and then the Values. Furthermore
244/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
245/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
246/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
247/// For LLVM 1.2 and before, this function will decrement the type id by
248/// one to account for the missing Type::TypeTyID enumerator if the value is
249/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
250/// function returns true, otherwise false. This helps detect situations
251/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000252/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000253inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
254 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
255 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000256 TypeId = Type::VoidTyID; // sanitize it
257 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000258 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000259 --TypeId; // shift all planes down because type type plane is missing
260 }
261 return false;
262}
263
264/// Reads a vbr uint to read in a type id and does the necessary
265/// conversion on it by calling sanitizeTypeId.
266/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
267/// @see sanitizeTypeId
268inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
269 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000270 if ( !has32BitTypes )
271 if ( TypeId == 0x00FFFFFF )
272 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000273 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000274}
275
276//===----------------------------------------------------------------------===//
277// IR Lookup Methods
278//===----------------------------------------------------------------------===//
279
Reid Spencer04cde2c2004-07-04 11:33:49 +0000280/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000281inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000282 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000283 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000284 return TyID >= Type::FirstDerivedTyID;
285}
286
Reid Spencer04cde2c2004-07-04 11:33:49 +0000287/// Obtain a type given a typeid and account for things like compaction tables,
288/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000289const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000290 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000291 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000292 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000293
294 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000295 ID -= Type::FirstDerivedTyID;
296
Reid Spencer060d25d2004-06-29 23:29:38 +0000297 if (!CompactionTypes.empty()) {
298 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000299 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000300 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000301 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000302
303 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000304 if (ID < ModuleTypes.size())
305 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000306
Reid Spencer46b002c2004-07-11 17:28:43 +0000307 // Nope, is it a function-level type?
308 ID -= ModuleTypes.size();
309 if (ID < FunctionTypes.size())
310 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000311
Reid Spencer46b002c2004-07-11 17:28:43 +0000312 error("Illegal type reference!");
313 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000314}
315
Reid Spencer04cde2c2004-07-04 11:33:49 +0000316/// Get a sanitized type id. This just makes sure that the \p ID
317/// is both sanitized and not the "type type" of pre-1.3 bytecode.
318/// @see sanitizeTypeId
319inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000320 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000321 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000322 return getType(ID);
323}
324
325/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000326/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000327/// then calls getType to return the type value.
328inline const Type* BytecodeReader::readSanitizedType() {
329 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000330 if (read_typeid(ID))
331 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000332 return getType(ID);
333}
334
335/// Get the slot number associated with a type accounting for primitive
336/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000337unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
338 if (Ty->isPrimitiveType())
339 return Ty->getTypeID();
340
341 // Scan the compaction table for the type if needed.
342 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000343 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
344 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000345 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000346
Chris Lattner45b5dd22004-08-03 23:41:28 +0000347 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000348 }
349
350 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000351 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
352 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000353
354 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000355 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000356 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000357
358 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000359 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000360 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000361 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000362 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000363}
364
Reid Spencer04cde2c2004-07-04 11:33:49 +0000365/// This is just like getType, but when a compaction table is in use, it is
366/// ignored. It also ignores function level types.
367/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000368const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
369 if (Slot < Type::FirstDerivedTyID) {
370 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000371 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000372 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000373 return Ty;
374 }
375 Slot -= Type::FirstDerivedTyID;
376 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000377 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000378 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000379}
380
Reid Spencer04cde2c2004-07-04 11:33:49 +0000381/// This is just like getTypeSlot, but when a compaction table is in use, it
382/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000383unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
384 if (Ty->isPrimitiveType())
385 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000386 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000387 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000388 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000389 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000390 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
391}
392
Misha Brukman8a96c532005-04-21 21:44:41 +0000393/// Retrieve a value of a given type and slot number, possibly creating
394/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000395Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000396 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000397 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000398
Chris Lattner89e02532004-01-18 21:08:15 +0000399 // If there is a compaction table active, it defines the low-level numbers.
400 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000401 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
402 if (Num < CompactionValues[type].size())
403 return CompactionValues[type][Num];
404 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000405 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000406 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000407 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000408
Chris Lattner45b5dd22004-08-03 23:41:28 +0000409 // If the type plane was compactified, figure out the global type ID by
410 // adding the derived type ids and the distance.
411 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
412 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000413
Reid Spencer060d25d2004-06-29 23:29:38 +0000414 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000415 const Type *Ty = getType(type);
416 if (!isa<OpaqueType>(Ty)) {
417 if (Num == 0)
418 return Constant::getNullValue(Ty);
419 --Num;
420 }
Chris Lattner89e02532004-01-18 21:08:15 +0000421 }
422
Chris Lattner52f86d62004-01-20 00:54:06 +0000423 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
424 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000425 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000426 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000427 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000428 }
429
Misha Brukman8a96c532005-04-21 21:44:41 +0000430 if (FunctionValues.size() > type &&
431 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000432 Num < FunctionValues[type]->size())
433 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000434
Chris Lattner74734132002-08-17 22:01:27 +0000435 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000436
Reid Spencer551ccae2004-09-01 22:55:40 +0000437 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000438 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000439 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000440 if (I != ForwardReferences.end() && I->first == KeyValue)
441 return I->second; // We have already created this placeholder
442
Reid Spencer551ccae2004-09-01 22:55:40 +0000443 // If the type exists (it should)
444 if (const Type* Ty = getType(type)) {
445 // Create the place holder
446 Value *Val = new Argument(Ty);
447 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
448 return Val;
449 }
450 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000451}
452
Misha Brukman8a96c532005-04-21 21:44:41 +0000453/// This is just like getValue, but when a compaction table is in use, it
454/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000455/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000456Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
457 if (SlotNo == 0)
458 return Constant::getNullValue(getType(TyID));
459
460 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
461 TyID -= Type::FirstDerivedTyID;
462 if (TyID >= CompactionTypes.size())
463 error("Type ID out of range for compaction table!");
464 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000465 }
466
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000467 --SlotNo;
468
Reid Spencer060d25d2004-06-29 23:29:38 +0000469 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
470 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000471 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
472 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000473 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000474 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000475 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000476 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000477 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000478 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000479 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
480 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000481 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000482 }
483 return ModuleValues[TyID]->getOperand(SlotNo);
484}
485
Reid Spencer04cde2c2004-07-04 11:33:49 +0000486/// Just like getValue, except that it returns a null pointer
487/// only on error. It always returns a constant (meaning that if the value is
488/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000489/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000490/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000491Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
492 if (Value *V = getValue(TypeSlot, Slot, false))
493 if (Constant *C = dyn_cast<Constant>(V))
494 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000495 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000496 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000497 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000498
Chris Lattner389bd042004-12-09 06:19:44 +0000499 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000500 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
501
502 if (I != ConstantFwdRefs.end() && I->first == Key) {
503 return I->second;
504 } else {
505 // Create a placeholder for the constant reference and
506 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000507 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000508
Reid Spencer060d25d2004-06-29 23:29:38 +0000509 // Keep track of the fact that we have a forward ref to recycle it
510 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
511 return C;
512 }
513}
514
515//===----------------------------------------------------------------------===//
516// IR Construction Methods
517//===----------------------------------------------------------------------===//
518
Reid Spencer04cde2c2004-07-04 11:33:49 +0000519/// As values are created, they are inserted into the appropriate place
520/// with this method. The ValueTable argument must be one of ModuleValues
521/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000522unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000523 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000524 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000525 !hasImplicitNull(type) &&
526 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000527
528 if (ValueTab.size() <= type)
529 ValueTab.resize(type+1);
530
531 if (!ValueTab[type]) ValueTab[type] = new ValueList();
532
533 ValueTab[type]->push_back(Val);
534
Chris Lattneraba5ff52005-05-05 20:57:00 +0000535 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000536 return ValueTab[type]->size()-1 + HasOffset;
537}
538
Reid Spencer04cde2c2004-07-04 11:33:49 +0000539/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000540void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000541 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000542 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000543 for (FunctionType::param_iterator It = FT->param_begin();
544 It != FT->param_end(); ++It, ++AI)
545 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
546}
547
548//===----------------------------------------------------------------------===//
549// Bytecode Parsing Methods
550//===----------------------------------------------------------------------===//
551
Reid Spencer04cde2c2004-07-04 11:33:49 +0000552/// This method parses a single instruction. The instruction is
553/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000554/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000555void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000556 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000557 BufPtr SaveAt = At;
558
559 // Clear instruction data
560 Oprnds.clear();
561 unsigned iType = 0;
562 unsigned Opcode = 0;
563 unsigned Op = read_uint();
564
565 // bits Instruction format: Common to all formats
566 // --------------------------
567 // 01-00: Opcode type, fixed to 1.
568 // 07-02: Opcode
569 Opcode = (Op >> 2) & 63;
570 Oprnds.resize((Op >> 0) & 03);
571
572 // Extract the operands
573 switch (Oprnds.size()) {
574 case 1:
575 // bits Instruction format:
576 // --------------------------
577 // 19-08: Resulting type plane
578 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
579 //
580 iType = (Op >> 8) & 4095;
581 Oprnds[0] = (Op >> 20) & 4095;
582 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
583 Oprnds.resize(0);
584 break;
585 case 2:
586 // bits Instruction format:
587 // --------------------------
588 // 15-08: Resulting type plane
589 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000590 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000591 //
592 iType = (Op >> 8) & 255;
593 Oprnds[0] = (Op >> 16) & 255;
594 Oprnds[1] = (Op >> 24) & 255;
595 break;
596 case 3:
597 // bits Instruction format:
598 // --------------------------
599 // 13-08: Resulting type plane
600 // 19-14: Operand #1
601 // 25-20: Operand #2
602 // 31-26: Operand #3
603 //
604 iType = (Op >> 8) & 63;
605 Oprnds[0] = (Op >> 14) & 63;
606 Oprnds[1] = (Op >> 20) & 63;
607 Oprnds[2] = (Op >> 26) & 63;
608 break;
609 case 0:
610 At -= 4; // Hrm, try this again...
611 Opcode = read_vbr_uint();
612 Opcode >>= 2;
613 iType = read_vbr_uint();
614
615 unsigned NumOprnds = read_vbr_uint();
616 Oprnds.resize(NumOprnds);
617
618 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000619 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000620
621 for (unsigned i = 0; i != NumOprnds; ++i)
622 Oprnds[i] = read_vbr_uint();
623 align32();
624 break;
625 }
626
Reid Spencer04cde2c2004-07-04 11:33:49 +0000627 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000628
Reid Spencer46b002c2004-07-11 17:28:43 +0000629 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000630 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000631
632 // Declare the resulting instruction we'll build.
633 Instruction *Result = 0;
634
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000635 // If this is a bytecode format that did not include the unreachable
636 // instruction, bump up all opcodes numbers to make space.
637 if (hasNoUnreachableInst) {
638 if (Opcode >= Instruction::Unreachable &&
639 Opcode < 62) {
640 ++Opcode;
641 }
642 }
643
Reid Spencer060d25d2004-06-29 23:29:38 +0000644 // Handle binary operators
645 if (Opcode >= Instruction::BinaryOpsBegin &&
646 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
647 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
648 getValue(iType, Oprnds[0]),
649 getValue(iType, Oprnds[1]));
650
651 switch (Opcode) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000652 default:
653 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000654 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000655 break;
656 case Instruction::VAArg:
Misha Brukman8a96c532005-04-21 21:44:41 +0000657 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000658 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000659 break;
660 case Instruction::VANext:
Misha Brukman8a96c532005-04-21 21:44:41 +0000661 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000662 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000663 break;
664 case Instruction::Cast:
Misha Brukman8a96c532005-04-21 21:44:41 +0000665 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000666 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000667 break;
668 case Instruction::Select:
669 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
670 getValue(iType, Oprnds[1]),
671 getValue(iType, Oprnds[2]));
672 break;
673 case Instruction::PHI: {
674 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000675 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000676
677 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000678 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000679 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
680 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
681 Result = PN;
682 break;
683 }
684
685 case Instruction::Shl:
686 case Instruction::Shr:
687 Result = new ShiftInst((Instruction::OtherOps)Opcode,
688 getValue(iType, Oprnds[0]),
689 getValue(Type::UByteTyID, Oprnds[1]));
690 break;
691 case Instruction::Ret:
692 if (Oprnds.size() == 0)
693 Result = new ReturnInst();
694 else if (Oprnds.size() == 1)
695 Result = new ReturnInst(getValue(iType, Oprnds[0]));
696 else
Reid Spencer24399722004-07-09 22:21:33 +0000697 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000698 break;
699
700 case Instruction::Br:
701 if (Oprnds.size() == 1)
702 Result = new BranchInst(getBasicBlock(Oprnds[0]));
703 else if (Oprnds.size() == 3)
Misha Brukman8a96c532005-04-21 21:44:41 +0000704 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000705 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000706 else
Reid Spencer24399722004-07-09 22:21:33 +0000707 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000708 break;
709 case Instruction::Switch: {
710 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000711 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000712
713 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000714 getBasicBlock(Oprnds[1]),
715 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000716 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000717 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000718 getBasicBlock(Oprnds[i+1]));
719 Result = I;
720 break;
721 }
722
Chris Lattner38287bd2005-05-06 06:13:34 +0000723 case 61: // tail call
Reid Spencer060d25d2004-06-29 23:29:38 +0000724 case Instruction::Call: {
725 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000726 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000727
728 Value *F = getValue(iType, Oprnds[0]);
729
730 // Check to make sure we have a pointer to function type
731 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000732 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000733 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000734 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000735
736 std::vector<Value *> Params;
737 if (!FTy->isVarArg()) {
738 FunctionType::param_iterator It = FTy->param_begin();
739
740 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
741 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000742 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000743 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
744 }
745 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000746 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000747 } else {
748 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
749
750 unsigned FirstVariableOperand;
751 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000752 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000753
754 // Read all of the fixed arguments
755 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
756 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000757
Reid Spencer060d25d2004-06-29 23:29:38 +0000758 FirstVariableOperand = FTy->getNumParams();
759
Misha Brukman8a96c532005-04-21 21:44:41 +0000760 if ((Oprnds.size()-FirstVariableOperand) & 1)
Chris Lattner4a242b32004-10-14 01:39:18 +0000761 error("Invalid call instruction!"); // Must be pairs of type/value
Misha Brukman8a96c532005-04-21 21:44:41 +0000762
763 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000764 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000765 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
766 }
767
768 Result = new CallInst(F, Params);
Chris Lattner38287bd2005-05-06 06:13:34 +0000769 if (Opcode == 61) cast<CallInst>(Result)->setTailCall(true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000770 break;
771 }
772 case Instruction::Invoke: {
Misha Brukman8a96c532005-04-21 21:44:41 +0000773 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000774 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000775 Value *F = getValue(iType, Oprnds[0]);
776
777 // Check to make sure we have a pointer to function type
778 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000779 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000780 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000781 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000782 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000783 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000784
785 std::vector<Value *> Params;
786 BasicBlock *Normal, *Except;
787
788 if (!FTy->isVarArg()) {
789 Normal = getBasicBlock(Oprnds[1]);
790 Except = getBasicBlock(Oprnds[2]);
791
792 FunctionType::param_iterator It = FTy->param_begin();
793 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
794 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000795 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000796 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
797 }
798 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000799 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000800 } else {
801 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
802
803 Normal = getBasicBlock(Oprnds[0]);
804 Except = getBasicBlock(Oprnds[1]);
Misha Brukman8a96c532005-04-21 21:44:41 +0000805
Reid Spencer060d25d2004-06-29 23:29:38 +0000806 unsigned FirstVariableArgument = FTy->getNumParams()+2;
807 for (unsigned i = 2; i != FirstVariableArgument; ++i)
808 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
809 Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000810
Reid Spencer060d25d2004-06-29 23:29:38 +0000811 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000812 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000813
814 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
815 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
816 }
817
818 Result = new InvokeInst(F, Normal, Except, Params);
819 break;
820 }
821 case Instruction::Malloc:
Misha Brukman8a96c532005-04-21 21:44:41 +0000822 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000823 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000824 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000825 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000826
827 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
828 Oprnds.size() ? getValue(Type::UIntTyID,
829 Oprnds[0]) : 0);
830 break;
831
832 case Instruction::Alloca:
Misha Brukman8a96c532005-04-21 21:44:41 +0000833 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000834 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000835 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000836 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000837
838 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Misha Brukman8a96c532005-04-21 21:44:41 +0000839 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000840 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000841 break;
842 case Instruction::Free:
843 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000844 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000845 Result = new FreeInst(getValue(iType, Oprnds[0]));
846 break;
847 case Instruction::GetElementPtr: {
848 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000849 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000850
851 std::vector<Value*> Idx;
852
853 const Type *NextTy = InstTy;
854 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
855 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Misha Brukman8a96c532005-04-21 21:44:41 +0000856 if (!TopTy)
857 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000858
859 unsigned ValIdx = Oprnds[i];
860 unsigned IdxTy = 0;
861 if (!hasRestrictedGEPTypes) {
862 // Struct indices are always uints, sequential type indices can be any
863 // of the 32 or 64-bit integer types. The actual choice of type is
864 // encoded in the low two bits of the slot number.
865 if (isa<StructType>(TopTy))
866 IdxTy = Type::UIntTyID;
867 else {
868 switch (ValIdx & 3) {
869 default:
870 case 0: IdxTy = Type::UIntTyID; break;
871 case 1: IdxTy = Type::IntTyID; break;
872 case 2: IdxTy = Type::ULongTyID; break;
873 case 3: IdxTy = Type::LongTyID; break;
874 }
875 ValIdx >>= 2;
876 }
877 } else {
878 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
879 }
880
881 Idx.push_back(getValue(IdxTy, ValIdx));
882
883 // Convert ubyte struct indices into uint struct indices.
884 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
885 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
886 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
887
888 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
889 }
890
891 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
892 break;
893 }
894
895 case 62: // volatile load
896 case Instruction::Load:
897 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000898 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000899 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
900 break;
901
Misha Brukman8a96c532005-04-21 21:44:41 +0000902 case 63: // volatile store
Reid Spencer060d25d2004-06-29 23:29:38 +0000903 case Instruction::Store: {
904 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000905 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000906
907 Value *Ptr = getValue(iType, Oprnds[1]);
908 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
909 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
910 Opcode == 63);
911 break;
912 }
913 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000914 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000915 Result = new UnwindInst();
916 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000917 case Instruction::Unreachable:
918 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
919 Result = new UnreachableInst();
920 break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000921 } // end switch(Opcode)
Reid Spencer060d25d2004-06-29 23:29:38 +0000922
923 unsigned TypeSlot;
924 if (Result->getType() == InstTy)
925 TypeSlot = iType;
926 else
927 TypeSlot = getTypeSlot(Result->getType());
928
929 insertValue(Result, TypeSlot, FunctionValues);
930 BB->getInstList().push_back(Result);
931}
932
Reid Spencer04cde2c2004-07-04 11:33:49 +0000933/// Get a particular numbered basic block, which might be a forward reference.
934/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +0000935/// in a clean manner. This function is used when constructing phi, br, switch,
936/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +0000937/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000938BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000939 // Make sure there is room in the table...
940 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
941
942 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
943 // has already created this block, or if the forward reference has already
944 // been created.
945 if (ParsedBasicBlocks[ID])
946 return ParsedBasicBlocks[ID];
947
948 // Otherwise, the basic block has not yet been created. Do so and add it to
949 // the ParsedBasicBlocks list.
950 return ParsedBasicBlocks[ID] = new BasicBlock();
951}
952
Misha Brukman8a96c532005-04-21 21:44:41 +0000953/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000954/// This method reads in one of the basicblock packets. This method is not used
955/// for bytecode files after LLVM 1.0
956/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000957BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
958 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000959
960 BasicBlock *BB = 0;
961
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000962 if (ParsedBasicBlocks.size() == BlockNo)
963 ParsedBasicBlocks.push_back(BB = new BasicBlock());
964 else if (ParsedBasicBlocks[BlockNo] == 0)
965 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
966 else
967 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000968
Reid Spencer060d25d2004-06-29 23:29:38 +0000969 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000970 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000971 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000972
Reid Spencer46b002c2004-07-11 17:28:43 +0000973 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000974 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000975}
976
Reid Spencer04cde2c2004-07-04 11:33:49 +0000977/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000978/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000979/// in order to avoid per-basic-block overhead.
980/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000981unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000982 unsigned BlockNo = 0;
983 std::vector<unsigned> Args;
984
Reid Spencer46b002c2004-07-11 17:28:43 +0000985 while (moreInBlock()) {
986 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000987 BasicBlock *BB;
988 if (ParsedBasicBlocks.size() == BlockNo)
989 ParsedBasicBlocks.push_back(BB = new BasicBlock());
990 else if (ParsedBasicBlocks[BlockNo] == 0)
991 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
992 else
993 BB = ParsedBasicBlocks[BlockNo];
994 ++BlockNo;
995 F->getBasicBlockList().push_back(BB);
996
997 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000998 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000999 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001000
1001 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001002 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001003
Reid Spencer46b002c2004-07-11 17:28:43 +00001004 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001005 }
1006
1007 return BlockNo;
1008}
1009
Reid Spencer04cde2c2004-07-04 11:33:49 +00001010/// Parse a symbol table. This works for both module level and function
1011/// level symbol tables. For function level symbol tables, the CurrentFunction
1012/// parameter must be non-zero and the ST parameter must correspond to
1013/// CurrentFunction's symbol table. For Module level symbol tables, the
1014/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001015void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001016 SymbolTable *ST) {
1017 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001018
Chris Lattner39cacce2003-10-10 05:43:47 +00001019 // Allow efficient basic block lookup by number.
1020 std::vector<BasicBlock*> BBMap;
1021 if (CurrentFunction)
1022 for (Function::iterator I = CurrentFunction->begin(),
1023 E = CurrentFunction->end(); I != E; ++I)
1024 BBMap.push_back(I);
1025
Reid Spencer04cde2c2004-07-04 11:33:49 +00001026 /// In LLVM 1.3 we write types separately from values so
1027 /// The types are always first in the symbol table. This is
1028 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001029 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001030 // Symtab block header: [num entries]
1031 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001032 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001033 // Symtab entry: [def slot #][name]
1034 unsigned slot = read_vbr_uint();
1035 std::string Name = read_str();
1036 const Type* T = getType(slot);
1037 ST->insert(Name, T);
1038 }
1039 }
1040
Reid Spencer46b002c2004-07-11 17:28:43 +00001041 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001042 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001043 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001044 unsigned Typ = 0;
1045 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001046 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001047
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001048 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001049 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001050 unsigned slot = read_vbr_uint();
1051 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001052
Reid Spencer04cde2c2004-07-04 11:33:49 +00001053 // if we're reading a pre 1.3 bytecode file and the type plane
1054 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001055 if (isTypeType) {
1056 const Type* T = getType(slot);
1057 if (T == 0)
1058 error("Failed type look-up for name '" + Name + "'");
1059 ST->insert(Name, T);
1060 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001061 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001062 Value *V = 0;
1063 if (Typ == Type::LabelTyID) {
1064 if (slot < BBMap.size())
1065 V = BBMap[slot];
1066 } else {
1067 V = getValue(Typ, slot, false); // Find mapping...
1068 }
1069 if (V == 0)
1070 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001071 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001072 }
Chris Lattner00950542001-06-06 20:29:01 +00001073 }
1074 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001075 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001076 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001077}
1078
Misha Brukman8a96c532005-04-21 21:44:41 +00001079/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001080void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001081 for (unsigned i = 0; i != NumEntries; ++i) {
1082 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001083 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001084 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001085 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001086 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001087 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001088 }
1089}
1090
1091/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001092void BytecodeReader::ParseCompactionTable() {
1093
Reid Spencer46b002c2004-07-11 17:28:43 +00001094 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001095 if (Handler) Handler->handleCompactionTableBegin();
1096
Misha Brukman8a96c532005-04-21 21:44:41 +00001097 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001098 // we always write them first in the compaction table
1099 // because they can't occupy a "type plane" where the
1100 // Values reside.
1101 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001102 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001103 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001104 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001105
Reid Spencer46b002c2004-07-11 17:28:43 +00001106 // Compaction tables live in separate blocks so we have to loop
1107 // until we've read the whole thing.
1108 while (moreInBlock()) {
1109 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001110 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001111 unsigned Ty = 0;
1112 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001113
Reid Spencer46b002c2004-07-11 17:28:43 +00001114 // Decode the type from value read in. Most compaction table
1115 // planes will have one or two entries in them. If that's the
1116 // case then the length is encoded in the bottom two bits and
1117 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001119 // In this case, both low-order bits are set (value 3). This
1120 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001121 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001122 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001123 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001124 // In this case, the low-order bits specify the number of entries
1125 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001126 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001127 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001128 NumEntries &= 3;
1129 }
1130
Reid Spencer04cde2c2004-07-04 11:33:49 +00001131 // if we're reading a pre 1.3 bytecode file and the type plane
1132 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001133 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001134 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001135 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001136 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001137 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001138 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001139
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001140 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001141 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001142 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001143
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001144 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001145 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001146
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001147 // Push the implicit zero.
1148 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001149
1150 // Read in each of the entries, put them in the compaction table
1151 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001152 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001153 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001154 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001155 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001156 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001157 }
1158 }
1159 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001160 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001161 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001162}
Misha Brukman8a96c532005-04-21 21:44:41 +00001163
Reid Spencer46b002c2004-07-11 17:28:43 +00001164// Parse a single type. The typeid is read in first. If its a primitive type
1165// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001166// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001167// definition.
1168const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001169 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001170 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001171 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001172
1173 const Type *Result = 0;
1174 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1175 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001176
Reid Spencer060d25d2004-06-29 23:29:38 +00001177 switch (PrimType) {
1178 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001179 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001180
1181 unsigned NumParams = read_vbr_uint();
1182
1183 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001184 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001185 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001186
1187 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1188 if (isVarArg) Params.pop_back();
1189
1190 Result = FunctionType::get(RetType, Params, isVarArg);
1191 break;
1192 }
1193 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001194 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001195 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001196 Result = ArrayType::get(ElementType, NumElements);
1197 break;
1198 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001199 case Type::PackedTyID: {
1200 const Type *ElementType = readSanitizedType();
1201 unsigned NumElements = read_vbr_uint();
1202 Result = PackedType::get(ElementType, NumElements);
1203 break;
1204 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001205 case Type::StructTyID: {
1206 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001207 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001208 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001209 error("Invalid element type (type type) for structure!");
1210
Reid Spencer060d25d2004-06-29 23:29:38 +00001211 while (Typ) { // List is terminated by void/0 typeid
1212 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001213 if (read_typeid(Typ))
1214 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001215 }
1216
1217 Result = StructType::get(Elements);
1218 break;
1219 }
1220 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001221 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001222 break;
1223 }
1224
1225 case Type::OpaqueTyID: {
1226 Result = OpaqueType::get();
1227 break;
1228 }
1229
1230 default:
Reid Spencer24399722004-07-09 22:21:33 +00001231 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001232 break;
1233 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001234 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001235 return Result;
1236}
1237
Reid Spencer5b472d92004-08-21 20:49:23 +00001238// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001239// types. We know that recursive types will only reference the current slab of
1240// values in the type plane, but they can forward reference types before they
1241// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1242// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1243// this ugly problem, we pessimistically insert an opaque type for each type we
1244// are about to read. This means that forward references will resolve to
1245// something and when we reread the type later, we can replace the opaque type
1246// with a new resolved concrete type.
1247//
Reid Spencer46b002c2004-07-11 17:28:43 +00001248void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001249 assert(Tab.size() == 0 && "should not have read type constants in before!");
1250
1251 // Insert a bunch of opaque types to be resolved later...
1252 Tab.reserve(NumEntries);
1253 for (unsigned i = 0; i != NumEntries; ++i)
1254 Tab.push_back(OpaqueType::get());
1255
Misha Brukman8a96c532005-04-21 21:44:41 +00001256 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001257 Handler->handleTypeList(NumEntries);
1258
Reid Spencer060d25d2004-06-29 23:29:38 +00001259 // Loop through reading all of the types. Forward types will make use of the
1260 // opaque types just inserted.
1261 //
1262 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001263 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001264 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001265 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001266 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001267
Misha Brukman8a96c532005-04-21 21:44:41 +00001268 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001269 // the opaque type we previously inserted with the new concrete value. This
1270 // approach helps with forward references to types. The refinement from the
1271 // abstract (opaque) type to the new type causes all uses of the abstract
1272 // type to use the concrete type (NewTy). This will also cause the opaque
1273 // type to be deleted.
1274 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1275
1276 // This should have replaced the old opaque type with the new type in the
1277 // value table... or with a preexisting type that was already in the system.
1278 // Let's just make sure it did.
1279 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1280 }
1281}
1282
Reid Spencer04cde2c2004-07-04 11:33:49 +00001283/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001284Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001285 // We must check for a ConstantExpr before switching by type because
1286 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001287 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001288 // 0 if not expr; numArgs if is expr
1289 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001290
Reid Spencer060d25d2004-06-29 23:29:38 +00001291 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001292 // 'undef' is encoded with 'exprnumargs' == 1.
1293 if (!hasNoUndefValue)
1294 if (--isExprNumArgs == 0)
1295 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001296
Reid Spencer060d25d2004-06-29 23:29:38 +00001297 // FIXME: Encoding of constant exprs could be much more compact!
1298 std::vector<Constant*> ArgVec;
1299 ArgVec.reserve(isExprNumArgs);
1300 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001301
1302 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1303 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001304
Reid Spencer060d25d2004-06-29 23:29:38 +00001305 // Read the slot number and types of each of the arguments
1306 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1307 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001308 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001309 if (read_typeid(ArgTypeSlot))
1310 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001311
Reid Spencer060d25d2004-06-29 23:29:38 +00001312 // Get the arg value from its slot if it exists, otherwise a placeholder
1313 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1314 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001315
Reid Spencer060d25d2004-06-29 23:29:38 +00001316 // Construct a ConstantExpr of the appropriate kind
1317 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001318 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001319 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001320
Reid Spencer060d25d2004-06-29 23:29:38 +00001321 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001322 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001323 return Result;
1324 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1325 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1326
1327 if (hasRestrictedGEPTypes) {
1328 const Type *BaseTy = ArgVec[0]->getType();
1329 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1330 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1331 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1332 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1333 if (isa<StructType>(*GTI)) {
1334 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001335 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001336 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1337 }
1338 }
1339
1340 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001341 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001342 return Result;
1343 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001344 if (ArgVec.size() != 3)
1345 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001346 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001347 ArgVec[2]);
1348 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001349 return Result;
1350 } else { // All other 2-operand expressions
1351 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001352 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001353 return Result;
1354 }
1355 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001356
Reid Spencer060d25d2004-06-29 23:29:38 +00001357 // Ok, not an ConstantExpr. We now know how to read the given type...
1358 const Type *Ty = getType(TypeID);
1359 switch (Ty->getTypeID()) {
1360 case Type::BoolTyID: {
1361 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001362 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001363 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001364 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001365 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001366 return Result;
1367 }
1368
1369 case Type::UByteTyID: // Unsigned integer types...
1370 case Type::UShortTyID:
1371 case Type::UIntTyID: {
1372 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001373 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001374 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001375 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001376 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001377 return Result;
1378 }
1379
1380 case Type::ULongTyID: {
1381 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001382 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001383 return Result;
1384 }
1385
1386 case Type::SByteTyID: // Signed integer types...
1387 case Type::ShortTyID:
1388 case Type::IntTyID: {
1389 case Type::LongTyID:
1390 int64_t Val = read_vbr_int64();
Misha Brukman8a96c532005-04-21 21:44:41 +00001391 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001392 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001393 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001395 return Result;
1396 }
1397
1398 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001399 float Val;
1400 read_float(Val);
1401 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001402 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 return Result;
1404 }
1405
1406 case Type::DoubleTyID: {
1407 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001408 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001410 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001411 return Result;
1412 }
1413
Reid Spencer060d25d2004-06-29 23:29:38 +00001414 case Type::ArrayTyID: {
1415 const ArrayType *AT = cast<ArrayType>(Ty);
1416 unsigned NumElements = AT->getNumElements();
1417 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1418 std::vector<Constant*> Elements;
1419 Elements.reserve(NumElements);
1420 while (NumElements--) // Read all of the elements of the constant.
1421 Elements.push_back(getConstantValue(TypeSlot,
1422 read_vbr_uint()));
1423 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001424 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001425 return Result;
1426 }
1427
1428 case Type::StructTyID: {
1429 const StructType *ST = cast<StructType>(Ty);
1430
1431 std::vector<Constant *> Elements;
1432 Elements.reserve(ST->getNumElements());
1433 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1434 Elements.push_back(getConstantValue(ST->getElementType(i),
1435 read_vbr_uint()));
1436
1437 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001438 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001439 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001440 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001441
Brian Gaeke715c90b2004-08-20 06:00:58 +00001442 case Type::PackedTyID: {
1443 const PackedType *PT = cast<PackedType>(Ty);
1444 unsigned NumElements = PT->getNumElements();
1445 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1446 std::vector<Constant*> Elements;
1447 Elements.reserve(NumElements);
1448 while (NumElements--) // Read all of the elements of the constant.
1449 Elements.push_back(getConstantValue(TypeSlot,
1450 read_vbr_uint()));
1451 Constant* Result = ConstantPacked::get(PT, Elements);
1452 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1453 return Result;
1454 }
1455
Chris Lattner638c3812004-11-19 16:24:05 +00001456 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001457 const PointerType *PT = cast<PointerType>(Ty);
1458 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001459
Reid Spencer060d25d2004-06-29 23:29:38 +00001460 // Check to see if we have already read this global variable...
1461 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001463 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1464 if (!GV) error("GlobalValue not in ValueTable!");
1465 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1466 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001468 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001469 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001470 }
1471
1472 default:
Reid Spencer24399722004-07-09 22:21:33 +00001473 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001474 Ty->getDescription());
1475 break;
1476 }
Reid Spencer24399722004-07-09 22:21:33 +00001477 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001478}
1479
Misha Brukman8a96c532005-04-21 21:44:41 +00001480/// Resolve references for constants. This function resolves the forward
1481/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001482/// replaceAllUsesWith method of Value class to substitute the placeholder
1483/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001484void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1485 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001486 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001487 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001488 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001489
Chris Lattner29b789b2003-11-19 17:27:18 +00001490 Value *PH = I->second; // Get the placeholder...
1491 PH->replaceAllUsesWith(NewV);
1492 delete PH; // Delete the old placeholder
1493 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001494}
1495
Reid Spencer04cde2c2004-07-04 11:33:49 +00001496/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001497void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1498 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001499 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001500 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001501 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001502 const Type *Ty = getType(Typ);
1503 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001504 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001505
Reid Spencer060d25d2004-06-29 23:29:38 +00001506 const ArrayType *ATy = cast<ArrayType>(Ty);
1507 if (ATy->getElementType() != Type::SByteTy &&
1508 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001509 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001510
Reid Spencer060d25d2004-06-29 23:29:38 +00001511 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001512 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001513 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001514
Reid Spencer060d25d2004-06-29 23:29:38 +00001515 std::vector<Constant*> Elements(ATy->getNumElements());
1516 if (ATy->getElementType() == Type::SByteTy)
1517 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1518 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1519 else
1520 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1521 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001522
Reid Spencer060d25d2004-06-29 23:29:38 +00001523 // Create the constant, inserting it as needed.
1524 Constant *C = ConstantArray::get(ATy, Elements);
1525 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001526 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001527 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001528 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001529}
1530
Reid Spencer04cde2c2004-07-04 11:33:49 +00001531/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001532void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001533 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001534 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001535 if (Handler) Handler->handleGlobalConstantsBegin();
1536
1537 /// In LLVM 1.3 Type does not derive from Value so the types
1538 /// do not occupy a plane. Consequently, we read the types
1539 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001540 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001541 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001542 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001543 }
1544
Reid Spencer46b002c2004-07-11 17:28:43 +00001545 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001546 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001547 unsigned Typ = 0;
1548 bool isTypeType = read_typeid(Typ);
1549
1550 /// In LLVM 1.2 and before, Types were written to the
1551 /// bytecode file in the "Type Type" plane (#12).
1552 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001553 if (isTypeType) {
1554 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001555 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001556 /// Use of Type::VoidTyID is a misnomer. It actually means
1557 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001558 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1559 ParseStringConstants(NumEntries, Tab);
1560 } else {
1561 for (unsigned i = 0; i < NumEntries; ++i) {
1562 Constant *C = ParseConstantValue(Typ);
1563 assert(C && "ParseConstantValue returned NULL!");
1564 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001565
Reid Spencer060d25d2004-06-29 23:29:38 +00001566 // If we are reading a function constant table, make sure that we adjust
1567 // the slot number to be the real global constant number.
1568 //
1569 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1570 ModuleValues[Typ])
1571 Slot += ModuleValues[Typ]->size();
Chris Lattner389bd042004-12-09 06:19:44 +00001572 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001573 }
1574 }
1575 }
Chris Lattner02dce162004-12-04 05:28:27 +00001576
1577 // After we have finished parsing the constant pool, we had better not have
1578 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001579 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001580 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001581 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001582 error(utostr(ConstantFwdRefs.size()) +
1583 " unresolved constant reference exist. First one is '" +
1584 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001585 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001586 }
Chris Lattner02dce162004-12-04 05:28:27 +00001587
Reid Spencer060d25d2004-06-29 23:29:38 +00001588 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001589 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001590}
Chris Lattner00950542001-06-06 20:29:01 +00001591
Reid Spencer04cde2c2004-07-04 11:33:49 +00001592/// Parse the contents of a function. Note that this function can be
1593/// called lazily by materializeFunction
1594/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001595void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001596
1597 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001598 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1599
Reid Spencer060d25d2004-06-29 23:29:38 +00001600 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001601 switch (LinkageType) {
1602 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1603 case 1: Linkage = GlobalValue::WeakLinkage; break;
1604 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1605 case 3: Linkage = GlobalValue::InternalLinkage; break;
1606 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001607 default:
Reid Spencer24399722004-07-09 22:21:33 +00001608 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001609 Linkage = GlobalValue::InternalLinkage;
1610 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001611 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001612
Reid Spencer46b002c2004-07-11 17:28:43 +00001613 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001614 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001615
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001616 // Keep track of how many basic blocks we have read in...
1617 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001618 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001619
Reid Spencer060d25d2004-06-29 23:29:38 +00001620 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001621 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001622 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001623 BufPtr OldAt = At;
1624 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001625
1626 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001627 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001628 if (!InsertedArguments) {
1629 // Insert arguments into the value table before we parse the first basic
1630 // block in the function, but after we potentially read in the
1631 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001632 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001633 InsertedArguments = true;
1634 }
1635
Reid Spencer04cde2c2004-07-04 11:33:49 +00001636 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001637 break;
1638
Reid Spencerad89bd62004-07-25 18:07:36 +00001639 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001640 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001641 break;
1642
Chris Lattner00950542001-06-06 20:29:01 +00001643 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001644 if (!InsertedArguments) {
1645 // Insert arguments into the value table before we parse the first basic
1646 // block in the function, but after we potentially read in the
1647 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001648 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001649 InsertedArguments = true;
1650 }
1651
Reid Spencer060d25d2004-06-29 23:29:38 +00001652 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001653 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001654 break;
1655 }
1656
Reid Spencerad89bd62004-07-25 18:07:36 +00001657 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001658 // Insert arguments into the value table before we parse the instruction
1659 // list for the function, but after we potentially read in the compaction
1660 // table.
1661 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001662 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001663 InsertedArguments = true;
1664 }
1665
Misha Brukman8a96c532005-04-21 21:44:41 +00001666 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001667 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001668 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001669 break;
1670 }
1671
Reid Spencerad89bd62004-07-25 18:07:36 +00001672 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001673 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001674 break;
1675
1676 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001677 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001678 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001679 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001680 break;
1681 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001682 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001683
Misha Brukman12c29d12003-09-22 23:38:23 +00001684 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001685 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001686 }
1687
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001688 // Make sure there were no references to non-existant basic blocks.
1689 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001690 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001691
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001692 ParsedBasicBlocks.clear();
1693
Chris Lattner97330cf2003-10-09 23:10:14 +00001694 // Resolve forward references. Replace any uses of a forward reference value
1695 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001696 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001697 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1698 I = ForwardReferences.begin();
1699 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001700 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001701 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001702 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001703 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001704 }
Chris Lattner00950542001-06-06 20:29:01 +00001705
Misha Brukman12c29d12003-09-22 23:38:23 +00001706 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001707 FunctionTypes.clear();
1708 CompactionTypes.clear();
1709 CompactionValues.clear();
1710 freeTable(FunctionValues);
1711
Reid Spencer04cde2c2004-07-04 11:33:49 +00001712 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001713}
1714
Reid Spencer04cde2c2004-07-04 11:33:49 +00001715/// This function parses LLVM functions lazily. It obtains the type of the
1716/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001717/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001718/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001719void BytecodeReader::ParseFunctionLazily() {
1720 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001721 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001722
Reid Spencer060d25d2004-06-29 23:29:38 +00001723 Function *Func = FunctionSignatureList.back();
1724 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001725
Reid Spencer060d25d2004-06-29 23:29:38 +00001726 // Save the information for future reading of the function
1727 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001728
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001729 // This function has a body but it's not loaded so it appears `External'.
1730 // Mark it as a `Ghost' instead to notify the users that it has a body.
1731 Func->setLinkage(GlobalValue::GhostLinkage);
1732
Reid Spencer060d25d2004-06-29 23:29:38 +00001733 // Pretend we've `parsed' this function
1734 At = BlockEnd;
1735}
Chris Lattner89e02532004-01-18 21:08:15 +00001736
Misha Brukman8a96c532005-04-21 21:44:41 +00001737/// The ParserFunction method lazily parses one function. Use this method to
1738/// casue the parser to parse a specific function in the module. Note that
1739/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001740/// ParseAllFunctionBodies.
1741/// @see ParseAllFunctionBodies
1742/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001743void BytecodeReader::ParseFunction(Function* Func) {
1744 // Find {start, end} pointers and slot in the map. If not there, we're done.
1745 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001746
Reid Spencer060d25d2004-06-29 23:29:38 +00001747 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001748 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001749 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001750 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001751 }
1752
Reid Spencer060d25d2004-06-29 23:29:38 +00001753 BlockStart = At = Fi->second.Buf;
1754 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001755 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001756
1757 LazyFunctionLoadMap.erase(Fi);
1758
Reid Spencer46b002c2004-07-11 17:28:43 +00001759 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001760}
1761
Reid Spencer04cde2c2004-07-04 11:33:49 +00001762/// The ParseAllFunctionBodies method parses through all the previously
1763/// unparsed functions in the bytecode file. If you want to completely parse
1764/// a bytecode file, this method should be called after Parsebytecode because
1765/// Parsebytecode only records the locations in the bytecode file of where
1766/// the function definitions are located. This function uses that information
1767/// to materialize the functions.
1768/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001769void BytecodeReader::ParseAllFunctionBodies() {
1770 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1771 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001772
Reid Spencer46b002c2004-07-11 17:28:43 +00001773 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001774 Function* Func = Fi->first;
1775 BlockStart = At = Fi->second.Buf;
1776 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001777 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001778 ++Fi;
1779 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001780 LazyFunctionLoadMap.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001781}
Chris Lattner89e02532004-01-18 21:08:15 +00001782
Reid Spencer04cde2c2004-07-04 11:33:49 +00001783/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001784void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001785 // Read the number of types
1786 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001787
1788 // Ignore the type plane identifier for types if the bc file is pre 1.3
1789 if (hasTypeDerivedFromValue)
1790 read_vbr_uint();
1791
Reid Spencer46b002c2004-07-11 17:28:43 +00001792 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001793}
1794
Reid Spencer04cde2c2004-07-04 11:33:49 +00001795/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001796void BytecodeReader::ParseModuleGlobalInfo() {
1797
Reid Spencer04cde2c2004-07-04 11:33:49 +00001798 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001799
Chris Lattner70cc3392001-09-10 07:58:01 +00001800 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001801 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001802 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001803 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1804 // Linkage, bit4+ = slot#
1805 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001806 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001807 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001808 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001809 bool isConstant = VarType & 1;
1810 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001811 GlobalValue::LinkageTypes Linkage;
1812
Chris Lattnerc08912f2004-01-14 16:44:44 +00001813 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001814 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1815 case 1: Linkage = GlobalValue::WeakLinkage; break;
1816 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1817 case 3: Linkage = GlobalValue::InternalLinkage; break;
1818 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001819 default:
Reid Spencer24399722004-07-09 22:21:33 +00001820 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001821 Linkage = GlobalValue::InternalLinkage;
1822 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001823 }
1824
1825 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001826 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001827 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001828 }
1829
Reid Spencer46b002c2004-07-11 17:28:43 +00001830 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001831 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001832 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001833
Chris Lattner52e20b02003-03-19 20:54:26 +00001834 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001835
Chris Lattner70cc3392001-09-10 07:58:01 +00001836 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001837 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001838 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001839 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001840
Reid Spencer060d25d2004-06-29 23:29:38 +00001841 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001842 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001843 initSlot = read_vbr_uint();
1844 GlobalInits.push_back(std::make_pair(GV, initSlot));
1845 }
1846
1847 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001848 if (Handler)
1849 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001850
1851 // Get next item
1852 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001853 }
1854
Chris Lattner52e20b02003-03-19 20:54:26 +00001855 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001856 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001857
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001858 if (hasNoFlagsForFunctions)
1859 FnSignature = (FnSignature << 5) + 1;
1860
1861 // List is terminated by VoidTy.
1862 while ((FnSignature >> 5) != Type::VoidTyID) {
1863 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001864 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001865 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001866 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001867 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001868 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001869
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001870 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001871 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001872 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001873
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001874
Chris Lattner18549c22004-11-15 21:43:03 +00001875 // Insert the place holder.
Misha Brukman8a96c532005-04-21 21:44:41 +00001876 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001877 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001878 insertValue(Func, FnSignature >> 5, ModuleValues);
1879
1880 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001881 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001882
Chris Lattner97fbc502004-11-15 22:38:52 +00001883 // Save this for later so we know type of lazily instantiated functions.
1884 // Note that known-external functions do not have FunctionInfo blocks, so we
1885 // do not add them to the FunctionSignatureList.
1886 if ((Flags & (1 << 4)) == 0)
1887 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001888
Chris Lattner479ffeb2005-05-06 20:42:57 +00001889 // Look at the low bits. If there is a calling conv here, apply it,
1890 // read it as a vbr.
1891 Flags &= 15;
1892 if (Flags)
1893 Func->setCallingConv(Flags-1);
1894 else
1895 Func->setCallingConv(read_vbr_uint());
1896
Reid Spencer04cde2c2004-07-04 11:33:49 +00001897 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001898
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001899 // Get the next function signature.
1900 FnSignature = read_vbr_uint();
1901 if (hasNoFlagsForFunctions)
1902 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001903 }
1904
Misha Brukman8a96c532005-04-21 21:44:41 +00001905 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001906 // remove elements efficiently from the back of the vector.
1907 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001908
Reid Spencerad89bd62004-07-25 18:07:36 +00001909 // If this bytecode format has dependent library information in it ..
1910 if (!hasNoDependentLibraries) {
1911 // Read in the number of dependent library items that follow
1912 unsigned num_dep_libs = read_vbr_uint();
1913 std::string dep_lib;
1914 while( num_dep_libs-- ) {
1915 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001916 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001917 if (Handler)
1918 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001919 }
1920
Reid Spencer5b472d92004-08-21 20:49:23 +00001921
Reid Spencerad89bd62004-07-25 18:07:36 +00001922 // Read target triple and place into the module
1923 std::string triple = read_str();
1924 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001925 if (Handler)
1926 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001927 }
1928
1929 if (hasInconsistentModuleGlobalInfo)
1930 align32();
1931
Chris Lattner00950542001-06-06 20:29:01 +00001932 // This is for future proofing... in the future extra fields may be added that
1933 // we don't understand, so we transparently ignore them.
1934 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001935 At = BlockEnd;
1936
Reid Spencer04cde2c2004-07-04 11:33:49 +00001937 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001938}
1939
Reid Spencer04cde2c2004-07-04 11:33:49 +00001940/// Parse the version information and decode it by setting flags on the
1941/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001942void BytecodeReader::ParseVersionInfo() {
1943 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001944
1945 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001946 Module::Endianness Endianness;
1947 Module::PointerSize PointerSize;
1948 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1949 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1950
1951 bool hasNoEndianness = Version & 4;
1952 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00001953
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001954 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001955
1956 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001957 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001958 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001959 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001960 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001961 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001962 has32BitTypes = false;
1963 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00001964 hasAlignment = false;
Reid Spencer5b472d92004-08-21 20:49:23 +00001965 hasInconsistentBBSlotNums = false;
1966 hasVBRByteTypes = false;
1967 hasUnnecessaryModuleBlockId = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001968 hasNoUndefValue = false;
1969 hasNoFlagsForFunctions = false;
1970 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001971
1972 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00001973 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001974 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001975 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001976 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001977
Chris Lattner80b97342004-01-17 23:25:43 +00001978 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001979
1980 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001981 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001982
1983 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1984 // included the size for the alignment at the end, where the rest of the
1985 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001986
1987 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1988 // structures and longs for sequential types.
1989 hasRestrictedGEPTypes = true;
1990
Reid Spencer04cde2c2004-07-04 11:33:49 +00001991 // LLVM 1.2 and before had the Type class derive from Value class. This
1992 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00001993 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001994 // type planes for Values.
1995 hasTypeDerivedFromValue = true;
1996
Chris Lattner5fa428f2004-04-05 01:27:26 +00001997 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00001998
Reid Spencer5b472d92004-08-21 20:49:23 +00001999 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002000
Reid Spencer5b472d92004-08-21 20:49:23 +00002001 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002002 // especially for small files where the 8 bytes per block is a large
2003 // fraction of the total block size. In LLVM 1.3, the block type and length
2004 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2005 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002006 hasLongBlockHeaders = true;
2007
Reid Spencer5b472d92004-08-21 20:49:23 +00002008 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002009 // this has been reduced to vbr_uint24. It shouldn't make much difference
2010 // since we haven't run into a module with > 24 million types, but for
2011 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2012 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002013 has32BitTypes = true;
2014
Misha Brukman8a96c532005-04-21 21:44:41 +00002015 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002016 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2017 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002018 hasNoDependentLibraries = true;
2019
2020 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002021
2022 case 3: // LLVM 1.3 (Released)
2023 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002024 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002025 // of GEP references to a constant array), this can increase the file size
2026 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002027 hasAlignment = true;
2028
2029 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002030
Reid Spencer5b472d92004-08-21 20:49:23 +00002031 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002032 // In version 4, we did not support the 'undef' constant.
2033 hasNoUndefValue = true;
2034
2035 // In version 4 and above, we did not include space for flags for functions
2036 // in the module info block.
2037 hasNoFlagsForFunctions = true;
2038
2039 // In version 4 and above, we did not include the 'unreachable' instruction
2040 // in the opcode numbering in the bytecode file.
2041 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002042 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002043
2044 // FALL THROUGH
2045
2046 case 5: // 1.x.x (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002047 break;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002048 // FIXME: NONE of this is implemented yet!
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002049
Misha Brukman8a96c532005-04-21 21:44:41 +00002050 // In version 5, basic blocks have a minimum index of 0 whereas all the
2051 // other primitives have a minimum index of 1 (because 0 is the "null"
Reid Spencer5b472d92004-08-21 20:49:23 +00002052 // value. In version 5, we made this consistent.
2053 hasInconsistentBBSlotNums = true;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002054
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002055 // In version 5, the types SByte and UByte were encoded as vbr_uint so that
Reid Spencer5b472d92004-08-21 20:49:23 +00002056 // signed values > 63 and unsigned values >127 would be encoded as two
2057 // bytes. In version 5, they are encoded directly in a single byte.
2058 hasVBRByteTypes = true;
2059
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002060 // In version 5, modules begin with a "Module Block" which encodes a 4-byte
Reid Spencer5b472d92004-08-21 20:49:23 +00002061 // integer value 0x01 to identify the module block. This is unnecessary and
2062 // removed in version 5.
2063 hasUnnecessaryModuleBlockId = true;
2064
Chris Lattner036b8aa2003-03-06 17:55:45 +00002065 default:
Reid Spencer24399722004-07-09 22:21:33 +00002066 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002067 }
2068
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002069 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2070 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002071
Brian Gaekefe2102b2004-07-14 20:33:13 +00002072 TheModule->setEndianness(Endianness);
2073 TheModule->setPointerSize(PointerSize);
2074
Reid Spencer46b002c2004-07-11 17:28:43 +00002075 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002076}
2077
Reid Spencer04cde2c2004-07-04 11:33:49 +00002078/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002079void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002080 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002081
Reid Spencer060d25d2004-06-29 23:29:38 +00002082 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002083
2084 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002085 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002086 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002087
Reid Spencer060d25d2004-06-29 23:29:38 +00002088 bool SeenModuleGlobalInfo = false;
2089 bool SeenGlobalTypePlane = false;
2090 BufPtr MyEnd = BlockEnd;
2091 while (At < MyEnd) {
2092 BufPtr OldAt = At;
2093 read_block(Type, Size);
2094
Chris Lattner00950542001-06-06 20:29:01 +00002095 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002096
Reid Spencerad89bd62004-07-25 18:07:36 +00002097 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002098 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002099 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002100
Reid Spencer5b472d92004-08-21 20:49:23 +00002101 if (Size > 0)
2102 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002103 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002104 break;
2105
Misha Brukman8a96c532005-04-21 21:44:41 +00002106 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002107 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002108 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002109 ParseModuleGlobalInfo();
2110 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002111 break;
2112
Reid Spencerad89bd62004-07-25 18:07:36 +00002113 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002114 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002115 break;
2116
Reid Spencerad89bd62004-07-25 18:07:36 +00002117 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002118 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002119 break;
Chris Lattner00950542001-06-06 20:29:01 +00002120
Reid Spencerad89bd62004-07-25 18:07:36 +00002121 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002122 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002123 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002124
Chris Lattner00950542001-06-06 20:29:01 +00002125 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002126 At += Size;
2127 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002128 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002129 }
Chris Lattner00950542001-06-06 20:29:01 +00002130 break;
2131 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002132 BlockEnd = MyEnd;
2133 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002134 }
2135
Chris Lattner52e20b02003-03-19 20:54:26 +00002136 // After the module constant pool has been read, we can safely initialize
2137 // global variables...
2138 while (!GlobalInits.empty()) {
2139 GlobalVariable *GV = GlobalInits.back().first;
2140 unsigned Slot = GlobalInits.back().second;
2141 GlobalInits.pop_back();
2142
2143 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002144 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002145
2146 const llvm::PointerType* GVType = GV->getType();
2147 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002148 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002149 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002150 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002151 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002152 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002153 } else
Reid Spencer24399722004-07-09 22:21:33 +00002154 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002155 }
2156
Chris Lattneraba5ff52005-05-05 20:57:00 +00002157 if (!ConstantFwdRefs.empty())
2158 error("Use of undefined constants in a module");
2159
Reid Spencer060d25d2004-06-29 23:29:38 +00002160 /// Make sure we pulled them all out. If we didn't then there's a declaration
2161 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002162 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002163 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002164}
2165
Reid Spencer04cde2c2004-07-04 11:33:49 +00002166/// This function completely parses a bytecode buffer given by the \p Buf
2167/// and \p Length parameters.
Misha Brukman8a96c532005-04-21 21:44:41 +00002168void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002169 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002170
Reid Spencer060d25d2004-06-29 23:29:38 +00002171 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002172 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002173 At = MemStart = BlockStart = Buf;
2174 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002175
Reid Spencer060d25d2004-06-29 23:29:38 +00002176 // Create the module
2177 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002178
Reid Spencer04cde2c2004-07-04 11:33:49 +00002179 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002180
Reid Spencerf0c977c2004-11-07 18:20:55 +00002181 // Read the four bytes of the signature.
2182 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002183
Reid Spencerf0c977c2004-11-07 18:20:55 +00002184 // If this is a compressed file
2185 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002186
Reid Spencerf0c977c2004-11-07 18:20:55 +00002187 // Invoke the decompression of the bytecode. Note that we have to skip the
2188 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002189 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2190 // member for retention until BytecodeReader is destructed.
2191 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2192 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002193
2194 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002195 // into the new decompressed block. After decompression, the
2196 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002197 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002198 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002199 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002200
Reid Spencerf0c977c2004-11-07 18:20:55 +00002201 // else if this isn't a regular (uncompressed) bytecode file, then its
2202 // and error, generate that now.
2203 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2204 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002205 }
2206
Reid Spencer060d25d2004-06-29 23:29:38 +00002207 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002208 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002209
Reid Spencerad89bd62004-07-25 18:07:36 +00002210 // Get the module block and size and verify. This is handled specially
2211 // because the module block/size is always written in long format. Other
2212 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002213 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002214 Type = read_uint();
2215 Size = read_uint();
2216 if (Type != BytecodeFormat::ModuleBlockID) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002217 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002218 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002219 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002220
2221 // It looks like the darwin ranlib program is broken, and adds trailing
2222 // garbage to the end of some bytecode files. This hack allows the bc
2223 // reader to ignore trailing garbage on bytecode files.
2224 if (At + Size < MemEnd)
2225 MemEnd = BlockEnd = At+Size;
2226
2227 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002228 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002229 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002230
2231 // Parse the module contents
2232 this->ParseModule();
2233
Reid Spencer060d25d2004-06-29 23:29:38 +00002234 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002235 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002236 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002237
Reid Spencer5c15fe52004-07-05 00:57:50 +00002238 // Tell the handler we're done with the module
Misha Brukman8a96c532005-04-21 21:44:41 +00002239 if (Handler)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002240 Handler->handleModuleEnd(ModuleID);
2241
2242 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002243 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002244
Reid Spencer46b002c2004-07-11 17:28:43 +00002245 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002246 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002247 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002248 delete TheModule;
2249 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002250 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002251 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002252 decompressedBlock = 0;
2253 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002254 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002255 } catch (...) {
2256 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002257 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002258 freeState();
2259 delete TheModule;
2260 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002261 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002262 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002263 decompressedBlock = 0;
2264 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002265 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002266 }
Chris Lattner00950542001-06-06 20:29:01 +00002267}
Reid Spencer060d25d2004-06-29 23:29:38 +00002268
2269//===----------------------------------------------------------------------===//
2270//=== Default Implementations of Handler Methods
2271//===----------------------------------------------------------------------===//
2272
2273BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002274