blob: 1ba79915e72e42470adb90a290d02fd25c7184fd [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"
Reid Spencer78d033e2007-01-06 07:24:44 +000026#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000028#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000030#include "llvm/Support/MathExtras.h"
Chris Lattner4c3d3a92007-01-31 19:56:15 +000031#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000033#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000034#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Reid Spencer46b002c2004-07-11 17:28:43 +000037namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000038 /// @brief A class for maintaining the slot number definition
39 /// as a placeholder for the actual definition for forward constants defs.
40 class ConstantPlaceHolder : public ConstantExpr {
41 ConstantPlaceHolder(); // DO NOT IMPLEMENT
42 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
43 public:
Chris Lattner61323322005-01-31 01:11:13 +000044 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000045 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000046 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000047 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000048 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000049 };
Reid Spencer46b002c2004-07-11 17:28:43 +000050}
Reid Spencer060d25d2004-06-29 23:29:38 +000051
Reid Spencer24399722004-07-09 22:21:33 +000052// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000053inline void BytecodeReader::error(const std::string& err) {
54 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
55 + itostr(At-MemStart) + ")";
Reid Spenceref9b9a72007-02-05 20:47:22 +000056 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer233fe722006-08-22 16:09:19 +000057 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;
Misha Brukman8a96c532005-04-21 21:44:41 +000088
Reid Spencer060d25d2004-06-29 23:29:38 +000089 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000090 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000091 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000092 Result |= (unsigned)((*At++) & 0x7F) << Shift;
93 Shift += 7;
94 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +000095 return Result;
96}
97
Reid Spencer04cde2c2004-07-04 11:33:49 +000098/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +000099inline uint64_t BytecodeReader::read_vbr_uint64() {
100 unsigned Shift = 0;
101 uint64_t Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +0000102
Reid Spencer060d25d2004-06-29 23:29:38 +0000103 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000104 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000105 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
107 Shift += 7;
108 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 return Result;
110}
111
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000113inline int64_t BytecodeReader::read_vbr_int64() {
114 uint64_t R = read_vbr_uint64();
115 if (R & 1) {
116 if (R != 1)
117 return -(int64_t)(R >> 1);
118 else // There is no such thing as -0 with integers. "-0" really means
119 // 0x8000000000000000.
120 return 1LL << 63;
121 } else
122 return (int64_t)(R >> 1);
123}
124
Reid Spencer04cde2c2004-07-04 11:33:49 +0000125/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000126inline std::string BytecodeReader::read_str() {
127 unsigned Size = read_vbr_uint();
128 const unsigned char *OldAt = At;
129 At += Size;
130 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000131 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000132 return std::string((char*)OldAt, Size);
133}
134
Reid Spencer04cde2c2004-07-04 11:33:49 +0000135/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000136inline void BytecodeReader::read_data(void *Ptr, void *End) {
137 unsigned char *Start = (unsigned char *)Ptr;
138 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000139 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000140 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000141 std::copy(At, At+Amount, Start);
142 At += Amount;
143}
144
Reid Spencer46b002c2004-07-11 17:28:43 +0000145/// Read a float value in little-endian order
146inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000147 /// FIXME: This isn't optimal, it has size problems on some platforms
148 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000149 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000150 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000151}
152
153/// Read a double value in little-endian order
154inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000155 /// FIXME: This isn't optimal, it has size problems on some platforms
156 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000157 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
158 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
159 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
160 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000161 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000162}
163
Reid Spencer04cde2c2004-07-04 11:33:49 +0000164/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000165inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000166 Size = read_uint(); // Read the header
167 Type = Size & 0x1F; // mask low order five bits to get type
168 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000169 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000170 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000171 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000172 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000173 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000174}
175
Reid Spencer060d25d2004-06-29 23:29:38 +0000176//===----------------------------------------------------------------------===//
177// IR Lookup Methods
178//===----------------------------------------------------------------------===//
179
Reid Spencer04cde2c2004-07-04 11:33:49 +0000180/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000181inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000182 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000183}
184
Reid Spencerd2bb8872007-01-30 19:36:46 +0000185/// Obtain a type given a typeid and account for things like function level vs
186/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000187const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000188 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000189 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000190 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000191
192 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000193 ID -= Type::FirstDerivedTyID;
194
Chris Lattner36392bc2003-10-08 21:18:57 +0000195 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000196 if (ID < ModuleTypes.size())
197 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000198
Reid Spencer46b002c2004-07-11 17:28:43 +0000199 // Nope, is it a function-level type?
200 ID -= ModuleTypes.size();
201 if (ID < FunctionTypes.size())
202 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000203
Reid Spencer46b002c2004-07-11 17:28:43 +0000204 error("Illegal type reference!");
205 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000206}
207
Reid Spencer3795ad12006-12-03 05:47:10 +0000208/// This method just saves some coding. It uses read_vbr_uint to read in a
209/// type id, errors that its not the type type, and then calls getType to
210/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000211inline const Type* BytecodeReader::readType() {
212 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000213}
214
215/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000216/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000217unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
218 if (Ty->isPrimitiveType())
219 return Ty->getTypeID();
220
Reid Spencer060d25d2004-06-29 23:29:38 +0000221 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000222 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
223 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000224
225 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000226 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000227 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000228
Chris Lattnereebac5f2005-10-03 21:26:53 +0000229 // If we don't have our cache yet, build it now.
230 if (ModuleTypeIDCache.empty()) {
231 unsigned N = 0;
232 ModuleTypeIDCache.reserve(ModuleTypes.size());
233 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
234 I != E; ++I, ++N)
235 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
236
237 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
238 }
239
240 // Binary search the cache for the entry.
241 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
242 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
243 std::make_pair(Ty, 0U));
244 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000245 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000246
247 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000248}
249
Misha Brukman8a96c532005-04-21 21:44:41 +0000250/// Retrieve a value of a given type and slot number, possibly creating
251/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000252Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000253 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000254 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000255
Reid Spencerd2bb8872007-01-30 19:36:46 +0000256 // By default, the global type id is the type id passed in
257 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000258
Reid Spencerd2bb8872007-01-30 19:36:46 +0000259 if (hasImplicitNull(GlobalTyID)) {
260 const Type *Ty = getType(type);
261 if (!isa<OpaqueType>(Ty)) {
262 if (Num == 0)
263 return Constant::getNullValue(Ty);
264 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000265 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000266 }
Chris Lattner89e02532004-01-18 21:08:15 +0000267
Reid Spencerd2bb8872007-01-30 19:36:46 +0000268 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
269 if (Num < ModuleValues[GlobalTyID]->size())
270 return ModuleValues[GlobalTyID]->getOperand(Num);
271 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner52e20b02003-03-19 20:54:26 +0000272 }
273
Misha Brukman8a96c532005-04-21 21:44:41 +0000274 if (FunctionValues.size() > type &&
275 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000276 Num < FunctionValues[type]->size())
277 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000278
Chris Lattner74734132002-08-17 22:01:27 +0000279 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000280
Reid Spencer551ccae2004-09-01 22:55:40 +0000281 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000282 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000283 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000284 if (I != ForwardReferences.end() && I->first == KeyValue)
285 return I->second; // We have already created this placeholder
286
Reid Spencer551ccae2004-09-01 22:55:40 +0000287 // If the type exists (it should)
288 if (const Type* Ty = getType(type)) {
289 // Create the place holder
290 Value *Val = new Argument(Ty);
291 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
292 return Val;
293 }
Reid Spencer233fe722006-08-22 16:09:19 +0000294 error("Can't create placeholder for value of type slot #" + utostr(type));
295 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000296}
297
Reid Spencer060d25d2004-06-29 23:29:38 +0000298
Reid Spencer04cde2c2004-07-04 11:33:49 +0000299/// Just like getValue, except that it returns a null pointer
300/// only on error. It always returns a constant (meaning that if the value is
301/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000302/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000303/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000304Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
305 if (Value *V = getValue(TypeSlot, Slot, false))
306 if (Constant *C = dyn_cast<Constant>(V))
307 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000308 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000309 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000310 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000311
Chris Lattner389bd042004-12-09 06:19:44 +0000312 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000313 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
314
315 if (I != ConstantFwdRefs.end() && I->first == Key) {
316 return I->second;
317 } else {
318 // Create a placeholder for the constant reference and
319 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000320 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000321
Reid Spencer060d25d2004-06-29 23:29:38 +0000322 // Keep track of the fact that we have a forward ref to recycle it
323 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
324 return C;
325 }
326}
327
328//===----------------------------------------------------------------------===//
329// IR Construction Methods
330//===----------------------------------------------------------------------===//
331
Reid Spencer04cde2c2004-07-04 11:33:49 +0000332/// As values are created, they are inserted into the appropriate place
333/// with this method. The ValueTable argument must be one of ModuleValues
334/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000335unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000336 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000337 if (ValueTab.size() <= type)
338 ValueTab.resize(type+1);
339
340 if (!ValueTab[type]) ValueTab[type] = new ValueList();
341
342 ValueTab[type]->push_back(Val);
343
Chris Lattneraba5ff52005-05-05 20:57:00 +0000344 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000345 return ValueTab[type]->size()-1 + HasOffset;
346}
347
Reid Spencer04cde2c2004-07-04 11:33:49 +0000348/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000349void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000350 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000351 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000352 for (FunctionType::param_iterator It = FT->param_begin();
353 It != FT->param_end(); ++It, ++AI)
354 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
355}
356
357//===----------------------------------------------------------------------===//
358// Bytecode Parsing Methods
359//===----------------------------------------------------------------------===//
360
Reid Spencer04cde2c2004-07-04 11:33:49 +0000361/// This method parses a single instruction. The instruction is
362/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000363/// the instruction are provided in the \p Oprnds vector.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000364void BytecodeReader::ParseInstruction(SmallVector<unsigned, 8> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000365 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000366 BufPtr SaveAt = At;
367
368 // Clear instruction data
369 Oprnds.clear();
370 unsigned iType = 0;
371 unsigned Opcode = 0;
372 unsigned Op = read_uint();
373
374 // bits Instruction format: Common to all formats
375 // --------------------------
376 // 01-00: Opcode type, fixed to 1.
377 // 07-02: Opcode
378 Opcode = (Op >> 2) & 63;
379 Oprnds.resize((Op >> 0) & 03);
380
381 // Extract the operands
382 switch (Oprnds.size()) {
383 case 1:
384 // bits Instruction format:
385 // --------------------------
386 // 19-08: Resulting type plane
387 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
388 //
389 iType = (Op >> 8) & 4095;
390 Oprnds[0] = (Op >> 20) & 4095;
391 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
392 Oprnds.resize(0);
393 break;
394 case 2:
395 // bits Instruction format:
396 // --------------------------
397 // 15-08: Resulting type plane
398 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000399 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000400 //
401 iType = (Op >> 8) & 255;
402 Oprnds[0] = (Op >> 16) & 255;
403 Oprnds[1] = (Op >> 24) & 255;
404 break;
405 case 3:
406 // bits Instruction format:
407 // --------------------------
408 // 13-08: Resulting type plane
409 // 19-14: Operand #1
410 // 25-20: Operand #2
411 // 31-26: Operand #3
412 //
413 iType = (Op >> 8) & 63;
414 Oprnds[0] = (Op >> 14) & 63;
415 Oprnds[1] = (Op >> 20) & 63;
416 Oprnds[2] = (Op >> 26) & 63;
417 break;
418 case 0:
419 At -= 4; // Hrm, try this again...
420 Opcode = read_vbr_uint();
421 Opcode >>= 2;
422 iType = read_vbr_uint();
423
424 unsigned NumOprnds = read_vbr_uint();
425 Oprnds.resize(NumOprnds);
426
427 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000428 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000429
430 for (unsigned i = 0; i != NumOprnds; ++i)
431 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000432 break;
433 }
434
Reid Spencerd798a512006-11-14 04:47:22 +0000435 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000436
Reid Spencer1628cec2006-10-26 06:15:43 +0000437 // Make the necessary adjustments for dealing with backwards compatibility
438 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000439 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000440
Reid Spencer3795ad12006-12-03 05:47:10 +0000441 // First, handle the easy binary operators case
442 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000443 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000444 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
445 getValue(iType, Oprnds[0]),
446 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000447 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000448 // Indicate that we don't think this is a call instruction (yet).
449 // Process based on the Opcode read
450 switch (Opcode) {
451 default: // There was an error, this shouldn't happen.
452 if (Result == 0)
453 error("Illegal instruction read!");
454 break;
455 case Instruction::VAArg:
456 if (Oprnds.size() != 2)
457 error("Invalid VAArg instruction!");
458 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000459 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000460 break;
461 case Instruction::ExtractElement: {
462 if (Oprnds.size() != 2)
463 error("Invalid extractelement instruction!");
464 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000465 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000466
Reid Spencer1628cec2006-10-26 06:15:43 +0000467 if (!ExtractElementInst::isValidOperands(V1, V2))
468 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000469
Reid Spencer1628cec2006-10-26 06:15:43 +0000470 Result = new ExtractElementInst(V1, V2);
471 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000472 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000473 case Instruction::InsertElement: {
474 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
475 if (!PackedTy || Oprnds.size() != 3)
476 error("Invalid insertelement instruction!");
477
478 Value *V1 = getValue(iType, Oprnds[0]);
479 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000480 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000481
482 if (!InsertElementInst::isValidOperands(V1, V2, V3))
483 error("Invalid insertelement instruction!");
484 Result = new InsertElementInst(V1, V2, V3);
485 break;
486 }
487 case Instruction::ShuffleVector: {
488 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
489 if (!PackedTy || Oprnds.size() != 3)
490 error("Invalid shufflevector instruction!");
491 Value *V1 = getValue(iType, Oprnds[0]);
492 Value *V2 = getValue(iType, Oprnds[1]);
493 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000494 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000495 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
496 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
497 error("Invalid shufflevector instruction!");
498 Result = new ShuffleVectorInst(V1, V2, V3);
499 break;
500 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000501 case Instruction::Trunc:
502 if (Oprnds.size() != 2)
503 error("Invalid cast instruction!");
504 Result = new TruncInst(getValue(iType, Oprnds[0]),
505 getType(Oprnds[1]));
506 break;
507 case Instruction::ZExt:
508 if (Oprnds.size() != 2)
509 error("Invalid cast instruction!");
510 Result = new ZExtInst(getValue(iType, Oprnds[0]),
511 getType(Oprnds[1]));
512 break;
513 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000514 if (Oprnds.size() != 2)
515 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000516 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000517 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000518 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000519 case Instruction::FPTrunc:
520 if (Oprnds.size() != 2)
521 error("Invalid cast instruction!");
522 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
523 getType(Oprnds[1]));
524 break;
525 case Instruction::FPExt:
526 if (Oprnds.size() != 2)
527 error("Invalid cast instruction!");
528 Result = new FPExtInst(getValue(iType, Oprnds[0]),
529 getType(Oprnds[1]));
530 break;
531 case Instruction::UIToFP:
532 if (Oprnds.size() != 2)
533 error("Invalid cast instruction!");
534 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
535 getType(Oprnds[1]));
536 break;
537 case Instruction::SIToFP:
538 if (Oprnds.size() != 2)
539 error("Invalid cast instruction!");
540 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
541 getType(Oprnds[1]));
542 break;
543 case Instruction::FPToUI:
544 if (Oprnds.size() != 2)
545 error("Invalid cast instruction!");
546 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
547 getType(Oprnds[1]));
548 break;
549 case Instruction::FPToSI:
550 if (Oprnds.size() != 2)
551 error("Invalid cast instruction!");
552 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
553 getType(Oprnds[1]));
554 break;
555 case Instruction::IntToPtr:
556 if (Oprnds.size() != 2)
557 error("Invalid cast instruction!");
558 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
559 getType(Oprnds[1]));
560 break;
561 case Instruction::PtrToInt:
562 if (Oprnds.size() != 2)
563 error("Invalid cast instruction!");
564 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
565 getType(Oprnds[1]));
566 break;
567 case Instruction::BitCast:
568 if (Oprnds.size() != 2)
569 error("Invalid cast instruction!");
570 Result = new BitCastInst(getValue(iType, Oprnds[0]),
571 getType(Oprnds[1]));
572 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000573 case Instruction::Select:
574 if (Oprnds.size() != 3)
575 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000576 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000577 getValue(iType, Oprnds[1]),
578 getValue(iType, Oprnds[2]));
579 break;
580 case Instruction::PHI: {
581 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
582 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000583
Reid Spencer1628cec2006-10-26 06:15:43 +0000584 PHINode *PN = new PHINode(InstTy);
585 PN->reserveOperandSpace(Oprnds.size());
586 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
587 PN->addIncoming(
588 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
589 Result = PN;
590 break;
591 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000592 case Instruction::ICmp:
593 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000594 if (Oprnds.size() != 3)
595 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000596 // These instructions encode the comparison predicate as the 3rd operand.
597 Result = CmpInst::create(Instruction::OtherOps(Opcode),
598 static_cast<unsigned short>(Oprnds[2]),
599 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
600 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000601 case Instruction::Ret:
602 if (Oprnds.size() == 0)
603 Result = new ReturnInst();
604 else if (Oprnds.size() == 1)
605 Result = new ReturnInst(getValue(iType, Oprnds[0]));
606 else
607 error("Unrecognized instruction!");
608 break;
609
610 case Instruction::Br:
611 if (Oprnds.size() == 1)
612 Result = new BranchInst(getBasicBlock(Oprnds[0]));
613 else if (Oprnds.size() == 3)
614 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000615 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000616 else
617 error("Invalid number of operands for a 'br' instruction!");
618 break;
619 case Instruction::Switch: {
620 if (Oprnds.size() & 1)
621 error("Switch statement with odd number of arguments!");
622
623 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
624 getBasicBlock(Oprnds[1]),
625 Oprnds.size()/2-1);
626 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
627 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
628 getBasicBlock(Oprnds[i+1]));
629 Result = I;
630 break;
631 }
632 case 58: // Call with extra operand for calling conv
633 case 59: // tail call, Fast CC
634 case 60: // normal call, Fast CC
635 case 61: // tail call, C Calling Conv
636 case Instruction::Call: { // Normal Call, C Calling Convention
637 if (Oprnds.size() == 0)
638 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000639 Value *F = getValue(iType, Oprnds[0]);
640
641 unsigned CallingConv = CallingConv::C;
642 bool isTailCall = false;
643
644 if (Opcode == 61 || Opcode == 59)
645 isTailCall = true;
646
647 if (Opcode == 58) {
648 isTailCall = Oprnds.back() & 1;
649 CallingConv = Oprnds.back() >> 1;
650 Oprnds.pop_back();
651 } else if (Opcode == 59 || Opcode == 60) {
652 CallingConv = CallingConv::Fast;
653 }
654
655 // Check to make sure we have a pointer to function type
656 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
657 if (PTy == 0) error("Call to non function pointer value!");
658 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
659 if (FTy == 0) error("Call to non function pointer value!");
660
661 std::vector<Value *> Params;
662 if (!FTy->isVarArg()) {
663 FunctionType::param_iterator It = FTy->param_begin();
664
665 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
666 if (It == FTy->param_end())
667 error("Invalid call instruction!");
668 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
669 }
670 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000671 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000672 } else {
673 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
674
675 unsigned FirstVariableOperand;
676 if (Oprnds.size() < FTy->getNumParams())
677 error("Call instruction missing operands!");
678
679 // Read all of the fixed arguments
680 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
681 Params.push_back(
682 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
683
684 FirstVariableOperand = FTy->getNumParams();
685
686 if ((Oprnds.size()-FirstVariableOperand) & 1)
687 error("Invalid call instruction!"); // Must be pairs of type/value
688
689 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
690 i != e; i += 2)
691 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000692 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000693
Reid Spencer1628cec2006-10-26 06:15:43 +0000694 Result = new CallInst(F, Params);
695 if (isTailCall) cast<CallInst>(Result)->setTailCall();
696 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
697 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000698 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000699 case Instruction::Invoke: { // Invoke C CC
700 if (Oprnds.size() < 3)
701 error("Invalid invoke instruction!");
702 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000703
Reid Spencer1628cec2006-10-26 06:15:43 +0000704 // Check to make sure we have a pointer to function type
705 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
706 if (PTy == 0)
707 error("Invoke to non function pointer value!");
708 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
709 if (FTy == 0)
710 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000711
Reid Spencer1628cec2006-10-26 06:15:43 +0000712 std::vector<Value *> Params;
713 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000714 unsigned CallingConv = Oprnds.back();
715 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000716
Reid Spencer1628cec2006-10-26 06:15:43 +0000717 if (!FTy->isVarArg()) {
718 Normal = getBasicBlock(Oprnds[1]);
719 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000720
Reid Spencer1628cec2006-10-26 06:15:43 +0000721 FunctionType::param_iterator It = FTy->param_begin();
722 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
723 if (It == FTy->param_end())
724 error("Invalid invoke instruction!");
725 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
726 }
727 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000728 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000729 } else {
730 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
731
732 Normal = getBasicBlock(Oprnds[0]);
733 Except = getBasicBlock(Oprnds[1]);
734
735 unsigned FirstVariableArgument = FTy->getNumParams()+2;
736 for (unsigned i = 2; i != FirstVariableArgument; ++i)
737 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
738 Oprnds[i]));
739
740 // Must be type/value pairs. If not, error out.
741 if (Oprnds.size()-FirstVariableArgument & 1)
742 error("Invalid invoke instruction!");
743
744 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
745 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000746 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000747
Reid Spencer1628cec2006-10-26 06:15:43 +0000748 Result = new InvokeInst(F, Normal, Except, Params);
749 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
750 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000751 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000752 case Instruction::Malloc: {
753 unsigned Align = 0;
754 if (Oprnds.size() == 2)
755 Align = (1 << Oprnds[1]) >> 1;
756 else if (Oprnds.size() > 2)
757 error("Invalid malloc instruction!");
758 if (!isa<PointerType>(InstTy))
759 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000760
Reid Spencer1628cec2006-10-26 06:15:43 +0000761 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000762 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000763 break;
764 }
765 case Instruction::Alloca: {
766 unsigned Align = 0;
767 if (Oprnds.size() == 2)
768 Align = (1 << Oprnds[1]) >> 1;
769 else if (Oprnds.size() > 2)
770 error("Invalid alloca instruction!");
771 if (!isa<PointerType>(InstTy))
772 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000773
Reid Spencer1628cec2006-10-26 06:15:43 +0000774 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000775 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000776 break;
777 }
778 case Instruction::Free:
779 if (!isa<PointerType>(InstTy))
780 error("Invalid free instruction!");
781 Result = new FreeInst(getValue(iType, Oprnds[0]));
782 break;
783 case Instruction::GetElementPtr: {
784 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000785 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000786
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000787 SmallVector<Value*, 8> Idx;
Reid Spencer1628cec2006-10-26 06:15:43 +0000788
789 const Type *NextTy = InstTy;
790 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
791 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
792 if (!TopTy)
793 error("Invalid getelementptr instruction!");
794
795 unsigned ValIdx = Oprnds[i];
796 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000797 // Struct indices are always uints, sequential type indices can be
798 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000799 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000800 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000801 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000802 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000803 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000804 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000805 case 0: IdxTy = Int32TySlot; break;
806 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000807 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000808 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000809 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000810 Idx.push_back(getValue(IdxTy, ValIdx));
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000811 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
812 true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000813 }
814
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000815 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
816 &Idx[0], Idx.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000817 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000818 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000819 case 62: // volatile load
820 case Instruction::Load:
821 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
822 error("Invalid load instruction!");
823 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
824 break;
825 case 63: // volatile store
826 case Instruction::Store: {
827 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
828 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000829
Reid Spencer1628cec2006-10-26 06:15:43 +0000830 Value *Ptr = getValue(iType, Oprnds[1]);
831 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
832 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
833 Opcode == 63);
834 break;
835 }
836 case Instruction::Unwind:
837 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
838 Result = new UnwindInst();
839 break;
840 case Instruction::Unreachable:
841 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
842 Result = new UnreachableInst();
843 break;
844 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000845 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000846
Reid Spencere1e96c02006-01-19 07:02:16 +0000847 BB->getInstList().push_back(Result);
848
Reid Spencer060d25d2004-06-29 23:29:38 +0000849 unsigned TypeSlot;
850 if (Result->getType() == InstTy)
851 TypeSlot = iType;
852 else
853 TypeSlot = getTypeSlot(Result->getType());
854
Reid Spenceref9b9a72007-02-05 20:47:22 +0000855 // We have enough info to inform the handler now.
856 if (Handler)
Chris Lattner63cf59e2007-02-07 05:08:39 +0000857 Handler->handleInstruction(Opcode, InstTy, &Oprnds[0], Oprnds.size(),
858 Result, At-SaveAt);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000859
Reid Spencer060d25d2004-06-29 23:29:38 +0000860 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000861}
862
Reid Spencer04cde2c2004-07-04 11:33:49 +0000863/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000864/// This works together with ParseInstructionList to handle these forward
865/// references in a clean manner. This function is used when constructing
866/// phi, br, switch, and other instructions that reference basic blocks.
867/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000868BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000869 // Make sure there is room in the table...
870 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
871
Reid Spencerd798a512006-11-14 04:47:22 +0000872 // First check to see if this is a backwards reference, i.e. this block
873 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000874 // been created.
875 if (ParsedBasicBlocks[ID])
876 return ParsedBasicBlocks[ID];
877
878 // Otherwise, the basic block has not yet been created. Do so and add it to
879 // the ParsedBasicBlocks list.
880 return ParsedBasicBlocks[ID] = new BasicBlock();
881}
882
Reid Spencer04cde2c2004-07-04 11:33:49 +0000883/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000884/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000885/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000886/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000887unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000888 unsigned BlockNo = 0;
Chris Lattner63cf59e2007-02-07 05:08:39 +0000889 SmallVector<unsigned, 8> Args;
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000890
Reid Spencer46b002c2004-07-11 17:28:43 +0000891 while (moreInBlock()) {
892 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000893 BasicBlock *BB;
894 if (ParsedBasicBlocks.size() == BlockNo)
895 ParsedBasicBlocks.push_back(BB = new BasicBlock());
896 else if (ParsedBasicBlocks[BlockNo] == 0)
897 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
898 else
899 BB = ParsedBasicBlocks[BlockNo];
900 ++BlockNo;
901 F->getBasicBlockList().push_back(BB);
902
903 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000904 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000905 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000906
907 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000908 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000909
Reid Spencer46b002c2004-07-11 17:28:43 +0000910 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000911 }
912
913 return BlockNo;
914}
915
Reid Spencer78d033e2007-01-06 07:24:44 +0000916/// Parse a type symbol table.
917void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
918 // Type Symtab block header: [num entries]
919 unsigned NumEntries = read_vbr_uint();
920 for (unsigned i = 0; i < NumEntries; ++i) {
921 // Symtab entry: [type slot #][name]
922 unsigned slot = read_vbr_uint();
923 std::string Name = read_str();
924 const Type* T = getType(slot);
925 TST->insert(Name, T);
926 }
927}
928
929/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000930/// level symbol tables. For function level symbol tables, the CurrentFunction
931/// parameter must be non-zero and the ST parameter must correspond to
932/// CurrentFunction's symbol table. For Module level symbol tables, the
933/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000934void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000935 ValueSymbolTable *VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000936
Reid Spenceref9b9a72007-02-05 20:47:22 +0000937 if (Handler) Handler->handleValueSymbolTableBegin(CurrentFunction,VST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000938
Chris Lattner39cacce2003-10-10 05:43:47 +0000939 // Allow efficient basic block lookup by number.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000940 SmallVector<BasicBlock*, 32> BBMap;
Chris Lattner39cacce2003-10-10 05:43:47 +0000941 if (CurrentFunction)
942 for (Function::iterator I = CurrentFunction->begin(),
943 E = CurrentFunction->end(); I != E; ++I)
944 BBMap.push_back(I);
945
Reid Spencer46b002c2004-07-11 17:28:43 +0000946 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000947 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000948 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000949 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000950
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000951 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000952 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000953 unsigned slot = read_vbr_uint();
954 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +0000955 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000956 if (Typ == LabelTySlot) {
Reid Spencerd798a512006-11-14 04:47:22 +0000957 if (slot < BBMap.size())
958 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +0000959 } else {
Reid Spencerd798a512006-11-14 04:47:22 +0000960 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +0000961 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000962 if (Handler) Handler->handleSymbolTableValue(Typ, slot, Name);
Reid Spencerd798a512006-11-14 04:47:22 +0000963 if (V == 0)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000964 error("Failed value look-up for name '" + Name + "', type #" +
965 utostr(Typ) + " slot #" + utostr(slot));
Reid Spencerd798a512006-11-14 04:47:22 +0000966 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +0000967 }
968 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000969 checkPastBlockEnd("Symbol Table");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000970 if (Handler) Handler->handleValueSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000971}
972
Reid Spencer46b002c2004-07-11 17:28:43 +0000973// Parse a single type. The typeid is read in first. If its a primitive type
974// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +0000975// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +0000976// definition.
977const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +0000978 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000979 const Type *Result = 0;
980 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
981 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +0000982
Reid Spencer060d25d2004-06-29 23:29:38 +0000983 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000984 case Type::IntegerTyID: {
985 unsigned NumBits = read_vbr_uint();
986 Result = IntegerType::get(NumBits);
987 break;
988 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000989 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +0000990 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +0000991 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000992
993 unsigned NumParams = read_vbr_uint();
994
995 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +0000996 std::vector<FunctionType::ParameterAttributes> Attrs;
997 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
998 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +0000999 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001000 if (Params.back() != Type::VoidTy)
1001 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1002 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001003
1004 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1005 if (isVarArg) Params.pop_back();
1006
Reid Spencer88cfda22006-12-31 05:44:24 +00001007 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001008 break;
1009 }
1010 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001011 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001012 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001013 Result = ArrayType::get(ElementType, NumElements);
1014 break;
1015 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001016 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001017 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001018 unsigned NumElements = read_vbr_uint();
1019 Result = PackedType::get(ElementType, NumElements);
1020 break;
1021 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001022 case Type::StructTyID: {
1023 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001024 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001025 while (Typ) { // List is terminated by void/0 typeid
1026 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001027 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001028 }
1029
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001030 Result = StructType::get(Elements, false);
1031 break;
1032 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001033 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001034 std::vector<const Type*> Elements;
1035 unsigned Typ = read_vbr_uint();
1036 while (Typ) { // List is terminated by void/0 typeid
1037 Elements.push_back(getType(Typ));
1038 Typ = read_vbr_uint();
1039 }
1040
1041 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001042 break;
1043 }
1044 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001045 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001046 break;
1047 }
1048
1049 case Type::OpaqueTyID: {
1050 Result = OpaqueType::get();
1051 break;
1052 }
1053
1054 default:
Reid Spencer24399722004-07-09 22:21:33 +00001055 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001056 break;
1057 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001058 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001059 return Result;
1060}
1061
Reid Spencer5b472d92004-08-21 20:49:23 +00001062// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001063// types. We know that recursive types will only reference the current slab of
1064// values in the type plane, but they can forward reference types before they
1065// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1066// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1067// this ugly problem, we pessimistically insert an opaque type for each type we
1068// are about to read. This means that forward references will resolve to
1069// something and when we reread the type later, we can replace the opaque type
1070// with a new resolved concrete type.
1071//
Reid Spencer46b002c2004-07-11 17:28:43 +00001072void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001073 assert(Tab.size() == 0 && "should not have read type constants in before!");
1074
1075 // Insert a bunch of opaque types to be resolved later...
1076 Tab.reserve(NumEntries);
1077 for (unsigned i = 0; i != NumEntries; ++i)
1078 Tab.push_back(OpaqueType::get());
1079
Misha Brukman8a96c532005-04-21 21:44:41 +00001080 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001081 Handler->handleTypeList(NumEntries);
1082
Chris Lattnereebac5f2005-10-03 21:26:53 +00001083 // If we are about to resolve types, make sure the type cache is clear.
1084 if (NumEntries)
1085 ModuleTypeIDCache.clear();
1086
Reid Spencer060d25d2004-06-29 23:29:38 +00001087 // Loop through reading all of the types. Forward types will make use of the
1088 // opaque types just inserted.
1089 //
1090 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001091 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001092 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001093 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001094 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001095
Misha Brukman8a96c532005-04-21 21:44:41 +00001096 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001097 // the opaque type we previously inserted with the new concrete value. This
1098 // approach helps with forward references to types. The refinement from the
1099 // abstract (opaque) type to the new type causes all uses of the abstract
1100 // type to use the concrete type (NewTy). This will also cause the opaque
1101 // type to be deleted.
1102 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1103
1104 // This should have replaced the old opaque type with the new type in the
1105 // value table... or with a preexisting type that was already in the system.
1106 // Let's just make sure it did.
1107 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1108 }
1109}
1110
Reid Spencer04cde2c2004-07-04 11:33:49 +00001111/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001112Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 // We must check for a ConstantExpr before switching by type because
1114 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001115 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001116 // 0 if not expr; numArgs if is expr
1117 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001118
Reid Spencer060d25d2004-06-29 23:29:38 +00001119 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001120 // 'undef' is encoded with 'exprnumargs' == 1.
1121 if (isExprNumArgs == 1)
1122 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001123
Reid Spencerd798a512006-11-14 04:47:22 +00001124 // Inline asm is encoded with exprnumargs == ~0U.
1125 if (isExprNumArgs == ~0U) {
1126 std::string AsmStr = read_str();
1127 std::string ConstraintStr = read_str();
1128 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001129
Reid Spencerd798a512006-11-14 04:47:22 +00001130 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1131 const FunctionType *FTy =
1132 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1133
1134 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1135 error("Invalid constraints for inline asm");
1136 if (Flags & ~1U)
1137 error("Invalid flags for inline asm");
1138 bool HasSideEffects = Flags & 1;
1139 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001140 }
Reid Spencerd798a512006-11-14 04:47:22 +00001141
1142 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001143
Reid Spencer060d25d2004-06-29 23:29:38 +00001144 // FIXME: Encoding of constant exprs could be much more compact!
Chris Lattner670ccfe2007-02-07 05:15:28 +00001145 SmallVector<Constant*, 8> ArgVec;
Reid Spencer060d25d2004-06-29 23:29:38 +00001146 ArgVec.reserve(isExprNumArgs);
1147 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001148
Reid Spencer060d25d2004-06-29 23:29:38 +00001149 // Read the slot number and types of each of the arguments
1150 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1151 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001152 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001153
Reid Spencer060d25d2004-06-29 23:29:38 +00001154 // Get the arg value from its slot if it exists, otherwise a placeholder
1155 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1156 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001157
Reid Spencer060d25d2004-06-29 23:29:38 +00001158 // Construct a ConstantExpr of the appropriate kind
1159 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001160 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001161 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001162
Reid Spencera77fa7e2006-12-11 23:20:20 +00001163 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1164 getType(TypeID));
Chris Lattner63cf59e2007-02-07 05:08:39 +00001165 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1166 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001167 return Result;
1168 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
Chris Lattnere0135402007-01-31 04:43:46 +00001169 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], &ArgVec[1],
1170 ArgVec.size()-1);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001171 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1172 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001173 return Result;
1174 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001175 if (ArgVec.size() != 3)
1176 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001177 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001178 ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001179 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1180 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001181 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001182 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001183 if (ArgVec.size() != 2 ||
1184 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1185 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001186 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001187 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1188 ArgVec.size(), Result);
Robert Bocchinofee31b32006-01-10 19:04:39 +00001189 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001190 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001191 if (ArgVec.size() != 3 ||
1192 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1193 error("Invalid insertelement constand expr arguments");
1194
1195 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001196 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001197 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1198 ArgVec.size(), Result);
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001199 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001200 } else if (Opcode == Instruction::ShuffleVector) {
1201 if (ArgVec.size() != 3 ||
1202 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001203 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001204 Constant *Result =
1205 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001206 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1207 ArgVec.size(), Result);
Chris Lattner30b44b62006-04-08 01:17:59 +00001208 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001209 } else if (Opcode == Instruction::ICmp) {
1210 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001211 error("Invalid ICmp constant expr arguments.");
1212 unsigned predicate = read_vbr_uint();
1213 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001214 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1215 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001216 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001217 } else if (Opcode == Instruction::FCmp) {
1218 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001219 error("Invalid FCmp constant expr arguments.");
1220 unsigned predicate = read_vbr_uint();
1221 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001222 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1223 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001224 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001225 } else { // All other 2-operand expressions
1226 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001227 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1228 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001229 return Result;
1230 }
1231 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001232
Reid Spencer060d25d2004-06-29 23:29:38 +00001233 // Ok, not an ConstantExpr. We now know how to read the given type...
1234 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001235 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001236 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001237 case Type::IntegerTyID: {
1238 const IntegerType *IT = cast<IntegerType>(Ty);
1239 if (IT->getBitWidth() <= 32) {
1240 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001241 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1242 error("Integer value read is invalid for type.");
1243 Result = ConstantInt::get(IT, Val);
1244 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001245 } else if (IT->getBitWidth() <= 64) {
1246 uint64_t Val = read_vbr_uint64();
1247 if (!ConstantInt::isValueValidForType(Ty, Val))
1248 error("Invalid constant integer read.");
1249 Result = ConstantInt::get(IT, Val);
1250 if (Handler) Handler->handleConstantValue(Result);
1251 } else
1252 assert("Integer types > 64 bits not supported");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001253 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001254 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001255 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001256 float Val;
1257 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001258 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001259 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001260 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001261 }
1262
1263 case Type::DoubleTyID: {
1264 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001265 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001266 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001267 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001268 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001269 }
1270
Reid Spencer060d25d2004-06-29 23:29:38 +00001271 case Type::ArrayTyID: {
1272 const ArrayType *AT = cast<ArrayType>(Ty);
1273 unsigned NumElements = AT->getNumElements();
1274 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1275 std::vector<Constant*> Elements;
1276 Elements.reserve(NumElements);
1277 while (NumElements--) // Read all of the elements of the constant.
1278 Elements.push_back(getConstantValue(TypeSlot,
1279 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001280 Result = ConstantArray::get(AT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001281 if (Handler) Handler->handleConstantArray(AT, &Elements[0], Elements.size(),
1282 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001283 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001284 }
1285
1286 case Type::StructTyID: {
1287 const StructType *ST = cast<StructType>(Ty);
1288
1289 std::vector<Constant *> Elements;
1290 Elements.reserve(ST->getNumElements());
1291 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1292 Elements.push_back(getConstantValue(ST->getElementType(i),
1293 read_vbr_uint()));
1294
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001295 Result = ConstantStruct::get(ST, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001296 if (Handler) Handler->handleConstantStruct(ST, &Elements[0],Elements.size(),
1297 Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001298 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001299 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001300
Brian Gaeke715c90b2004-08-20 06:00:58 +00001301 case Type::PackedTyID: {
1302 const PackedType *PT = cast<PackedType>(Ty);
1303 unsigned NumElements = PT->getNumElements();
1304 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1305 std::vector<Constant*> Elements;
1306 Elements.reserve(NumElements);
1307 while (NumElements--) // Read all of the elements of the constant.
1308 Elements.push_back(getConstantValue(TypeSlot,
1309 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001310 Result = ConstantPacked::get(PT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001311 if (Handler) Handler->handleConstantPacked(PT, &Elements[0],Elements.size(),
1312 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001313 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001314 }
1315
Chris Lattner638c3812004-11-19 16:24:05 +00001316 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001317 const PointerType *PT = cast<PointerType>(Ty);
1318 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001319
Reid Spencer060d25d2004-06-29 23:29:38 +00001320 // Check to see if we have already read this global variable...
1321 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001322 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001323 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1324 if (!GV) error("GlobalValue not in ValueTable!");
1325 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1326 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001327 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001328 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001329 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001330 }
1331
1332 default:
Reid Spencer24399722004-07-09 22:21:33 +00001333 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001334 Ty->getDescription());
1335 break;
1336 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001337
1338 // Check that we didn't read a null constant if they are implicit for this
1339 // type plane. Do not do this check for constantexprs, as they may be folded
1340 // to a null value in a way that isn't predicted when a .bc file is initially
1341 // produced.
1342 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1343 !hasImplicitNull(TypeID) &&
1344 "Cannot read null values from bytecode!");
1345 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001346}
1347
Misha Brukman8a96c532005-04-21 21:44:41 +00001348/// Resolve references for constants. This function resolves the forward
1349/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001350/// replaceAllUsesWith method of Value class to substitute the placeholder
1351/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001352void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1353 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001354 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001355 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001356 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001357
Chris Lattner29b789b2003-11-19 17:27:18 +00001358 Value *PH = I->second; // Get the placeholder...
1359 PH->replaceAllUsesWith(NewV);
1360 delete PH; // Delete the old placeholder
1361 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001362}
1363
Reid Spencer04cde2c2004-07-04 11:33:49 +00001364/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001365void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1366 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001367 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001368 const Type *Ty = getType(Typ);
1369 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001370 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001371
Reid Spencer060d25d2004-06-29 23:29:38 +00001372 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001373 if (ATy->getElementType() != Type::Int8Ty &&
1374 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001375 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001376
Reid Spencer060d25d2004-06-29 23:29:38 +00001377 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001378 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001379 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001380
Reid Spencer060d25d2004-06-29 23:29:38 +00001381 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001382 const Type* ElemType = ATy->getElementType();
1383 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1384 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001385
Reid Spencer060d25d2004-06-29 23:29:38 +00001386 // Create the constant, inserting it as needed.
1387 Constant *C = ConstantArray::get(ATy, Elements);
1388 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001389 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001390 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001391 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001392}
1393
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001395void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001396 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001397 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001398 if (Handler) Handler->handleGlobalConstantsBegin();
1399
1400 /// In LLVM 1.3 Type does not derive from Value so the types
1401 /// do not occupy a plane. Consequently, we read the types
1402 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001403 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001404 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001405 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001406 }
1407
Reid Spencer46b002c2004-07-11 17:28:43 +00001408 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001410 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001411
Reid Spencerd798a512006-11-14 04:47:22 +00001412 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001413 /// Use of Type::VoidTyID is a misnomer. It actually means
1414 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001415 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1416 ParseStringConstants(NumEntries, Tab);
1417 } else {
1418 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001419 Value *V = ParseConstantPoolValue(Typ);
1420 assert(V && "ParseConstantPoolValue returned NULL!");
1421 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001422
Reid Spencer060d25d2004-06-29 23:29:38 +00001423 // If we are reading a function constant table, make sure that we adjust
1424 // the slot number to be the real global constant number.
1425 //
1426 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1427 ModuleValues[Typ])
1428 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001429 if (Constant *C = dyn_cast<Constant>(V))
1430 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001431 }
1432 }
1433 }
Chris Lattner02dce162004-12-04 05:28:27 +00001434
1435 // After we have finished parsing the constant pool, we had better not have
1436 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001437 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001438 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001439 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001440 error(utostr(ConstantFwdRefs.size()) +
1441 " unresolved constant reference exist. First one is '" +
1442 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001443 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001444 }
Chris Lattner02dce162004-12-04 05:28:27 +00001445
Reid Spencer060d25d2004-06-29 23:29:38 +00001446 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001447 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001448}
Chris Lattner00950542001-06-06 20:29:01 +00001449
Reid Spencer04cde2c2004-07-04 11:33:49 +00001450/// Parse the contents of a function. Note that this function can be
1451/// called lazily by materializeFunction
1452/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001453void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001454
1455 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001456 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001457 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001458
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001459 unsigned rWord = read_vbr_uint();
1460 unsigned LinkageID = rWord & 65535;
1461 unsigned VisibilityID = rWord >> 16;
1462 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001463 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1464 case 1: Linkage = GlobalValue::WeakLinkage; break;
1465 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1466 case 3: Linkage = GlobalValue::InternalLinkage; break;
1467 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001468 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1469 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1470 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001471 default:
Reid Spencer24399722004-07-09 22:21:33 +00001472 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001473 Linkage = GlobalValue::InternalLinkage;
1474 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001475 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001476 switch (VisibilityID) {
1477 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1478 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1479 default:
1480 error("Unknown visibility type: " + utostr(VisibilityID));
1481 Visibility = GlobalValue::DefaultVisibility;
1482 break;
1483 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001484
Reid Spencer46b002c2004-07-11 17:28:43 +00001485 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001486 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001487 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001488
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001489 // Keep track of how many basic blocks we have read in...
1490 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001491 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001492
Reid Spencer060d25d2004-06-29 23:29:38 +00001493 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001494 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001495 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001496 BufPtr OldAt = At;
1497 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001498
1499 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001500 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001501 if (!InsertedArguments) {
1502 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001503 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001504 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001505 InsertedArguments = true;
1506 }
1507
Reid Spencer04cde2c2004-07-04 11:33:49 +00001508 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001509 break;
1510
Reid Spencerad89bd62004-07-25 18:07:36 +00001511 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001512 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001513 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001514 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001515 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001516 InsertedArguments = true;
1517 }
1518
Misha Brukman8a96c532005-04-21 21:44:41 +00001519 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001520 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001521 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001522 break;
1523 }
1524
Reid Spencer78d033e2007-01-06 07:24:44 +00001525 case BytecodeFormat::ValueSymbolTableBlockID:
1526 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1527 break;
1528
1529 case BytecodeFormat::TypeSymbolTableBlockID:
1530 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001531 break;
1532
1533 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001534 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001535 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001536 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001537 break;
1538 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001539 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001540 }
1541
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001542 // Make sure there were no references to non-existant basic blocks.
1543 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001544 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001545
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001546 ParsedBasicBlocks.clear();
1547
Chris Lattner97330cf2003-10-09 23:10:14 +00001548 // Resolve forward references. Replace any uses of a forward reference value
1549 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001550 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001551 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1552 I = ForwardReferences.begin();
1553 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001554 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001555 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001556 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001557 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001558 }
Chris Lattner00950542001-06-06 20:29:01 +00001559
Misha Brukman12c29d12003-09-22 23:38:23 +00001560 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001561 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001562 freeTable(FunctionValues);
1563
Reid Spencer04cde2c2004-07-04 11:33:49 +00001564 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001565}
1566
Reid Spencer04cde2c2004-07-04 11:33:49 +00001567/// This function parses LLVM functions lazily. It obtains the type of the
1568/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001569/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001570/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001571void BytecodeReader::ParseFunctionLazily() {
1572 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001573 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001574
Reid Spencer060d25d2004-06-29 23:29:38 +00001575 Function *Func = FunctionSignatureList.back();
1576 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001577
Reid Spencer060d25d2004-06-29 23:29:38 +00001578 // Save the information for future reading of the function
1579 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001580
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001581 // This function has a body but it's not loaded so it appears `External'.
1582 // Mark it as a `Ghost' instead to notify the users that it has a body.
1583 Func->setLinkage(GlobalValue::GhostLinkage);
1584
Reid Spencer060d25d2004-06-29 23:29:38 +00001585 // Pretend we've `parsed' this function
1586 At = BlockEnd;
1587}
Chris Lattner89e02532004-01-18 21:08:15 +00001588
Misha Brukman8a96c532005-04-21 21:44:41 +00001589/// The ParserFunction method lazily parses one function. Use this method to
1590/// casue the parser to parse a specific function in the module. Note that
1591/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001592/// ParseAllFunctionBodies.
1593/// @see ParseAllFunctionBodies
1594/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001595bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1596
Reid Spencer9b84ad12006-12-15 19:49:23 +00001597 if (setjmp(context)) {
1598 // Set caller's error message, if requested
1599 if (ErrMsg)
1600 *ErrMsg = ErrorMsg;
1601 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001602 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001603 }
Reid Spencer99655e12006-08-25 19:54:53 +00001604
Reid Spencer060d25d2004-06-29 23:29:38 +00001605 // Find {start, end} pointers and slot in the map. If not there, we're done.
1606 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001607
Reid Spencer060d25d2004-06-29 23:29:38 +00001608 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001609 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001610 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001611 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001612 }
1613
Reid Spencer060d25d2004-06-29 23:29:38 +00001614 BlockStart = At = Fi->second.Buf;
1615 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001616 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001617
1618 LazyFunctionLoadMap.erase(Fi);
1619
Reid Spencer46b002c2004-07-11 17:28:43 +00001620 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001621 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001622}
1623
Reid Spencer04cde2c2004-07-04 11:33:49 +00001624/// The ParseAllFunctionBodies method parses through all the previously
1625/// unparsed functions in the bytecode file. If you want to completely parse
1626/// a bytecode file, this method should be called after Parsebytecode because
1627/// Parsebytecode only records the locations in the bytecode file of where
1628/// the function definitions are located. This function uses that information
1629/// to materialize the functions.
1630/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001631bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001632 if (setjmp(context)) {
1633 // Set caller's error message, if requested
1634 if (ErrMsg)
1635 *ErrMsg = ErrorMsg;
1636 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001637 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001638 }
Reid Spencer99655e12006-08-25 19:54:53 +00001639
Reid Spencer060d25d2004-06-29 23:29:38 +00001640 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1641 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001642
Reid Spencer46b002c2004-07-11 17:28:43 +00001643 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001644 Function* Func = Fi->first;
1645 BlockStart = At = Fi->second.Buf;
1646 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001647 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001648 ++Fi;
1649 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001650 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001651 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001652}
Chris Lattner89e02532004-01-18 21:08:15 +00001653
Reid Spencer04cde2c2004-07-04 11:33:49 +00001654/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001655void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001656 // Read the number of types
1657 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001658 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001659}
1660
Reid Spencer04cde2c2004-07-04 11:33:49 +00001661/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001662void BytecodeReader::ParseModuleGlobalInfo() {
1663
Reid Spencer04cde2c2004-07-04 11:33:49 +00001664 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001665
Chris Lattner404cddf2005-11-12 01:33:40 +00001666 // SectionID - If a global has an explicit section specified, this map
1667 // remembers the ID until we can translate it into a string.
1668 std::map<GlobalValue*, unsigned> SectionID;
1669
Chris Lattner70cc3392001-09-10 07:58:01 +00001670 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001671 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001672 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001673 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1674 // Linkage, bit4+ = slot#
1675 unsigned SlotNo = VarType >> 5;
1676 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001677 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001678 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001679 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001680 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001681 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001682
1683 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1684 if (LinkageID == 3 && !hasInitializer) {
1685 unsigned ExtWord = read_vbr_uint();
1686 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001687 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1688 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001689 hasInitializer = ExtWord & 1;
1690 LinkageID = (ExtWord >> 1) & 7;
1691 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001692 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001693
1694 if (ExtWord & (1 << 9)) // Has a section ID.
1695 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001696 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001697
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001698 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001699 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001700 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1701 case 1: Linkage = GlobalValue::WeakLinkage; break;
1702 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1703 case 3: Linkage = GlobalValue::InternalLinkage; break;
1704 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001705 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1706 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1707 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001708 default:
Reid Spencer24399722004-07-09 22:21:33 +00001709 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001710 Linkage = GlobalValue::InternalLinkage;
1711 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001712 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001713 GlobalValue::VisibilityTypes Visibility;
1714 switch (VisibilityID) {
1715 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1716 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1717 default:
1718 error("Unknown visibility type: " + utostr(VisibilityID));
1719 Visibility = GlobalValue::DefaultVisibility;
1720 break;
1721 }
1722
Chris Lattnere3869c82003-04-16 21:16:05 +00001723 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001724 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001725 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001726
Chris Lattnere73bd452005-11-06 07:43:39 +00001727 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001728 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001729
Chris Lattner52e20b02003-03-19 20:54:26 +00001730 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001731
Chris Lattner70cc3392001-09-10 07:58:01 +00001732 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001733 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001734 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001735 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001736 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001737 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001738
Chris Lattner404cddf2005-11-12 01:33:40 +00001739 if (GlobalSectionID != 0)
1740 SectionID[GV] = GlobalSectionID;
1741
Reid Spencer060d25d2004-06-29 23:29:38 +00001742 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001743 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001744 initSlot = read_vbr_uint();
1745 GlobalInits.push_back(std::make_pair(GV, initSlot));
1746 }
1747
1748 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001749 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001750 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1751 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001752
1753 // Get next item
1754 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001755 }
1756
Chris Lattner52e20b02003-03-19 20:54:26 +00001757 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001758 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001759
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001760 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001761 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1762 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001763 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001764 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001765 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001766 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001767 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001768
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001769 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001770 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001771 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001772
Chris Lattner18549c22004-11-15 21:43:03 +00001773 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001774 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001775 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001776
Chris Lattnere73bd452005-11-06 07:43:39 +00001777 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001778
1779 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001780 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001781
Chris Lattner97fbc502004-11-15 22:38:52 +00001782 // Save this for later so we know type of lazily instantiated functions.
1783 // Note that known-external functions do not have FunctionInfo blocks, so we
1784 // do not add them to the FunctionSignatureList.
1785 if ((Flags & (1 << 4)) == 0)
1786 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001787
Chris Lattnere73bd452005-11-06 07:43:39 +00001788 // Get the calling convention from the low bits.
1789 unsigned CC = Flags & 15;
1790 unsigned Alignment = 0;
1791 if (FnSignature & (1 << 31)) { // Has extension word?
1792 unsigned ExtWord = read_vbr_uint();
1793 Alignment = (1 << (ExtWord & 31)) >> 1;
1794 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001795
1796 if (ExtWord & (1 << 10)) // Has a section ID.
1797 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001798
1799 // Parse external declaration linkage
1800 switch ((ExtWord >> 11) & 3) {
1801 case 0: break;
1802 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1803 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1804 default: assert(0 && "Unsupported external linkage");
1805 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001806 }
1807
Chris Lattner54b369e2005-11-06 07:46:13 +00001808 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001809 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001810
Reid Spencer04cde2c2004-07-04 11:33:49 +00001811 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001812
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001813 // Get the next function signature.
1814 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001815 }
1816
Misha Brukman8a96c532005-04-21 21:44:41 +00001817 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001818 // remove elements efficiently from the back of the vector.
1819 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001820
Chris Lattner404cddf2005-11-12 01:33:40 +00001821 /// SectionNames - This contains the list of section names encoded in the
1822 /// moduleinfoblock. Functions and globals with an explicit section index
1823 /// into this to get their section name.
1824 std::vector<std::string> SectionNames;
1825
Reid Spencerd798a512006-11-14 04:47:22 +00001826 // Read in the dependent library information.
1827 unsigned num_dep_libs = read_vbr_uint();
1828 std::string dep_lib;
1829 while (num_dep_libs--) {
1830 dep_lib = read_str();
1831 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001832 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001833 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001834 }
1835
Reid Spencerd798a512006-11-14 04:47:22 +00001836 // Read target triple and place into the module.
1837 std::string triple = read_str();
1838 TheModule->setTargetTriple(triple);
1839 if (Handler)
1840 Handler->handleTargetTriple(triple);
1841
Reid Spenceraacc35a2007-01-26 08:10:24 +00001842 // Read the data layout string and place into the module.
1843 std::string datalayout = read_str();
1844 TheModule->setDataLayout(datalayout);
1845 // FIXME: Implement
1846 // if (Handler)
1847 // Handler->handleDataLayout(datalayout);
1848
Reid Spencerd798a512006-11-14 04:47:22 +00001849 if (At != BlockEnd) {
1850 // If the file has section info in it, read the section names now.
1851 unsigned NumSections = read_vbr_uint();
1852 while (NumSections--)
1853 SectionNames.push_back(read_str());
1854 }
1855
1856 // If the file has module-level inline asm, read it now.
1857 if (At != BlockEnd)
1858 TheModule->setModuleInlineAsm(read_str());
1859
Chris Lattner404cddf2005-11-12 01:33:40 +00001860 // If any globals are in specified sections, assign them now.
1861 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1862 SectionID.end(); I != E; ++I)
1863 if (I->second) {
1864 if (I->second > SectionID.size())
1865 error("SectionID out of range for global!");
1866 I->first->setSection(SectionNames[I->second-1]);
1867 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001868
Chris Lattner00950542001-06-06 20:29:01 +00001869 // This is for future proofing... in the future extra fields may be added that
1870 // we don't understand, so we transparently ignore them.
1871 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001872 At = BlockEnd;
1873
Reid Spencer04cde2c2004-07-04 11:33:49 +00001874 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001875}
1876
Reid Spencer04cde2c2004-07-04 11:33:49 +00001877/// Parse the version information and decode it by setting flags on the
1878/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001879void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001880 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001881
Reid Spencer3795ad12006-12-03 05:47:10 +00001882 // We don't provide backwards compatibility in the Reader any more. To
1883 // upgrade, the user should use llvm-upgrade.
1884 if (RevisionNum < 7)
1885 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001886
Reid Spenceraacc35a2007-01-26 08:10:24 +00001887 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001888}
1889
Reid Spencer04cde2c2004-07-04 11:33:49 +00001890/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001891void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001892 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001893
Reid Spencer060d25d2004-06-29 23:29:38 +00001894 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001895
1896 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001897 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001898
Reid Spencer060d25d2004-06-29 23:29:38 +00001899 bool SeenModuleGlobalInfo = false;
1900 bool SeenGlobalTypePlane = false;
1901 BufPtr MyEnd = BlockEnd;
1902 while (At < MyEnd) {
1903 BufPtr OldAt = At;
1904 read_block(Type, Size);
1905
Chris Lattner00950542001-06-06 20:29:01 +00001906 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001907
Reid Spencerad89bd62004-07-25 18:07:36 +00001908 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001909 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001910 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001911
Reid Spencer5b472d92004-08-21 20:49:23 +00001912 if (Size > 0)
1913 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001914 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001915 break;
1916
Misha Brukman8a96c532005-04-21 21:44:41 +00001917 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001918 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001919 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001920 ParseModuleGlobalInfo();
1921 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001922 break;
1923
Reid Spencerad89bd62004-07-25 18:07:36 +00001924 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001925 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001926 break;
1927
Reid Spencerad89bd62004-07-25 18:07:36 +00001928 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001929 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001930 break;
Chris Lattner00950542001-06-06 20:29:01 +00001931
Reid Spencer78d033e2007-01-06 07:24:44 +00001932 case BytecodeFormat::ValueSymbolTableBlockID:
1933 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1934 break;
1935
1936 case BytecodeFormat::TypeSymbolTableBlockID:
1937 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001938 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001939
Chris Lattner00950542001-06-06 20:29:01 +00001940 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001941 At += Size;
1942 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001943 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001944 }
Chris Lattner00950542001-06-06 20:29:01 +00001945 break;
1946 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001947 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001948 }
1949
Chris Lattner52e20b02003-03-19 20:54:26 +00001950 // After the module constant pool has been read, we can safely initialize
1951 // global variables...
1952 while (!GlobalInits.empty()) {
1953 GlobalVariable *GV = GlobalInits.back().first;
1954 unsigned Slot = GlobalInits.back().second;
1955 GlobalInits.pop_back();
1956
1957 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001958 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001959
1960 const llvm::PointerType* GVType = GV->getType();
1961 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001962 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001963 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001964 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001965 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001966 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001967 } else
Reid Spencer24399722004-07-09 22:21:33 +00001968 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001969 }
1970
Chris Lattneraba5ff52005-05-05 20:57:00 +00001971 if (!ConstantFwdRefs.empty())
1972 error("Use of undefined constants in a module");
1973
Reid Spencer060d25d2004-06-29 23:29:38 +00001974 /// Make sure we pulled them all out. If we didn't then there's a declaration
1975 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001976 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001977 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001978}
1979
Reid Spencer04cde2c2004-07-04 11:33:49 +00001980/// This function completely parses a bytecode buffer given by the \p Buf
1981/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00001982bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00001983 const std::string &ModuleID,
Chris Lattner0d3382a2007-02-07 19:49:01 +00001984 Decompressor_t *Decompressor,
Reid Spencer233fe722006-08-22 16:09:19 +00001985 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001986
Reid Spencer233fe722006-08-22 16:09:19 +00001987 /// We handle errors by
1988 if (setjmp(context)) {
1989 // Cleanup after error
1990 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00001991 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001992 delete TheModule;
1993 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00001994 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00001995 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00001996 decompressedBlock = 0;
1997 }
Reid Spencer233fe722006-08-22 16:09:19 +00001998 // Set caller's error message, if requested
1999 if (ErrMsg)
2000 *ErrMsg = ErrorMsg;
2001 // Indicate an error occurred
2002 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002003 }
Reid Spencer233fe722006-08-22 16:09:19 +00002004
2005 RevisionNum = 0;
2006 At = MemStart = BlockStart = Buf;
2007 MemEnd = BlockEnd = Buf + Length;
2008
2009 // Create the module
2010 TheModule = new Module(ModuleID);
2011
2012 if (Handler) Handler->handleStart(TheModule, Length);
2013
2014 // Read the four bytes of the signature.
2015 unsigned Sig = read_uint();
2016
2017 // If this is a compressed file
2018 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2019
2020 // Invoke the decompression of the bytecode. Note that we have to skip the
2021 // file's magic number which is not part of the compressed block. Hence,
2022 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2023 // member for retention until BytecodeReader is destructed.
Chris Lattner0d3382a2007-02-07 19:49:01 +00002024 unsigned decompressedLength =
2025 Decompressor((char*)Buf+4,Length-4,decompressedBlock, 0);
Reid Spencer233fe722006-08-22 16:09:19 +00002026
2027 // We must adjust the buffer pointers used by the bytecode reader to point
2028 // into the new decompressed block. After decompression, the
2029 // decompressedBlock will point to a contiguous memory area that has
2030 // the decompressed data.
2031 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2032 MemEnd = BlockEnd = Buf + decompressedLength;
2033
2034 // else if this isn't a regular (uncompressed) bytecode file, then its
2035 // and error, generate that now.
2036 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2037 error("Invalid bytecode signature: " + utohexstr(Sig));
2038 }
2039
2040 // Tell the handler we're starting a module
2041 if (Handler) Handler->handleModuleBegin(ModuleID);
2042
2043 // Get the module block and size and verify. This is handled specially
2044 // because the module block/size is always written in long format. Other
2045 // blocks are written in short format so the read_block method is used.
2046 unsigned Type, Size;
2047 Type = read_uint();
2048 Size = read_uint();
2049 if (Type != BytecodeFormat::ModuleBlockID) {
2050 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2051 + utostr(Size));
2052 }
2053
2054 // It looks like the darwin ranlib program is broken, and adds trailing
2055 // garbage to the end of some bytecode files. This hack allows the bc
2056 // reader to ignore trailing garbage on bytecode files.
2057 if (At + Size < MemEnd)
2058 MemEnd = BlockEnd = At+Size;
2059
2060 if (At + Size != MemEnd)
2061 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2062 + ", Size:" + utostr(Size));
2063
2064 // Parse the module contents
2065 this->ParseModule();
2066
2067 // Check for missing functions
2068 if (hasFunctions())
2069 error("Function expected, but bytecode stream ended!");
2070
Reid Spencer233fe722006-08-22 16:09:19 +00002071 // Tell the handler we're done with the module
2072 if (Handler)
2073 Handler->handleModuleEnd(ModuleID);
2074
2075 // Tell the handler we're finished the parse
2076 if (Handler) Handler->handleFinish();
2077
2078 return false;
2079
Chris Lattner00950542001-06-06 20:29:01 +00002080}
Reid Spencer060d25d2004-06-29 23:29:38 +00002081
2082//===----------------------------------------------------------------------===//
2083//=== Default Implementations of Handler Methods
2084//===----------------------------------------------------------------------===//
2085
2086BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002087