blob: b91604acd7b8b03613a4ce1b7adc79fb7ddb6894 [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"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000024#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000025#include "llvm/Instructions.h"
26#include "llvm/SymbolTable.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000027#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000048 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000049 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
57 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000078 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000079 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000080 At += 4;
81 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
82}
83
Reid Spencer04cde2c2004-07-04 11:33:49 +000084/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000085inline unsigned BytecodeReader::read_vbr_uint() {
86 unsigned Shift = 0;
87 unsigned Result = 0;
88 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +000089
Reid Spencer060d25d2004-06-29 23:29:38 +000090 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000091 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000092 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000093 Result |= (unsigned)((*At++) & 0x7F) << Shift;
94 Shift += 7;
95 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +000096 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000097 return Result;
98}
99
Reid Spencer04cde2c2004-07-04 11:33:49 +0000100/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000101inline uint64_t BytecodeReader::read_vbr_uint64() {
102 unsigned Shift = 0;
103 uint64_t Result = 0;
104 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000105
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000107 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000108 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
110 Shift += 7;
111 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000113 return Result;
114}
115
Reid Spencer04cde2c2004-07-04 11:33:49 +0000116/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000117inline int64_t BytecodeReader::read_vbr_int64() {
118 uint64_t R = read_vbr_uint64();
119 if (R & 1) {
120 if (R != 1)
121 return -(int64_t)(R >> 1);
122 else // There is no such thing as -0 with integers. "-0" really means
123 // 0x8000000000000000.
124 return 1LL << 63;
125 } else
126 return (int64_t)(R >> 1);
127}
128
Reid Spencer04cde2c2004-07-04 11:33:49 +0000129/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000130inline std::string BytecodeReader::read_str() {
131 unsigned Size = read_vbr_uint();
132 const unsigned char *OldAt = At;
133 At += Size;
134 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000135 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000136 return std::string((char*)OldAt, Size);
137}
138
Reid Spencer04cde2c2004-07-04 11:33:49 +0000139/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000140inline void BytecodeReader::read_data(void *Ptr, void *End) {
141 unsigned char *Start = (unsigned char *)Ptr;
142 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000143 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000144 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000145 std::copy(At, At+Amount, Start);
146 At += Amount;
147}
148
Reid Spencer46b002c2004-07-11 17:28:43 +0000149/// Read a float value in little-endian order
150inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000151 /// FIXME: This isn't optimal, it has size problems on some platforms
152 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000153 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000154 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000155}
156
157/// Read a double value in little-endian order
158inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000159 /// FIXME: This isn't optimal, it has size problems on some platforms
160 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000161 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
162 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
163 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
164 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000165 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000166}
167
Reid Spencer04cde2c2004-07-04 11:33:49 +0000168/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000169inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000170 Size = read_uint(); // Read the header
171 Type = Size & 0x1F; // mask low order five bits to get type
172 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000173 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000174 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000175 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000176 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000177 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000178}
179
Reid Spencer060d25d2004-06-29 23:29:38 +0000180//===----------------------------------------------------------------------===//
181// IR Lookup Methods
182//===----------------------------------------------------------------------===//
183
Reid Spencer04cde2c2004-07-04 11:33:49 +0000184/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000185inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000186 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000187}
188
Reid Spencer04cde2c2004-07-04 11:33:49 +0000189/// Obtain a type given a typeid and account for things like compaction tables,
190/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000191const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000192 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000193 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000194 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000195
196 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000197 ID -= Type::FirstDerivedTyID;
198
Reid Spencer060d25d2004-06-29 23:29:38 +0000199 if (!CompactionTypes.empty()) {
200 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000201 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000202 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000203 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000204
205 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000206 if (ID < ModuleTypes.size())
207 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000208
Reid Spencer46b002c2004-07-11 17:28:43 +0000209 // Nope, is it a function-level type?
210 ID -= ModuleTypes.size();
211 if (ID < FunctionTypes.size())
212 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000213
Reid Spencer46b002c2004-07-11 17:28:43 +0000214 error("Illegal type reference!");
215 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000216}
217
Reid Spencer3795ad12006-12-03 05:47:10 +0000218/// This method just saves some coding. It uses read_vbr_uint to read in a
219/// type id, errors that its not the type type, and then calls getType to
220/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000221inline const Type* BytecodeReader::readType() {
222 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000223}
224
225/// Get the slot number associated with a type accounting for primitive
226/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000227unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
228 if (Ty->isPrimitiveType())
229 return Ty->getTypeID();
230
231 // Scan the compaction table for the type if needed.
232 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000233 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
234 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000235 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000236
Chris Lattner45b5dd22004-08-03 23:41:28 +0000237 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000238 }
239
240 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000241 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
242 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000243
244 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000245 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000246 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000247
Chris Lattnereebac5f2005-10-03 21:26:53 +0000248 // If we don't have our cache yet, build it now.
249 if (ModuleTypeIDCache.empty()) {
250 unsigned N = 0;
251 ModuleTypeIDCache.reserve(ModuleTypes.size());
252 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
253 I != E; ++I, ++N)
254 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
255
256 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
257 }
258
259 // Binary search the cache for the entry.
260 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
261 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
262 std::make_pair(Ty, 0U));
263 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000264 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000265
266 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000267}
268
Reid Spencer04cde2c2004-07-04 11:33:49 +0000269/// This is just like getType, but when a compaction table is in use, it is
270/// ignored. It also ignores function level types.
271/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000272const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
273 if (Slot < Type::FirstDerivedTyID) {
274 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000275 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000276 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000277 return Ty;
278 }
279 Slot -= Type::FirstDerivedTyID;
280 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000281 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000282 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000283}
284
Reid Spencer04cde2c2004-07-04 11:33:49 +0000285/// This is just like getTypeSlot, but when a compaction table is in use, it
286/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000287unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
288 if (Ty->isPrimitiveType())
289 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000290
291 // If we don't have our cache yet, build it now.
292 if (ModuleTypeIDCache.empty()) {
293 unsigned N = 0;
294 ModuleTypeIDCache.reserve(ModuleTypes.size());
295 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
296 I != E; ++I, ++N)
297 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
298
299 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
300 }
301
302 // Binary search the cache for the entry.
303 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
304 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
305 std::make_pair(Ty, 0U));
306 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000307 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000308
309 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000310}
311
Misha Brukman8a96c532005-04-21 21:44:41 +0000312/// Retrieve a value of a given type and slot number, possibly creating
313/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000314Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000315 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000316 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000317
Chris Lattner89e02532004-01-18 21:08:15 +0000318 // If there is a compaction table active, it defines the low-level numbers.
319 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000320 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
321 if (Num < CompactionValues[type].size())
322 return CompactionValues[type][Num];
323 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000324 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000325 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000326 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000327
Chris Lattner45b5dd22004-08-03 23:41:28 +0000328 // If the type plane was compactified, figure out the global type ID by
329 // adding the derived type ids and the distance.
330 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
331 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000332
Reid Spencer060d25d2004-06-29 23:29:38 +0000333 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000334 const Type *Ty = getType(type);
335 if (!isa<OpaqueType>(Ty)) {
336 if (Num == 0)
337 return Constant::getNullValue(Ty);
338 --Num;
339 }
Chris Lattner89e02532004-01-18 21:08:15 +0000340 }
341
Chris Lattner52f86d62004-01-20 00:54:06 +0000342 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
343 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000344 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000345 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000346 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000347 }
348
Misha Brukman8a96c532005-04-21 21:44:41 +0000349 if (FunctionValues.size() > type &&
350 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000351 Num < FunctionValues[type]->size())
352 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000353
Chris Lattner74734132002-08-17 22:01:27 +0000354 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000355
Reid Spencer551ccae2004-09-01 22:55:40 +0000356 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000357 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000358 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000359 if (I != ForwardReferences.end() && I->first == KeyValue)
360 return I->second; // We have already created this placeholder
361
Reid Spencer551ccae2004-09-01 22:55:40 +0000362 // If the type exists (it should)
363 if (const Type* Ty = getType(type)) {
364 // Create the place holder
365 Value *Val = new Argument(Ty);
366 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
367 return Val;
368 }
Reid Spencer233fe722006-08-22 16:09:19 +0000369 error("Can't create placeholder for value of type slot #" + utostr(type));
370 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000371}
372
Misha Brukman8a96c532005-04-21 21:44:41 +0000373/// This is just like getValue, but when a compaction table is in use, it
374/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000375/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000376Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
377 if (SlotNo == 0)
378 return Constant::getNullValue(getType(TyID));
379
380 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
381 TyID -= Type::FirstDerivedTyID;
382 if (TyID >= CompactionTypes.size())
383 error("Type ID out of range for compaction table!");
384 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000385 }
386
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000387 --SlotNo;
388
Reid Spencer060d25d2004-06-29 23:29:38 +0000389 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
390 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000391 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
392 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000393 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000394 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000395 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000396 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000397 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000398 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000399 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
400 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000401 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000402 }
403 return ModuleValues[TyID]->getOperand(SlotNo);
404}
405
Reid Spencer04cde2c2004-07-04 11:33:49 +0000406/// Just like getValue, except that it returns a null pointer
407/// only on error. It always returns a constant (meaning that if the value is
408/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000409/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000410/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000411Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
412 if (Value *V = getValue(TypeSlot, Slot, false))
413 if (Constant *C = dyn_cast<Constant>(V))
414 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000415 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000416 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000417 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000418
Chris Lattner389bd042004-12-09 06:19:44 +0000419 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000420 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
421
422 if (I != ConstantFwdRefs.end() && I->first == Key) {
423 return I->second;
424 } else {
425 // Create a placeholder for the constant reference and
426 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000427 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000428
Reid Spencer060d25d2004-06-29 23:29:38 +0000429 // Keep track of the fact that we have a forward ref to recycle it
430 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
431 return C;
432 }
433}
434
435//===----------------------------------------------------------------------===//
436// IR Construction Methods
437//===----------------------------------------------------------------------===//
438
Reid Spencer04cde2c2004-07-04 11:33:49 +0000439/// As values are created, they are inserted into the appropriate place
440/// with this method. The ValueTable argument must be one of ModuleValues
441/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000442unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000443 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000444 if (ValueTab.size() <= type)
445 ValueTab.resize(type+1);
446
447 if (!ValueTab[type]) ValueTab[type] = new ValueList();
448
449 ValueTab[type]->push_back(Val);
450
Chris Lattneraba5ff52005-05-05 20:57:00 +0000451 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000452 return ValueTab[type]->size()-1 + HasOffset;
453}
454
Reid Spencer04cde2c2004-07-04 11:33:49 +0000455/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000456void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000457 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000458 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000459 for (FunctionType::param_iterator It = FT->param_begin();
460 It != FT->param_end(); ++It, ++AI)
461 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
462}
463
464//===----------------------------------------------------------------------===//
465// Bytecode Parsing Methods
466//===----------------------------------------------------------------------===//
467
Reid Spencer04cde2c2004-07-04 11:33:49 +0000468/// This method parses a single instruction. The instruction is
469/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000470/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000471void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000472 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000473 BufPtr SaveAt = At;
474
475 // Clear instruction data
476 Oprnds.clear();
477 unsigned iType = 0;
478 unsigned Opcode = 0;
479 unsigned Op = read_uint();
480
481 // bits Instruction format: Common to all formats
482 // --------------------------
483 // 01-00: Opcode type, fixed to 1.
484 // 07-02: Opcode
485 Opcode = (Op >> 2) & 63;
486 Oprnds.resize((Op >> 0) & 03);
487
488 // Extract the operands
489 switch (Oprnds.size()) {
490 case 1:
491 // bits Instruction format:
492 // --------------------------
493 // 19-08: Resulting type plane
494 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
495 //
496 iType = (Op >> 8) & 4095;
497 Oprnds[0] = (Op >> 20) & 4095;
498 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
499 Oprnds.resize(0);
500 break;
501 case 2:
502 // bits Instruction format:
503 // --------------------------
504 // 15-08: Resulting type plane
505 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000506 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000507 //
508 iType = (Op >> 8) & 255;
509 Oprnds[0] = (Op >> 16) & 255;
510 Oprnds[1] = (Op >> 24) & 255;
511 break;
512 case 3:
513 // bits Instruction format:
514 // --------------------------
515 // 13-08: Resulting type plane
516 // 19-14: Operand #1
517 // 25-20: Operand #2
518 // 31-26: Operand #3
519 //
520 iType = (Op >> 8) & 63;
521 Oprnds[0] = (Op >> 14) & 63;
522 Oprnds[1] = (Op >> 20) & 63;
523 Oprnds[2] = (Op >> 26) & 63;
524 break;
525 case 0:
526 At -= 4; // Hrm, try this again...
527 Opcode = read_vbr_uint();
528 Opcode >>= 2;
529 iType = read_vbr_uint();
530
531 unsigned NumOprnds = read_vbr_uint();
532 Oprnds.resize(NumOprnds);
533
534 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000535 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000536
537 for (unsigned i = 0; i != NumOprnds; ++i)
538 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000539 break;
540 }
541
Reid Spencerd798a512006-11-14 04:47:22 +0000542 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000543
Reid Spencer1628cec2006-10-26 06:15:43 +0000544 // Make the necessary adjustments for dealing with backwards compatibility
545 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000546 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000547
Reid Spencer46b002c2004-07-11 17:28:43 +0000548 // We have enough info to inform the handler now.
Reid Spencer1628cec2006-10-26 06:15:43 +0000549 if (Handler)
550 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000551
Reid Spencer3795ad12006-12-03 05:47:10 +0000552 // First, handle the easy binary operators case
553 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000554 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000555 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
556 getValue(iType, Oprnds[0]),
557 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000558 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000559 // Indicate that we don't think this is a call instruction (yet).
560 // Process based on the Opcode read
561 switch (Opcode) {
562 default: // There was an error, this shouldn't happen.
563 if (Result == 0)
564 error("Illegal instruction read!");
565 break;
566 case Instruction::VAArg:
567 if (Oprnds.size() != 2)
568 error("Invalid VAArg instruction!");
569 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000570 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000571 break;
572 case Instruction::ExtractElement: {
573 if (Oprnds.size() != 2)
574 error("Invalid extractelement instruction!");
575 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000576 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000577
Reid Spencer1628cec2006-10-26 06:15:43 +0000578 if (!ExtractElementInst::isValidOperands(V1, V2))
579 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000580
Reid Spencer1628cec2006-10-26 06:15:43 +0000581 Result = new ExtractElementInst(V1, V2);
582 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000583 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000584 case Instruction::InsertElement: {
585 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
586 if (!PackedTy || Oprnds.size() != 3)
587 error("Invalid insertelement instruction!");
588
589 Value *V1 = getValue(iType, Oprnds[0]);
590 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000591 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000592
593 if (!InsertElementInst::isValidOperands(V1, V2, V3))
594 error("Invalid insertelement instruction!");
595 Result = new InsertElementInst(V1, V2, V3);
596 break;
597 }
598 case Instruction::ShuffleVector: {
599 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
600 if (!PackedTy || Oprnds.size() != 3)
601 error("Invalid shufflevector instruction!");
602 Value *V1 = getValue(iType, Oprnds[0]);
603 Value *V2 = getValue(iType, Oprnds[1]);
604 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000605 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000606 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
607 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
608 error("Invalid shufflevector instruction!");
609 Result = new ShuffleVectorInst(V1, V2, V3);
610 break;
611 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000612 case Instruction::Trunc:
613 if (Oprnds.size() != 2)
614 error("Invalid cast instruction!");
615 Result = new TruncInst(getValue(iType, Oprnds[0]),
616 getType(Oprnds[1]));
617 break;
618 case Instruction::ZExt:
619 if (Oprnds.size() != 2)
620 error("Invalid cast instruction!");
621 Result = new ZExtInst(getValue(iType, Oprnds[0]),
622 getType(Oprnds[1]));
623 break;
624 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000625 if (Oprnds.size() != 2)
626 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000627 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000628 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000629 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000630 case Instruction::FPTrunc:
631 if (Oprnds.size() != 2)
632 error("Invalid cast instruction!");
633 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
634 getType(Oprnds[1]));
635 break;
636 case Instruction::FPExt:
637 if (Oprnds.size() != 2)
638 error("Invalid cast instruction!");
639 Result = new FPExtInst(getValue(iType, Oprnds[0]),
640 getType(Oprnds[1]));
641 break;
642 case Instruction::UIToFP:
643 if (Oprnds.size() != 2)
644 error("Invalid cast instruction!");
645 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
646 getType(Oprnds[1]));
647 break;
648 case Instruction::SIToFP:
649 if (Oprnds.size() != 2)
650 error("Invalid cast instruction!");
651 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
652 getType(Oprnds[1]));
653 break;
654 case Instruction::FPToUI:
655 if (Oprnds.size() != 2)
656 error("Invalid cast instruction!");
657 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
658 getType(Oprnds[1]));
659 break;
660 case Instruction::FPToSI:
661 if (Oprnds.size() != 2)
662 error("Invalid cast instruction!");
663 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
664 getType(Oprnds[1]));
665 break;
666 case Instruction::IntToPtr:
667 if (Oprnds.size() != 2)
668 error("Invalid cast instruction!");
669 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
670 getType(Oprnds[1]));
671 break;
672 case Instruction::PtrToInt:
673 if (Oprnds.size() != 2)
674 error("Invalid cast instruction!");
675 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
676 getType(Oprnds[1]));
677 break;
678 case Instruction::BitCast:
679 if (Oprnds.size() != 2)
680 error("Invalid cast instruction!");
681 Result = new BitCastInst(getValue(iType, Oprnds[0]),
682 getType(Oprnds[1]));
683 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000684 case Instruction::Select:
685 if (Oprnds.size() != 3)
686 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000687 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000688 getValue(iType, Oprnds[1]),
689 getValue(iType, Oprnds[2]));
690 break;
691 case Instruction::PHI: {
692 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
693 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000694
Reid Spencer1628cec2006-10-26 06:15:43 +0000695 PHINode *PN = new PHINode(InstTy);
696 PN->reserveOperandSpace(Oprnds.size());
697 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
698 PN->addIncoming(
699 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
700 Result = PN;
701 break;
702 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000703 case Instruction::ICmp:
704 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000705 if (Oprnds.size() != 3)
706 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000707 // These instructions encode the comparison predicate as the 3rd operand.
708 Result = CmpInst::create(Instruction::OtherOps(Opcode),
709 static_cast<unsigned short>(Oprnds[2]),
710 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
711 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000712 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000713 case Instruction::LShr:
714 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000715 Result = new ShiftInst(Instruction::OtherOps(Opcode),
716 getValue(iType, Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000717 getValue(Int8TySlot, Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000718 break;
719 case Instruction::Ret:
720 if (Oprnds.size() == 0)
721 Result = new ReturnInst();
722 else if (Oprnds.size() == 1)
723 Result = new ReturnInst(getValue(iType, Oprnds[0]));
724 else
725 error("Unrecognized instruction!");
726 break;
727
728 case Instruction::Br:
729 if (Oprnds.size() == 1)
730 Result = new BranchInst(getBasicBlock(Oprnds[0]));
731 else if (Oprnds.size() == 3)
732 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000733 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000734 else
735 error("Invalid number of operands for a 'br' instruction!");
736 break;
737 case Instruction::Switch: {
738 if (Oprnds.size() & 1)
739 error("Switch statement with odd number of arguments!");
740
741 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
742 getBasicBlock(Oprnds[1]),
743 Oprnds.size()/2-1);
744 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
745 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
746 getBasicBlock(Oprnds[i+1]));
747 Result = I;
748 break;
749 }
750 case 58: // Call with extra operand for calling conv
751 case 59: // tail call, Fast CC
752 case 60: // normal call, Fast CC
753 case 61: // tail call, C Calling Conv
754 case Instruction::Call: { // Normal Call, C Calling Convention
755 if (Oprnds.size() == 0)
756 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000757 Value *F = getValue(iType, Oprnds[0]);
758
759 unsigned CallingConv = CallingConv::C;
760 bool isTailCall = false;
761
762 if (Opcode == 61 || Opcode == 59)
763 isTailCall = true;
764
765 if (Opcode == 58) {
766 isTailCall = Oprnds.back() & 1;
767 CallingConv = Oprnds.back() >> 1;
768 Oprnds.pop_back();
769 } else if (Opcode == 59 || Opcode == 60) {
770 CallingConv = CallingConv::Fast;
771 }
772
773 // Check to make sure we have a pointer to function type
774 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
775 if (PTy == 0) error("Call to non function pointer value!");
776 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
777 if (FTy == 0) error("Call to non function pointer value!");
778
779 std::vector<Value *> Params;
780 if (!FTy->isVarArg()) {
781 FunctionType::param_iterator It = FTy->param_begin();
782
783 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
784 if (It == FTy->param_end())
785 error("Invalid call instruction!");
786 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
787 }
788 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000789 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000790 } else {
791 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
792
793 unsigned FirstVariableOperand;
794 if (Oprnds.size() < FTy->getNumParams())
795 error("Call instruction missing operands!");
796
797 // Read all of the fixed arguments
798 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
799 Params.push_back(
800 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
801
802 FirstVariableOperand = FTy->getNumParams();
803
804 if ((Oprnds.size()-FirstVariableOperand) & 1)
805 error("Invalid call instruction!"); // Must be pairs of type/value
806
807 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
808 i != e; i += 2)
809 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000810 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000811
Reid Spencer1628cec2006-10-26 06:15:43 +0000812 Result = new CallInst(F, Params);
813 if (isTailCall) cast<CallInst>(Result)->setTailCall();
814 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
815 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000816 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000817 case Instruction::Invoke: { // Invoke C CC
818 if (Oprnds.size() < 3)
819 error("Invalid invoke instruction!");
820 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000821
Reid Spencer1628cec2006-10-26 06:15:43 +0000822 // Check to make sure we have a pointer to function type
823 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
824 if (PTy == 0)
825 error("Invoke to non function pointer value!");
826 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
827 if (FTy == 0)
828 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000829
Reid Spencer1628cec2006-10-26 06:15:43 +0000830 std::vector<Value *> Params;
831 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000832 unsigned CallingConv = Oprnds.back();
833 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000834
Reid Spencer1628cec2006-10-26 06:15:43 +0000835 if (!FTy->isVarArg()) {
836 Normal = getBasicBlock(Oprnds[1]);
837 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000838
Reid Spencer1628cec2006-10-26 06:15:43 +0000839 FunctionType::param_iterator It = FTy->param_begin();
840 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
841 if (It == FTy->param_end())
842 error("Invalid invoke instruction!");
843 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
844 }
845 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000846 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000847 } else {
848 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
849
850 Normal = getBasicBlock(Oprnds[0]);
851 Except = getBasicBlock(Oprnds[1]);
852
853 unsigned FirstVariableArgument = FTy->getNumParams()+2;
854 for (unsigned i = 2; i != FirstVariableArgument; ++i)
855 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
856 Oprnds[i]));
857
858 // Must be type/value pairs. If not, error out.
859 if (Oprnds.size()-FirstVariableArgument & 1)
860 error("Invalid invoke instruction!");
861
862 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
863 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000864 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000865
Reid Spencer1628cec2006-10-26 06:15:43 +0000866 Result = new InvokeInst(F, Normal, Except, Params);
867 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
868 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000869 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000870 case Instruction::Malloc: {
871 unsigned Align = 0;
872 if (Oprnds.size() == 2)
873 Align = (1 << Oprnds[1]) >> 1;
874 else if (Oprnds.size() > 2)
875 error("Invalid malloc instruction!");
876 if (!isa<PointerType>(InstTy))
877 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000878
Reid Spencer1628cec2006-10-26 06:15:43 +0000879 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000880 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000881 break;
882 }
883 case Instruction::Alloca: {
884 unsigned Align = 0;
885 if (Oprnds.size() == 2)
886 Align = (1 << Oprnds[1]) >> 1;
887 else if (Oprnds.size() > 2)
888 error("Invalid alloca instruction!");
889 if (!isa<PointerType>(InstTy))
890 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000891
Reid Spencer1628cec2006-10-26 06:15:43 +0000892 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000893 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000894 break;
895 }
896 case Instruction::Free:
897 if (!isa<PointerType>(InstTy))
898 error("Invalid free instruction!");
899 Result = new FreeInst(getValue(iType, Oprnds[0]));
900 break;
901 case Instruction::GetElementPtr: {
902 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000903 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000904
Reid Spencer1628cec2006-10-26 06:15:43 +0000905 std::vector<Value*> Idx;
906
907 const Type *NextTy = InstTy;
908 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
909 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
910 if (!TopTy)
911 error("Invalid getelementptr instruction!");
912
913 unsigned ValIdx = Oprnds[i];
914 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000915 // Struct indices are always uints, sequential type indices can be
916 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000917 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000918 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000919 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000920 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000921 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000922 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000923 case 0: IdxTy = Int32TySlot; break;
924 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000925 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000926 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000927 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000928 Idx.push_back(getValue(IdxTy, ValIdx));
Reid Spencer1628cec2006-10-26 06:15:43 +0000929 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000930 }
931
Reid Spencer1628cec2006-10-26 06:15:43 +0000932 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
933 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000934 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000935 case 62: // volatile load
936 case Instruction::Load:
937 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
938 error("Invalid load instruction!");
939 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
940 break;
941 case 63: // volatile store
942 case Instruction::Store: {
943 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
944 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000945
Reid Spencer1628cec2006-10-26 06:15:43 +0000946 Value *Ptr = getValue(iType, Oprnds[1]);
947 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
948 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
949 Opcode == 63);
950 break;
951 }
952 case Instruction::Unwind:
953 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
954 Result = new UnwindInst();
955 break;
956 case Instruction::Unreachable:
957 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
958 Result = new UnreachableInst();
959 break;
960 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000961 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000962
Reid Spencere1e96c02006-01-19 07:02:16 +0000963 BB->getInstList().push_back(Result);
964
Reid Spencer060d25d2004-06-29 23:29:38 +0000965 unsigned TypeSlot;
966 if (Result->getType() == InstTy)
967 TypeSlot = iType;
968 else
969 TypeSlot = getTypeSlot(Result->getType());
970
971 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000972}
973
Reid Spencer04cde2c2004-07-04 11:33:49 +0000974/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000975/// This works together with ParseInstructionList to handle these forward
976/// references in a clean manner. This function is used when constructing
977/// phi, br, switch, and other instructions that reference basic blocks.
978/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000979BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000980 // Make sure there is room in the table...
981 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
982
Reid Spencerd798a512006-11-14 04:47:22 +0000983 // First check to see if this is a backwards reference, i.e. this block
984 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000985 // been created.
986 if (ParsedBasicBlocks[ID])
987 return ParsedBasicBlocks[ID];
988
989 // Otherwise, the basic block has not yet been created. Do so and add it to
990 // the ParsedBasicBlocks list.
991 return ParsedBasicBlocks[ID] = new BasicBlock();
992}
993
Reid Spencer04cde2c2004-07-04 11:33:49 +0000994/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000995/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000996/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000997/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000998unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000999 unsigned BlockNo = 0;
1000 std::vector<unsigned> Args;
1001
Reid Spencer46b002c2004-07-11 17:28:43 +00001002 while (moreInBlock()) {
1003 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001004 BasicBlock *BB;
1005 if (ParsedBasicBlocks.size() == BlockNo)
1006 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1007 else if (ParsedBasicBlocks[BlockNo] == 0)
1008 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1009 else
1010 BB = ParsedBasicBlocks[BlockNo];
1011 ++BlockNo;
1012 F->getBasicBlockList().push_back(BB);
1013
1014 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001015 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001016 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001017
1018 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001019 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001020
Reid Spencer46b002c2004-07-11 17:28:43 +00001021 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001022 }
1023
1024 return BlockNo;
1025}
1026
Reid Spencer78d033e2007-01-06 07:24:44 +00001027/// Parse a type symbol table.
1028void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
1029 // Type Symtab block header: [num entries]
1030 unsigned NumEntries = read_vbr_uint();
1031 for (unsigned i = 0; i < NumEntries; ++i) {
1032 // Symtab entry: [type slot #][name]
1033 unsigned slot = read_vbr_uint();
1034 std::string Name = read_str();
1035 const Type* T = getType(slot);
1036 TST->insert(Name, T);
1037 }
1038}
1039
1040/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001041/// level symbol tables. For function level symbol tables, the CurrentFunction
1042/// parameter must be non-zero and the ST parameter must correspond to
1043/// CurrentFunction's symbol table. For Module level symbol tables, the
1044/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +00001045void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
1046 SymbolTable *ST) {
1047
Reid Spencer04cde2c2004-07-04 11:33:49 +00001048 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001049
Chris Lattner39cacce2003-10-10 05:43:47 +00001050 // Allow efficient basic block lookup by number.
1051 std::vector<BasicBlock*> BBMap;
1052 if (CurrentFunction)
1053 for (Function::iterator I = CurrentFunction->begin(),
1054 E = CurrentFunction->end(); I != E; ++I)
1055 BBMap.push_back(I);
1056
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001058 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001059 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001060 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +00001061
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001062 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001063 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001064 unsigned slot = read_vbr_uint();
1065 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +00001066 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +00001067 if (Typ == LabelTySlot) {
Reid Spencerd798a512006-11-14 04:47:22 +00001068 if (slot < BBMap.size())
1069 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +00001070 } else {
Reid Spencerd798a512006-11-14 04:47:22 +00001071 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +00001072 }
Reid Spencerd798a512006-11-14 04:47:22 +00001073 if (V == 0)
1074 error("Failed value look-up for name '" + Name + "'");
1075 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +00001076 }
1077 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001078 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001079 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001080}
1081
Misha Brukman8a96c532005-04-21 21:44:41 +00001082/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001083void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001084 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencerd798a512006-11-14 04:47:22 +00001085 unsigned TypeSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001086 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001087 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001088 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001089 }
1090}
1091
1092/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001093void BytecodeReader::ParseCompactionTable() {
1094
Reid Spencer46b002c2004-07-11 17:28:43 +00001095 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001096 if (Handler) Handler->handleCompactionTableBegin();
1097
Reid Spencerd798a512006-11-14 04:47:22 +00001098 // Get the types for the compaction table.
1099 unsigned NumEntries = read_vbr_uint();
1100 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001101
Reid Spencer46b002c2004-07-11 17:28:43 +00001102 // Compaction tables live in separate blocks so we have to loop
1103 // until we've read the whole thing.
1104 while (moreInBlock()) {
1105 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001106 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001107 unsigned Ty = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001108
Reid Spencer46b002c2004-07-11 17:28:43 +00001109 // Decode the type from value read in. Most compaction table
1110 // planes will have one or two entries in them. If that's the
1111 // case then the length is encoded in the bottom two bits and
1112 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001114 // In this case, both low-order bits are set (value 3). This
1115 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001116 NumEntries >>= 2;
Reid Spencerd798a512006-11-14 04:47:22 +00001117 Ty = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001119 // In this case, the low-order bits specify the number of entries
1120 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001121 Ty = NumEntries >> 2;
1122 NumEntries &= 3;
1123 }
1124
Reid Spencerd798a512006-11-14 04:47:22 +00001125 // Make sure we have enough room for the plane.
1126 if (Ty >= CompactionValues.size())
1127 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001128
Reid Spencerd798a512006-11-14 04:47:22 +00001129 // Make sure the plane is empty or we have some kind of error.
1130 if (!CompactionValues[Ty].empty())
1131 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001132
Reid Spencerd798a512006-11-14 04:47:22 +00001133 // Notify handler about the plane.
1134 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001135
Reid Spencerd798a512006-11-14 04:47:22 +00001136 // Push the implicit zero.
1137 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001138
Reid Spencerd798a512006-11-14 04:47:22 +00001139 // Read in each of the entries, put them in the compaction table
1140 // and notify the handler that we have a new compaction table value.
1141 for (unsigned i = 0; i != NumEntries; ++i) {
1142 unsigned ValSlot = read_vbr_uint();
1143 Value *V = getGlobalTableValue(Ty, ValSlot);
1144 CompactionValues[Ty].push_back(V);
1145 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001146 }
1147 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001148 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001149 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001150}
Misha Brukman8a96c532005-04-21 21:44:41 +00001151
Reid Spencer46b002c2004-07-11 17:28:43 +00001152// Parse a single type. The typeid is read in first. If its a primitive type
1153// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001154// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001155// definition.
1156const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +00001157 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001158 const Type *Result = 0;
1159 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1160 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001161
Reid Spencer060d25d2004-06-29 23:29:38 +00001162 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001163 case Type::IntegerTyID: {
1164 unsigned NumBits = read_vbr_uint();
1165 Result = IntegerType::get(NumBits);
1166 break;
1167 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001168 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001169 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +00001170 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001171
1172 unsigned NumParams = read_vbr_uint();
1173
1174 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +00001175 std::vector<FunctionType::ParameterAttributes> Attrs;
1176 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1177 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001178 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001179 if (Params.back() != Type::VoidTy)
1180 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1181 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001182
1183 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1184 if (isVarArg) Params.pop_back();
1185
Reid Spencer88cfda22006-12-31 05:44:24 +00001186 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001187 break;
1188 }
1189 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001190 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001191 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001192 Result = ArrayType::get(ElementType, NumElements);
1193 break;
1194 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001195 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001196 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001197 unsigned NumElements = read_vbr_uint();
1198 Result = PackedType::get(ElementType, NumElements);
1199 break;
1200 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001201 case Type::StructTyID: {
1202 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001203 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001204 while (Typ) { // List is terminated by void/0 typeid
1205 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001206 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001207 }
1208
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001209 Result = StructType::get(Elements, false);
1210 break;
1211 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001212 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001213 std::vector<const Type*> Elements;
1214 unsigned Typ = read_vbr_uint();
1215 while (Typ) { // List is terminated by void/0 typeid
1216 Elements.push_back(getType(Typ));
1217 Typ = read_vbr_uint();
1218 }
1219
1220 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001221 break;
1222 }
1223 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001224 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001225 break;
1226 }
1227
1228 case Type::OpaqueTyID: {
1229 Result = OpaqueType::get();
1230 break;
1231 }
1232
1233 default:
Reid Spencer24399722004-07-09 22:21:33 +00001234 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001235 break;
1236 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001237 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001238 return Result;
1239}
1240
Reid Spencer5b472d92004-08-21 20:49:23 +00001241// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001242// types. We know that recursive types will only reference the current slab of
1243// values in the type plane, but they can forward reference types before they
1244// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1245// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1246// this ugly problem, we pessimistically insert an opaque type for each type we
1247// are about to read. This means that forward references will resolve to
1248// something and when we reread the type later, we can replace the opaque type
1249// with a new resolved concrete type.
1250//
Reid Spencer46b002c2004-07-11 17:28:43 +00001251void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001252 assert(Tab.size() == 0 && "should not have read type constants in before!");
1253
1254 // Insert a bunch of opaque types to be resolved later...
1255 Tab.reserve(NumEntries);
1256 for (unsigned i = 0; i != NumEntries; ++i)
1257 Tab.push_back(OpaqueType::get());
1258
Misha Brukman8a96c532005-04-21 21:44:41 +00001259 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001260 Handler->handleTypeList(NumEntries);
1261
Chris Lattnereebac5f2005-10-03 21:26:53 +00001262 // If we are about to resolve types, make sure the type cache is clear.
1263 if (NumEntries)
1264 ModuleTypeIDCache.clear();
1265
Reid Spencer060d25d2004-06-29 23:29:38 +00001266 // Loop through reading all of the types. Forward types will make use of the
1267 // opaque types just inserted.
1268 //
1269 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001270 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001271 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001272 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001273 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001274
Misha Brukman8a96c532005-04-21 21:44:41 +00001275 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001276 // the opaque type we previously inserted with the new concrete value. This
1277 // approach helps with forward references to types. The refinement from the
1278 // abstract (opaque) type to the new type causes all uses of the abstract
1279 // type to use the concrete type (NewTy). This will also cause the opaque
1280 // type to be deleted.
1281 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1282
1283 // This should have replaced the old opaque type with the new type in the
1284 // value table... or with a preexisting type that was already in the system.
1285 // Let's just make sure it did.
1286 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1287 }
1288}
1289
Reid Spencer04cde2c2004-07-04 11:33:49 +00001290/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001291Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001292 // We must check for a ConstantExpr before switching by type because
1293 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001294 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001295 // 0 if not expr; numArgs if is expr
1296 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001297
Reid Spencer060d25d2004-06-29 23:29:38 +00001298 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001299 // 'undef' is encoded with 'exprnumargs' == 1.
1300 if (isExprNumArgs == 1)
1301 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001302
Reid Spencerd798a512006-11-14 04:47:22 +00001303 // Inline asm is encoded with exprnumargs == ~0U.
1304 if (isExprNumArgs == ~0U) {
1305 std::string AsmStr = read_str();
1306 std::string ConstraintStr = read_str();
1307 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001308
Reid Spencerd798a512006-11-14 04:47:22 +00001309 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1310 const FunctionType *FTy =
1311 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1312
1313 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1314 error("Invalid constraints for inline asm");
1315 if (Flags & ~1U)
1316 error("Invalid flags for inline asm");
1317 bool HasSideEffects = Flags & 1;
1318 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001319 }
Reid Spencerd798a512006-11-14 04:47:22 +00001320
1321 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001322
Reid Spencer060d25d2004-06-29 23:29:38 +00001323 // FIXME: Encoding of constant exprs could be much more compact!
1324 std::vector<Constant*> ArgVec;
1325 ArgVec.reserve(isExprNumArgs);
1326 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001327
Reid Spencer060d25d2004-06-29 23:29:38 +00001328 // Read the slot number and types of each of the arguments
1329 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1330 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001331 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001332
Reid Spencer060d25d2004-06-29 23:29:38 +00001333 // Get the arg value from its slot if it exists, otherwise a placeholder
1334 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1335 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001336
Reid Spencer060d25d2004-06-29 23:29:38 +00001337 // Construct a ConstantExpr of the appropriate kind
1338 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001339 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001340 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001341
Reid Spencera77fa7e2006-12-11 23:20:20 +00001342 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1343 getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001344 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 return Result;
1346 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1347 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
Reid Spencer3da59db2006-11-27 01:05:10 +00001348 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001349 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001350 return Result;
1351 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001352 if (ArgVec.size() != 3)
1353 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001354 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001355 ArgVec[2]);
1356 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001357 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001358 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001359 if (ArgVec.size() != 2 ||
1360 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1361 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001362 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1363 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1364 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001365 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001366 if (ArgVec.size() != 3 ||
1367 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1368 error("Invalid insertelement constand expr arguments");
1369
1370 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001371 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1372 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1373 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001374 } else if (Opcode == Instruction::ShuffleVector) {
1375 if (ArgVec.size() != 3 ||
1376 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001377 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001378 Constant *Result =
1379 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1380 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1381 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001382 } else if (Opcode == Instruction::ICmp) {
1383 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001384 error("Invalid ICmp constant expr arguments.");
1385 unsigned predicate = read_vbr_uint();
1386 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
1387 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1388 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001389 } else if (Opcode == Instruction::FCmp) {
1390 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001391 error("Invalid FCmp constant expr arguments.");
1392 unsigned predicate = read_vbr_uint();
1393 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
1394 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1395 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001396 } else { // All other 2-operand expressions
1397 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001398 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001399 return Result;
1400 }
1401 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001402
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 // Ok, not an ConstantExpr. We now know how to read the given type...
1404 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001405 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001406 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001407 case Type::IntegerTyID: {
1408 const IntegerType *IT = cast<IntegerType>(Ty);
1409 if (IT->getBitWidth() <= 32) {
1410 uint32_t Val = read_vbr_uint();
1411 if (IT->getBitWidth() == 1) {
1412 if (Val != 0 && Val != 1)
1413 error("Invalid boolean value read.");
1414 Result = ConstantInt::get(Type::Int1Ty, Val == 1);
1415 if (Handler) Handler->handleConstantValue(Result);
1416 } else {
1417 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1418 error("Integer value read is invalid for type.");
1419 Result = ConstantInt::get(IT, Val);
1420 if (Handler) Handler->handleConstantValue(Result);
1421 }
1422 } else if (IT->getBitWidth() <= 64) {
1423 uint64_t Val = read_vbr_uint64();
1424 if (!ConstantInt::isValueValidForType(Ty, Val))
1425 error("Invalid constant integer read.");
1426 Result = ConstantInt::get(IT, Val);
1427 if (Handler) Handler->handleConstantValue(Result);
1428 } else
1429 assert("Integer types > 64 bits not supported");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001430 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001431 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001432 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001433 float Val;
1434 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001435 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001436 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001437 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001438 }
1439
1440 case Type::DoubleTyID: {
1441 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001442 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001443 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001444 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001445 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001446 }
1447
Reid Spencer060d25d2004-06-29 23:29:38 +00001448 case Type::ArrayTyID: {
1449 const ArrayType *AT = cast<ArrayType>(Ty);
1450 unsigned NumElements = AT->getNumElements();
1451 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1452 std::vector<Constant*> Elements;
1453 Elements.reserve(NumElements);
1454 while (NumElements--) // Read all of the elements of the constant.
1455 Elements.push_back(getConstantValue(TypeSlot,
1456 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001457 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001458 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001459 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001460 }
1461
1462 case Type::StructTyID: {
1463 const StructType *ST = cast<StructType>(Ty);
1464
1465 std::vector<Constant *> Elements;
1466 Elements.reserve(ST->getNumElements());
1467 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1468 Elements.push_back(getConstantValue(ST->getElementType(i),
1469 read_vbr_uint()));
1470
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001471 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001472 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001473 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001474 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001475
Brian Gaeke715c90b2004-08-20 06:00:58 +00001476 case Type::PackedTyID: {
1477 const PackedType *PT = cast<PackedType>(Ty);
1478 unsigned NumElements = PT->getNumElements();
1479 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1480 std::vector<Constant*> Elements;
1481 Elements.reserve(NumElements);
1482 while (NumElements--) // Read all of the elements of the constant.
1483 Elements.push_back(getConstantValue(TypeSlot,
1484 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001485 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001486 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001487 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001488 }
1489
Chris Lattner638c3812004-11-19 16:24:05 +00001490 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001491 const PointerType *PT = cast<PointerType>(Ty);
1492 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001493
Reid Spencer060d25d2004-06-29 23:29:38 +00001494 // Check to see if we have already read this global variable...
1495 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001496 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001497 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1498 if (!GV) error("GlobalValue not in ValueTable!");
1499 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1500 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001501 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001502 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001503 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001504 }
1505
1506 default:
Reid Spencer24399722004-07-09 22:21:33 +00001507 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001508 Ty->getDescription());
1509 break;
1510 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001511
1512 // Check that we didn't read a null constant if they are implicit for this
1513 // type plane. Do not do this check for constantexprs, as they may be folded
1514 // to a null value in a way that isn't predicted when a .bc file is initially
1515 // produced.
1516 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1517 !hasImplicitNull(TypeID) &&
1518 "Cannot read null values from bytecode!");
1519 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001520}
1521
Misha Brukman8a96c532005-04-21 21:44:41 +00001522/// Resolve references for constants. This function resolves the forward
1523/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001524/// replaceAllUsesWith method of Value class to substitute the placeholder
1525/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001526void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1527 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001528 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001529 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001530 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001531
Chris Lattner29b789b2003-11-19 17:27:18 +00001532 Value *PH = I->second; // Get the placeholder...
1533 PH->replaceAllUsesWith(NewV);
1534 delete PH; // Delete the old placeholder
1535 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001536}
1537
Reid Spencer04cde2c2004-07-04 11:33:49 +00001538/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001539void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1540 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001541 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001542 const Type *Ty = getType(Typ);
1543 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001544 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001545
Reid Spencer060d25d2004-06-29 23:29:38 +00001546 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001547 if (ATy->getElementType() != Type::Int8Ty &&
1548 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001549 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001550
Reid Spencer060d25d2004-06-29 23:29:38 +00001551 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001552 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001553 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001554
Reid Spencer060d25d2004-06-29 23:29:38 +00001555 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001556 const Type* ElemType = ATy->getElementType();
1557 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1558 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001559
Reid Spencer060d25d2004-06-29 23:29:38 +00001560 // Create the constant, inserting it as needed.
1561 Constant *C = ConstantArray::get(ATy, Elements);
1562 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001563 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001564 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001565 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001566}
1567
Reid Spencer04cde2c2004-07-04 11:33:49 +00001568/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001569void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001570 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001571 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001572 if (Handler) Handler->handleGlobalConstantsBegin();
1573
1574 /// In LLVM 1.3 Type does not derive from Value so the types
1575 /// do not occupy a plane. Consequently, we read the types
1576 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001577 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001578 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001579 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001580 }
1581
Reid Spencer46b002c2004-07-11 17:28:43 +00001582 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001583 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001584 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001585
Reid Spencerd798a512006-11-14 04:47:22 +00001586 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001587 /// Use of Type::VoidTyID is a misnomer. It actually means
1588 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001589 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1590 ParseStringConstants(NumEntries, Tab);
1591 } else {
1592 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001593 Value *V = ParseConstantPoolValue(Typ);
1594 assert(V && "ParseConstantPoolValue returned NULL!");
1595 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001596
Reid Spencer060d25d2004-06-29 23:29:38 +00001597 // If we are reading a function constant table, make sure that we adjust
1598 // the slot number to be the real global constant number.
1599 //
1600 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1601 ModuleValues[Typ])
1602 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001603 if (Constant *C = dyn_cast<Constant>(V))
1604 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001605 }
1606 }
1607 }
Chris Lattner02dce162004-12-04 05:28:27 +00001608
1609 // After we have finished parsing the constant pool, we had better not have
1610 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001611 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001612 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001613 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001614 error(utostr(ConstantFwdRefs.size()) +
1615 " unresolved constant reference exist. First one is '" +
1616 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001617 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001618 }
Chris Lattner02dce162004-12-04 05:28:27 +00001619
Reid Spencer060d25d2004-06-29 23:29:38 +00001620 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001621 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001622}
Chris Lattner00950542001-06-06 20:29:01 +00001623
Reid Spencer04cde2c2004-07-04 11:33:49 +00001624/// Parse the contents of a function. Note that this function can be
1625/// called lazily by materializeFunction
1626/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001627void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001628
1629 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001630 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001631 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001632
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001633 unsigned rWord = read_vbr_uint();
1634 unsigned LinkageID = rWord & 65535;
1635 unsigned VisibilityID = rWord >> 16;
1636 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001637 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1638 case 1: Linkage = GlobalValue::WeakLinkage; break;
1639 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1640 case 3: Linkage = GlobalValue::InternalLinkage; break;
1641 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001642 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1643 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1644 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001645 default:
Reid Spencer24399722004-07-09 22:21:33 +00001646 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001647 Linkage = GlobalValue::InternalLinkage;
1648 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001649 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001650 switch (VisibilityID) {
1651 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1652 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1653 default:
1654 error("Unknown visibility type: " + utostr(VisibilityID));
1655 Visibility = GlobalValue::DefaultVisibility;
1656 break;
1657 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001658
Reid Spencer46b002c2004-07-11 17:28:43 +00001659 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001660 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001661 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001662
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001663 // Keep track of how many basic blocks we have read in...
1664 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001665 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001666
Reid Spencer060d25d2004-06-29 23:29:38 +00001667 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001668 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001669 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001670 BufPtr OldAt = At;
1671 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001672
1673 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001674 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001675 if (!InsertedArguments) {
1676 // Insert arguments into the value table before we parse the first basic
1677 // block in the function, but after we potentially read in the
1678 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001679 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001680 InsertedArguments = true;
1681 }
1682
Reid Spencer04cde2c2004-07-04 11:33:49 +00001683 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001684 break;
1685
Reid Spencerad89bd62004-07-25 18:07:36 +00001686 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001687 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001688 break;
1689
Reid Spencerad89bd62004-07-25 18:07:36 +00001690 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001691 // Insert arguments into the value table before we parse the instruction
1692 // list for the function, but after we potentially read in the compaction
1693 // table.
1694 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001695 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001696 InsertedArguments = true;
1697 }
1698
Misha Brukman8a96c532005-04-21 21:44:41 +00001699 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001700 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001701 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001702 break;
1703 }
1704
Reid Spencer78d033e2007-01-06 07:24:44 +00001705 case BytecodeFormat::ValueSymbolTableBlockID:
1706 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1707 break;
1708
1709 case BytecodeFormat::TypeSymbolTableBlockID:
1710 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001711 break;
1712
1713 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001714 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001715 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001716 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001717 break;
1718 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001719 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001720 }
1721
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001722 // Make sure there were no references to non-existant basic blocks.
1723 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001724 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001725
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001726 ParsedBasicBlocks.clear();
1727
Chris Lattner97330cf2003-10-09 23:10:14 +00001728 // Resolve forward references. Replace any uses of a forward reference value
1729 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001730 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001731 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1732 I = ForwardReferences.begin();
1733 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001734 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001735 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001736 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001737 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001738 }
Chris Lattner00950542001-06-06 20:29:01 +00001739
Misha Brukman12c29d12003-09-22 23:38:23 +00001740 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001741 FunctionTypes.clear();
1742 CompactionTypes.clear();
1743 CompactionValues.clear();
1744 freeTable(FunctionValues);
1745
Reid Spencer04cde2c2004-07-04 11:33:49 +00001746 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001747}
1748
Reid Spencer04cde2c2004-07-04 11:33:49 +00001749/// This function parses LLVM functions lazily. It obtains the type of the
1750/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001751/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001752/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001753void BytecodeReader::ParseFunctionLazily() {
1754 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001755 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001756
Reid Spencer060d25d2004-06-29 23:29:38 +00001757 Function *Func = FunctionSignatureList.back();
1758 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001759
Reid Spencer060d25d2004-06-29 23:29:38 +00001760 // Save the information for future reading of the function
1761 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001762
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001763 // This function has a body but it's not loaded so it appears `External'.
1764 // Mark it as a `Ghost' instead to notify the users that it has a body.
1765 Func->setLinkage(GlobalValue::GhostLinkage);
1766
Reid Spencer060d25d2004-06-29 23:29:38 +00001767 // Pretend we've `parsed' this function
1768 At = BlockEnd;
1769}
Chris Lattner89e02532004-01-18 21:08:15 +00001770
Misha Brukman8a96c532005-04-21 21:44:41 +00001771/// The ParserFunction method lazily parses one function. Use this method to
1772/// casue the parser to parse a specific function in the module. Note that
1773/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001774/// ParseAllFunctionBodies.
1775/// @see ParseAllFunctionBodies
1776/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001777bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1778
Reid Spencer9b84ad12006-12-15 19:49:23 +00001779 if (setjmp(context)) {
1780 // Set caller's error message, if requested
1781 if (ErrMsg)
1782 *ErrMsg = ErrorMsg;
1783 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001784 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001785 }
Reid Spencer99655e12006-08-25 19:54:53 +00001786
Reid Spencer060d25d2004-06-29 23:29:38 +00001787 // Find {start, end} pointers and slot in the map. If not there, we're done.
1788 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001789
Reid Spencer060d25d2004-06-29 23:29:38 +00001790 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001791 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001792 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001793 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001794 }
1795
Reid Spencer060d25d2004-06-29 23:29:38 +00001796 BlockStart = At = Fi->second.Buf;
1797 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001798 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001799
1800 LazyFunctionLoadMap.erase(Fi);
1801
Reid Spencer46b002c2004-07-11 17:28:43 +00001802 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001803 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001804}
1805
Reid Spencer04cde2c2004-07-04 11:33:49 +00001806/// The ParseAllFunctionBodies method parses through all the previously
1807/// unparsed functions in the bytecode file. If you want to completely parse
1808/// a bytecode file, this method should be called after Parsebytecode because
1809/// Parsebytecode only records the locations in the bytecode file of where
1810/// the function definitions are located. This function uses that information
1811/// to materialize the functions.
1812/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001813bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001814 if (setjmp(context)) {
1815 // Set caller's error message, if requested
1816 if (ErrMsg)
1817 *ErrMsg = ErrorMsg;
1818 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001819 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001820 }
Reid Spencer99655e12006-08-25 19:54:53 +00001821
Reid Spencer060d25d2004-06-29 23:29:38 +00001822 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1823 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001824
Reid Spencer46b002c2004-07-11 17:28:43 +00001825 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001826 Function* Func = Fi->first;
1827 BlockStart = At = Fi->second.Buf;
1828 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001829 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001830 ++Fi;
1831 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001832 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001833 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001834}
Chris Lattner89e02532004-01-18 21:08:15 +00001835
Reid Spencer04cde2c2004-07-04 11:33:49 +00001836/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001837void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001838 // Read the number of types
1839 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001840 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001841}
1842
Reid Spencer04cde2c2004-07-04 11:33:49 +00001843/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001844void BytecodeReader::ParseModuleGlobalInfo() {
1845
Reid Spencer04cde2c2004-07-04 11:33:49 +00001846 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001847
Chris Lattner404cddf2005-11-12 01:33:40 +00001848 // SectionID - If a global has an explicit section specified, this map
1849 // remembers the ID until we can translate it into a string.
1850 std::map<GlobalValue*, unsigned> SectionID;
1851
Chris Lattner70cc3392001-09-10 07:58:01 +00001852 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001853 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001854 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001855 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1856 // Linkage, bit4+ = slot#
1857 unsigned SlotNo = VarType >> 5;
1858 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001859 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001860 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001861 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001862 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001863 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001864
1865 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1866 if (LinkageID == 3 && !hasInitializer) {
1867 unsigned ExtWord = read_vbr_uint();
1868 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001869 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1870 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001871 hasInitializer = ExtWord & 1;
1872 LinkageID = (ExtWord >> 1) & 7;
1873 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001874 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001875
1876 if (ExtWord & (1 << 9)) // Has a section ID.
1877 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001878 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001879
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001880 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001881 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001882 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1883 case 1: Linkage = GlobalValue::WeakLinkage; break;
1884 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1885 case 3: Linkage = GlobalValue::InternalLinkage; break;
1886 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001887 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1888 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1889 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001890 default:
Reid Spencer24399722004-07-09 22:21:33 +00001891 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001892 Linkage = GlobalValue::InternalLinkage;
1893 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001894 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001895 GlobalValue::VisibilityTypes Visibility;
1896 switch (VisibilityID) {
1897 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1898 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1899 default:
1900 error("Unknown visibility type: " + utostr(VisibilityID));
1901 Visibility = GlobalValue::DefaultVisibility;
1902 break;
1903 }
1904
Chris Lattnere3869c82003-04-16 21:16:05 +00001905 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001906 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001907 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001908
Chris Lattnere73bd452005-11-06 07:43:39 +00001909 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001910 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001911
Chris Lattner52e20b02003-03-19 20:54:26 +00001912 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001913
Chris Lattner70cc3392001-09-10 07:58:01 +00001914 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001915 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001916 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001917 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001918 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001919 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001920
Chris Lattner404cddf2005-11-12 01:33:40 +00001921 if (GlobalSectionID != 0)
1922 SectionID[GV] = GlobalSectionID;
1923
Reid Spencer060d25d2004-06-29 23:29:38 +00001924 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001925 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001926 initSlot = read_vbr_uint();
1927 GlobalInits.push_back(std::make_pair(GV, initSlot));
1928 }
1929
1930 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001931 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001932 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1933 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001934
1935 // Get next item
1936 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001937 }
1938
Chris Lattner52e20b02003-03-19 20:54:26 +00001939 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001940 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001941
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001942 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001943 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1944 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001945 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001946 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001947 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001948 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001949 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001950
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001951 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001952 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001953 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001954
Chris Lattner18549c22004-11-15 21:43:03 +00001955 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001956 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001957 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001958
Chris Lattnere73bd452005-11-06 07:43:39 +00001959 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001960
1961 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001962 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001963
Chris Lattner97fbc502004-11-15 22:38:52 +00001964 // Save this for later so we know type of lazily instantiated functions.
1965 // Note that known-external functions do not have FunctionInfo blocks, so we
1966 // do not add them to the FunctionSignatureList.
1967 if ((Flags & (1 << 4)) == 0)
1968 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001969
Chris Lattnere73bd452005-11-06 07:43:39 +00001970 // Get the calling convention from the low bits.
1971 unsigned CC = Flags & 15;
1972 unsigned Alignment = 0;
1973 if (FnSignature & (1 << 31)) { // Has extension word?
1974 unsigned ExtWord = read_vbr_uint();
1975 Alignment = (1 << (ExtWord & 31)) >> 1;
1976 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001977
1978 if (ExtWord & (1 << 10)) // Has a section ID.
1979 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001980
1981 // Parse external declaration linkage
1982 switch ((ExtWord >> 11) & 3) {
1983 case 0: break;
1984 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1985 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1986 default: assert(0 && "Unsupported external linkage");
1987 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001988 }
1989
Chris Lattner54b369e2005-11-06 07:46:13 +00001990 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001991 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001992
Reid Spencer04cde2c2004-07-04 11:33:49 +00001993 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001994
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001995 // Get the next function signature.
1996 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001997 }
1998
Misha Brukman8a96c532005-04-21 21:44:41 +00001999 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002000 // remove elements efficiently from the back of the vector.
2001 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002002
Chris Lattner404cddf2005-11-12 01:33:40 +00002003 /// SectionNames - This contains the list of section names encoded in the
2004 /// moduleinfoblock. Functions and globals with an explicit section index
2005 /// into this to get their section name.
2006 std::vector<std::string> SectionNames;
2007
Reid Spencerd798a512006-11-14 04:47:22 +00002008 // Read in the dependent library information.
2009 unsigned num_dep_libs = read_vbr_uint();
2010 std::string dep_lib;
2011 while (num_dep_libs--) {
2012 dep_lib = read_str();
2013 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002014 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00002015 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002016 }
2017
Reid Spencerd798a512006-11-14 04:47:22 +00002018 // Read target triple and place into the module.
2019 std::string triple = read_str();
2020 TheModule->setTargetTriple(triple);
2021 if (Handler)
2022 Handler->handleTargetTriple(triple);
2023
2024 if (At != BlockEnd) {
2025 // If the file has section info in it, read the section names now.
2026 unsigned NumSections = read_vbr_uint();
2027 while (NumSections--)
2028 SectionNames.push_back(read_str());
2029 }
2030
2031 // If the file has module-level inline asm, read it now.
2032 if (At != BlockEnd)
2033 TheModule->setModuleInlineAsm(read_str());
2034
Chris Lattner404cddf2005-11-12 01:33:40 +00002035 // If any globals are in specified sections, assign them now.
2036 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2037 SectionID.end(); I != E; ++I)
2038 if (I->second) {
2039 if (I->second > SectionID.size())
2040 error("SectionID out of range for global!");
2041 I->first->setSection(SectionNames[I->second-1]);
2042 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002043
Chris Lattner00950542001-06-06 20:29:01 +00002044 // This is for future proofing... in the future extra fields may be added that
2045 // we don't understand, so we transparently ignore them.
2046 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002047 At = BlockEnd;
2048
Reid Spencer04cde2c2004-07-04 11:33:49 +00002049 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002050}
2051
Reid Spencer04cde2c2004-07-04 11:33:49 +00002052/// Parse the version information and decode it by setting flags on the
2053/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002054void BytecodeReader::ParseVersionInfo() {
2055 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002056
2057 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002058 Module::Endianness Endianness;
2059 Module::PointerSize PointerSize;
2060 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2061 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2062
2063 bool hasNoEndianness = Version & 4;
2064 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002065
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002066 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002067
Reid Spencer3795ad12006-12-03 05:47:10 +00002068 // We don't provide backwards compatibility in the Reader any more. To
2069 // upgrade, the user should use llvm-upgrade.
2070 if (RevisionNum < 7)
2071 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00002072
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002073 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2074 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002075
Brian Gaekefe2102b2004-07-14 20:33:13 +00002076 TheModule->setEndianness(Endianness);
2077 TheModule->setPointerSize(PointerSize);
2078
Reid Spencer46b002c2004-07-11 17:28:43 +00002079 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002080}
2081
Reid Spencer04cde2c2004-07-04 11:33:49 +00002082/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002083void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002084 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002085
Reid Spencer060d25d2004-06-29 23:29:38 +00002086 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002087
2088 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002089 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00002090
Reid Spencer060d25d2004-06-29 23:29:38 +00002091 bool SeenModuleGlobalInfo = false;
2092 bool SeenGlobalTypePlane = false;
2093 BufPtr MyEnd = BlockEnd;
2094 while (At < MyEnd) {
2095 BufPtr OldAt = At;
2096 read_block(Type, Size);
2097
Chris Lattner00950542001-06-06 20:29:01 +00002098 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002099
Reid Spencerad89bd62004-07-25 18:07:36 +00002100 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002101 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002102 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002103
Reid Spencer5b472d92004-08-21 20:49:23 +00002104 if (Size > 0)
2105 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002106 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002107 break;
2108
Misha Brukman8a96c532005-04-21 21:44:41 +00002109 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002110 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002111 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002112 ParseModuleGlobalInfo();
2113 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002114 break;
2115
Reid Spencerad89bd62004-07-25 18:07:36 +00002116 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002117 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002118 break;
2119
Reid Spencerad89bd62004-07-25 18:07:36 +00002120 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002121 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002122 break;
Chris Lattner00950542001-06-06 20:29:01 +00002123
Reid Spencer78d033e2007-01-06 07:24:44 +00002124 case BytecodeFormat::ValueSymbolTableBlockID:
2125 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
2126 break;
2127
2128 case BytecodeFormat::TypeSymbolTableBlockID:
2129 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002130 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002131
Chris Lattner00950542001-06-06 20:29:01 +00002132 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002133 At += Size;
2134 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002135 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002136 }
Chris Lattner00950542001-06-06 20:29:01 +00002137 break;
2138 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002139 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00002140 }
2141
Chris Lattner52e20b02003-03-19 20:54:26 +00002142 // After the module constant pool has been read, we can safely initialize
2143 // global variables...
2144 while (!GlobalInits.empty()) {
2145 GlobalVariable *GV = GlobalInits.back().first;
2146 unsigned Slot = GlobalInits.back().second;
2147 GlobalInits.pop_back();
2148
2149 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002150 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002151
2152 const llvm::PointerType* GVType = GV->getType();
2153 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002154 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002155 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002156 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002157 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002158 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002159 } else
Reid Spencer24399722004-07-09 22:21:33 +00002160 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002161 }
2162
Chris Lattneraba5ff52005-05-05 20:57:00 +00002163 if (!ConstantFwdRefs.empty())
2164 error("Use of undefined constants in a module");
2165
Reid Spencer060d25d2004-06-29 23:29:38 +00002166 /// Make sure we pulled them all out. If we didn't then there's a declaration
2167 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002168 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002169 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002170}
2171
Reid Spencer04cde2c2004-07-04 11:33:49 +00002172/// This function completely parses a bytecode buffer given by the \p Buf
2173/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002174bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002175 const std::string &ModuleID,
2176 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002177
Reid Spencer233fe722006-08-22 16:09:19 +00002178 /// We handle errors by
2179 if (setjmp(context)) {
2180 // Cleanup after error
2181 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002182 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002183 delete TheModule;
2184 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002185 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002186 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002187 decompressedBlock = 0;
2188 }
Reid Spencer233fe722006-08-22 16:09:19 +00002189 // Set caller's error message, if requested
2190 if (ErrMsg)
2191 *ErrMsg = ErrorMsg;
2192 // Indicate an error occurred
2193 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002194 }
Reid Spencer233fe722006-08-22 16:09:19 +00002195
2196 RevisionNum = 0;
2197 At = MemStart = BlockStart = Buf;
2198 MemEnd = BlockEnd = Buf + Length;
2199
2200 // Create the module
2201 TheModule = new Module(ModuleID);
2202
2203 if (Handler) Handler->handleStart(TheModule, Length);
2204
2205 // Read the four bytes of the signature.
2206 unsigned Sig = read_uint();
2207
2208 // If this is a compressed file
2209 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2210
2211 // Invoke the decompression of the bytecode. Note that we have to skip the
2212 // file's magic number which is not part of the compressed block. Hence,
2213 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2214 // member for retention until BytecodeReader is destructed.
2215 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2216 (char*)Buf+4,Length-4,decompressedBlock);
2217
2218 // We must adjust the buffer pointers used by the bytecode reader to point
2219 // into the new decompressed block. After decompression, the
2220 // decompressedBlock will point to a contiguous memory area that has
2221 // the decompressed data.
2222 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2223 MemEnd = BlockEnd = Buf + decompressedLength;
2224
2225 // else if this isn't a regular (uncompressed) bytecode file, then its
2226 // and error, generate that now.
2227 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2228 error("Invalid bytecode signature: " + utohexstr(Sig));
2229 }
2230
2231 // Tell the handler we're starting a module
2232 if (Handler) Handler->handleModuleBegin(ModuleID);
2233
2234 // Get the module block and size and verify. This is handled specially
2235 // because the module block/size is always written in long format. Other
2236 // blocks are written in short format so the read_block method is used.
2237 unsigned Type, Size;
2238 Type = read_uint();
2239 Size = read_uint();
2240 if (Type != BytecodeFormat::ModuleBlockID) {
2241 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2242 + utostr(Size));
2243 }
2244
2245 // It looks like the darwin ranlib program is broken, and adds trailing
2246 // garbage to the end of some bytecode files. This hack allows the bc
2247 // reader to ignore trailing garbage on bytecode files.
2248 if (At + Size < MemEnd)
2249 MemEnd = BlockEnd = At+Size;
2250
2251 if (At + Size != MemEnd)
2252 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2253 + ", Size:" + utostr(Size));
2254
2255 // Parse the module contents
2256 this->ParseModule();
2257
2258 // Check for missing functions
2259 if (hasFunctions())
2260 error("Function expected, but bytecode stream ended!");
2261
Reid Spencer233fe722006-08-22 16:09:19 +00002262 // Tell the handler we're done with the module
2263 if (Handler)
2264 Handler->handleModuleEnd(ModuleID);
2265
2266 // Tell the handler we're finished the parse
2267 if (Handler) Handler->handleFinish();
2268
2269 return false;
2270
Chris Lattner00950542001-06-06 20:29:01 +00002271}
Reid Spencer060d25d2004-06-29 23:29:38 +00002272
2273//===----------------------------------------------------------------------===//
2274//=== Default Implementations of Handler Methods
2275//===----------------------------------------------------------------------===//
2276
2277BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002278