blob: 8d0f86fcaa51332d1a982534a7f15abf7c0fe7cc [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"
Reid Spencer17f52c52004-11-06 23:17:23 +000030#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000031#include "llvm/Support/MathExtras.h"
Chris Lattner4c3d3a92007-01-31 19:56:15 +000032#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000048 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000049 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
Reid Spenceref9b9a72007-02-05 20:47:22 +000057 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer233fe722006-08-22 16:09:19 +000058 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000059}
60
Reid Spencer060d25d2004-06-29 23:29:38 +000061//===----------------------------------------------------------------------===//
62// Bytecode Reading Methods
63//===----------------------------------------------------------------------===//
64
Reid Spencer04cde2c2004-07-04 11:33:49 +000065/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000066inline bool BytecodeReader::moreInBlock() {
67 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000068}
69
Reid Spencer04cde2c2004-07-04 11:33:49 +000070/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000071inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000072 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000073 error(std::string("Attempt to read past the end of ") + block_name +
74 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000075}
Chris Lattner36392bc2003-10-08 21:18:57 +000076
Reid Spencer04cde2c2004-07-04 11:33:49 +000077/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000078inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000079 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000080 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000081 At += 4;
82 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
83}
84
Reid Spencer04cde2c2004-07-04 11:33:49 +000085/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000086inline unsigned BytecodeReader::read_vbr_uint() {
87 unsigned Shift = 0;
88 unsigned Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +000089
Reid Spencer060d25d2004-06-29 23:29:38 +000090 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000091 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000092 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000093 Result |= (unsigned)((*At++) & 0x7F) << Shift;
94 Shift += 7;
95 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +000096 return Result;
97}
98
Reid Spencer04cde2c2004-07-04 11:33:49 +000099/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000100inline uint64_t BytecodeReader::read_vbr_uint64() {
101 unsigned Shift = 0;
102 uint64_t Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +0000103
Reid Spencer060d25d2004-06-29 23:29:38 +0000104 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000105 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000106 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000107 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
108 Shift += 7;
109 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +0000110 return Result;
111}
112
Reid Spencer04cde2c2004-07-04 11:33:49 +0000113/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000114inline int64_t BytecodeReader::read_vbr_int64() {
115 uint64_t R = read_vbr_uint64();
116 if (R & 1) {
117 if (R != 1)
118 return -(int64_t)(R >> 1);
119 else // There is no such thing as -0 with integers. "-0" really means
120 // 0x8000000000000000.
121 return 1LL << 63;
122 } else
123 return (int64_t)(R >> 1);
124}
125
Reid Spencer04cde2c2004-07-04 11:33:49 +0000126/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000127inline std::string BytecodeReader::read_str() {
128 unsigned Size = read_vbr_uint();
129 const unsigned char *OldAt = At;
130 At += Size;
131 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000132 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000133 return std::string((char*)OldAt, Size);
134}
135
Reid Spencer04cde2c2004-07-04 11:33:49 +0000136/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000137inline void BytecodeReader::read_data(void *Ptr, void *End) {
138 unsigned char *Start = (unsigned char *)Ptr;
139 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000140 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000141 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000142 std::copy(At, At+Amount, Start);
143 At += Amount;
144}
145
Reid Spencer46b002c2004-07-11 17:28:43 +0000146/// Read a float value in little-endian order
147inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000148 /// FIXME: This isn't optimal, it has size problems on some platforms
149 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000150 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000151 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000152}
153
154/// Read a double value in little-endian order
155inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000156 /// FIXME: This isn't optimal, it has size problems on some platforms
157 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000158 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
159 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
160 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
161 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000162 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000163}
164
Reid Spencer04cde2c2004-07-04 11:33:49 +0000165/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000166inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000167 Size = read_uint(); // Read the header
168 Type = Size & 0x1F; // mask low order five bits to get type
169 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000170 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000171 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000172 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000173 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000174 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000175}
176
Reid Spencer060d25d2004-06-29 23:29:38 +0000177//===----------------------------------------------------------------------===//
178// IR Lookup Methods
179//===----------------------------------------------------------------------===//
180
Reid Spencer04cde2c2004-07-04 11:33:49 +0000181/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000182inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000183 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000184}
185
Reid Spencerd2bb8872007-01-30 19:36:46 +0000186/// Obtain a type given a typeid and account for things like function level vs
187/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000188const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000189 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000190 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000191 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000192
193 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000194 ID -= Type::FirstDerivedTyID;
195
Chris Lattner36392bc2003-10-08 21:18:57 +0000196 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000197 if (ID < ModuleTypes.size())
198 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000199
Reid Spencer46b002c2004-07-11 17:28:43 +0000200 // Nope, is it a function-level type?
201 ID -= ModuleTypes.size();
202 if (ID < FunctionTypes.size())
203 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000204
Reid Spencer46b002c2004-07-11 17:28:43 +0000205 error("Illegal type reference!");
206 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000207}
208
Reid Spencer3795ad12006-12-03 05:47:10 +0000209/// This method just saves some coding. It uses read_vbr_uint to read in a
210/// type id, errors that its not the type type, and then calls getType to
211/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000212inline const Type* BytecodeReader::readType() {
213 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000214}
215
216/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000217/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000218unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
219 if (Ty->isPrimitiveType())
220 return Ty->getTypeID();
221
Reid Spencer060d25d2004-06-29 23:29:38 +0000222 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000223 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
224 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000225
226 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000227 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000228 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000229
Chris Lattnereebac5f2005-10-03 21:26:53 +0000230 // If we don't have our cache yet, build it now.
231 if (ModuleTypeIDCache.empty()) {
232 unsigned N = 0;
233 ModuleTypeIDCache.reserve(ModuleTypes.size());
234 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
235 I != E; ++I, ++N)
236 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
237
238 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
239 }
240
241 // Binary search the cache for the entry.
242 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
243 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
244 std::make_pair(Ty, 0U));
245 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000246 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000247
248 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000249}
250
Misha Brukman8a96c532005-04-21 21:44:41 +0000251/// Retrieve a value of a given type and slot number, possibly creating
252/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000253Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000254 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000255 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000256
Reid Spencerd2bb8872007-01-30 19:36:46 +0000257 // By default, the global type id is the type id passed in
258 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000259
Reid Spencerd2bb8872007-01-30 19:36:46 +0000260 if (hasImplicitNull(GlobalTyID)) {
261 const Type *Ty = getType(type);
262 if (!isa<OpaqueType>(Ty)) {
263 if (Num == 0)
264 return Constant::getNullValue(Ty);
265 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000266 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000267 }
Chris Lattner89e02532004-01-18 21:08:15 +0000268
Reid Spencerd2bb8872007-01-30 19:36:46 +0000269 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
270 if (Num < ModuleValues[GlobalTyID]->size())
271 return ModuleValues[GlobalTyID]->getOperand(Num);
272 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner52e20b02003-03-19 20:54:26 +0000273 }
274
Misha Brukman8a96c532005-04-21 21:44:41 +0000275 if (FunctionValues.size() > type &&
276 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000277 Num < FunctionValues[type]->size())
278 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000279
Chris Lattner74734132002-08-17 22:01:27 +0000280 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000281
Reid Spencer551ccae2004-09-01 22:55:40 +0000282 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000283 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000284 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000285 if (I != ForwardReferences.end() && I->first == KeyValue)
286 return I->second; // We have already created this placeholder
287
Reid Spencer551ccae2004-09-01 22:55:40 +0000288 // If the type exists (it should)
289 if (const Type* Ty = getType(type)) {
290 // Create the place holder
291 Value *Val = new Argument(Ty);
292 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
293 return Val;
294 }
Reid Spencer233fe722006-08-22 16:09:19 +0000295 error("Can't create placeholder for value of type slot #" + utostr(type));
296 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000297}
298
Reid Spencer060d25d2004-06-29 23:29:38 +0000299
Reid Spencer04cde2c2004-07-04 11:33:49 +0000300/// Just like getValue, except that it returns a null pointer
301/// only on error. It always returns a constant (meaning that if the value is
302/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000303/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000304/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000305Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
306 if (Value *V = getValue(TypeSlot, Slot, false))
307 if (Constant *C = dyn_cast<Constant>(V))
308 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000309 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000310 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000311 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000312
Chris Lattner389bd042004-12-09 06:19:44 +0000313 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000314 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
315
316 if (I != ConstantFwdRefs.end() && I->first == Key) {
317 return I->second;
318 } else {
319 // Create a placeholder for the constant reference and
320 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000321 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000322
Reid Spencer060d25d2004-06-29 23:29:38 +0000323 // Keep track of the fact that we have a forward ref to recycle it
324 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
325 return C;
326 }
327}
328
329//===----------------------------------------------------------------------===//
330// IR Construction Methods
331//===----------------------------------------------------------------------===//
332
Reid Spencer04cde2c2004-07-04 11:33:49 +0000333/// As values are created, they are inserted into the appropriate place
334/// with this method. The ValueTable argument must be one of ModuleValues
335/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000336unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000337 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000338 if (ValueTab.size() <= type)
339 ValueTab.resize(type+1);
340
341 if (!ValueTab[type]) ValueTab[type] = new ValueList();
342
343 ValueTab[type]->push_back(Val);
344
Chris Lattneraba5ff52005-05-05 20:57:00 +0000345 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000346 return ValueTab[type]->size()-1 + HasOffset;
347}
348
Reid Spencer04cde2c2004-07-04 11:33:49 +0000349/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000350void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000351 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000352 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000353 for (FunctionType::param_iterator It = FT->param_begin();
354 It != FT->param_end(); ++It, ++AI)
355 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
356}
357
358//===----------------------------------------------------------------------===//
359// Bytecode Parsing Methods
360//===----------------------------------------------------------------------===//
361
Reid Spencer04cde2c2004-07-04 11:33:49 +0000362/// This method parses a single instruction. The instruction is
363/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000364/// the instruction are provided in the \p Oprnds vector.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000365void BytecodeReader::ParseInstruction(SmallVector<unsigned, 8> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000366 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000367 BufPtr SaveAt = At;
368
369 // Clear instruction data
370 Oprnds.clear();
371 unsigned iType = 0;
372 unsigned Opcode = 0;
373 unsigned Op = read_uint();
374
375 // bits Instruction format: Common to all formats
376 // --------------------------
377 // 01-00: Opcode type, fixed to 1.
378 // 07-02: Opcode
379 Opcode = (Op >> 2) & 63;
380 Oprnds.resize((Op >> 0) & 03);
381
382 // Extract the operands
383 switch (Oprnds.size()) {
384 case 1:
385 // bits Instruction format:
386 // --------------------------
387 // 19-08: Resulting type plane
388 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
389 //
390 iType = (Op >> 8) & 4095;
391 Oprnds[0] = (Op >> 20) & 4095;
392 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
393 Oprnds.resize(0);
394 break;
395 case 2:
396 // bits Instruction format:
397 // --------------------------
398 // 15-08: Resulting type plane
399 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000400 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000401 //
402 iType = (Op >> 8) & 255;
403 Oprnds[0] = (Op >> 16) & 255;
404 Oprnds[1] = (Op >> 24) & 255;
405 break;
406 case 3:
407 // bits Instruction format:
408 // --------------------------
409 // 13-08: Resulting type plane
410 // 19-14: Operand #1
411 // 25-20: Operand #2
412 // 31-26: Operand #3
413 //
414 iType = (Op >> 8) & 63;
415 Oprnds[0] = (Op >> 14) & 63;
416 Oprnds[1] = (Op >> 20) & 63;
417 Oprnds[2] = (Op >> 26) & 63;
418 break;
419 case 0:
420 At -= 4; // Hrm, try this again...
421 Opcode = read_vbr_uint();
422 Opcode >>= 2;
423 iType = read_vbr_uint();
424
425 unsigned NumOprnds = read_vbr_uint();
426 Oprnds.resize(NumOprnds);
427
428 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000429 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000430
431 for (unsigned i = 0; i != NumOprnds; ++i)
432 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000433 break;
434 }
435
Reid Spencerd798a512006-11-14 04:47:22 +0000436 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000437
Reid Spencer1628cec2006-10-26 06:15:43 +0000438 // Make the necessary adjustments for dealing with backwards compatibility
439 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000440 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000441
Reid Spencer3795ad12006-12-03 05:47:10 +0000442 // First, handle the easy binary operators case
443 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000444 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000445 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
446 getValue(iType, Oprnds[0]),
447 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000448 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000449 // Indicate that we don't think this is a call instruction (yet).
450 // Process based on the Opcode read
451 switch (Opcode) {
452 default: // There was an error, this shouldn't happen.
453 if (Result == 0)
454 error("Illegal instruction read!");
455 break;
456 case Instruction::VAArg:
457 if (Oprnds.size() != 2)
458 error("Invalid VAArg instruction!");
459 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000460 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000461 break;
462 case Instruction::ExtractElement: {
463 if (Oprnds.size() != 2)
464 error("Invalid extractelement instruction!");
465 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000466 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000467
Reid Spencer1628cec2006-10-26 06:15:43 +0000468 if (!ExtractElementInst::isValidOperands(V1, V2))
469 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000470
Reid Spencer1628cec2006-10-26 06:15:43 +0000471 Result = new ExtractElementInst(V1, V2);
472 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000473 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000474 case Instruction::InsertElement: {
475 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
476 if (!PackedTy || Oprnds.size() != 3)
477 error("Invalid insertelement instruction!");
478
479 Value *V1 = getValue(iType, Oprnds[0]);
480 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000481 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000482
483 if (!InsertElementInst::isValidOperands(V1, V2, V3))
484 error("Invalid insertelement instruction!");
485 Result = new InsertElementInst(V1, V2, V3);
486 break;
487 }
488 case Instruction::ShuffleVector: {
489 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
490 if (!PackedTy || Oprnds.size() != 3)
491 error("Invalid shufflevector instruction!");
492 Value *V1 = getValue(iType, Oprnds[0]);
493 Value *V2 = getValue(iType, Oprnds[1]);
494 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000495 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000496 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
497 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
498 error("Invalid shufflevector instruction!");
499 Result = new ShuffleVectorInst(V1, V2, V3);
500 break;
501 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000502 case Instruction::Trunc:
503 if (Oprnds.size() != 2)
504 error("Invalid cast instruction!");
505 Result = new TruncInst(getValue(iType, Oprnds[0]),
506 getType(Oprnds[1]));
507 break;
508 case Instruction::ZExt:
509 if (Oprnds.size() != 2)
510 error("Invalid cast instruction!");
511 Result = new ZExtInst(getValue(iType, Oprnds[0]),
512 getType(Oprnds[1]));
513 break;
514 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000515 if (Oprnds.size() != 2)
516 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000517 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000518 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000519 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000520 case Instruction::FPTrunc:
521 if (Oprnds.size() != 2)
522 error("Invalid cast instruction!");
523 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
524 getType(Oprnds[1]));
525 break;
526 case Instruction::FPExt:
527 if (Oprnds.size() != 2)
528 error("Invalid cast instruction!");
529 Result = new FPExtInst(getValue(iType, Oprnds[0]),
530 getType(Oprnds[1]));
531 break;
532 case Instruction::UIToFP:
533 if (Oprnds.size() != 2)
534 error("Invalid cast instruction!");
535 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
536 getType(Oprnds[1]));
537 break;
538 case Instruction::SIToFP:
539 if (Oprnds.size() != 2)
540 error("Invalid cast instruction!");
541 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
542 getType(Oprnds[1]));
543 break;
544 case Instruction::FPToUI:
545 if (Oprnds.size() != 2)
546 error("Invalid cast instruction!");
547 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
548 getType(Oprnds[1]));
549 break;
550 case Instruction::FPToSI:
551 if (Oprnds.size() != 2)
552 error("Invalid cast instruction!");
553 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
554 getType(Oprnds[1]));
555 break;
556 case Instruction::IntToPtr:
557 if (Oprnds.size() != 2)
558 error("Invalid cast instruction!");
559 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
560 getType(Oprnds[1]));
561 break;
562 case Instruction::PtrToInt:
563 if (Oprnds.size() != 2)
564 error("Invalid cast instruction!");
565 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
566 getType(Oprnds[1]));
567 break;
568 case Instruction::BitCast:
569 if (Oprnds.size() != 2)
570 error("Invalid cast instruction!");
571 Result = new BitCastInst(getValue(iType, Oprnds[0]),
572 getType(Oprnds[1]));
573 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000574 case Instruction::Select:
575 if (Oprnds.size() != 3)
576 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000577 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000578 getValue(iType, Oprnds[1]),
579 getValue(iType, Oprnds[2]));
580 break;
581 case Instruction::PHI: {
582 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
583 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000584
Reid Spencer1628cec2006-10-26 06:15:43 +0000585 PHINode *PN = new PHINode(InstTy);
586 PN->reserveOperandSpace(Oprnds.size());
587 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
588 PN->addIncoming(
589 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
590 Result = PN;
591 break;
592 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000593 case Instruction::ICmp:
594 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000595 if (Oprnds.size() != 3)
596 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000597 // These instructions encode the comparison predicate as the 3rd operand.
598 Result = CmpInst::create(Instruction::OtherOps(Opcode),
599 static_cast<unsigned short>(Oprnds[2]),
600 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
601 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000602 case Instruction::Ret:
603 if (Oprnds.size() == 0)
604 Result = new ReturnInst();
605 else if (Oprnds.size() == 1)
606 Result = new ReturnInst(getValue(iType, Oprnds[0]));
607 else
608 error("Unrecognized instruction!");
609 break;
610
611 case Instruction::Br:
612 if (Oprnds.size() == 1)
613 Result = new BranchInst(getBasicBlock(Oprnds[0]));
614 else if (Oprnds.size() == 3)
615 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000616 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000617 else
618 error("Invalid number of operands for a 'br' instruction!");
619 break;
620 case Instruction::Switch: {
621 if (Oprnds.size() & 1)
622 error("Switch statement with odd number of arguments!");
623
624 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
625 getBasicBlock(Oprnds[1]),
626 Oprnds.size()/2-1);
627 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
628 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
629 getBasicBlock(Oprnds[i+1]));
630 Result = I;
631 break;
632 }
633 case 58: // Call with extra operand for calling conv
634 case 59: // tail call, Fast CC
635 case 60: // normal call, Fast CC
636 case 61: // tail call, C Calling Conv
637 case Instruction::Call: { // Normal Call, C Calling Convention
638 if (Oprnds.size() == 0)
639 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000640 Value *F = getValue(iType, Oprnds[0]);
641
642 unsigned CallingConv = CallingConv::C;
643 bool isTailCall = false;
644
645 if (Opcode == 61 || Opcode == 59)
646 isTailCall = true;
647
648 if (Opcode == 58) {
649 isTailCall = Oprnds.back() & 1;
650 CallingConv = Oprnds.back() >> 1;
651 Oprnds.pop_back();
652 } else if (Opcode == 59 || Opcode == 60) {
653 CallingConv = CallingConv::Fast;
654 }
655
656 // Check to make sure we have a pointer to function type
657 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
658 if (PTy == 0) error("Call to non function pointer value!");
659 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
660 if (FTy == 0) error("Call to non function pointer value!");
661
662 std::vector<Value *> Params;
663 if (!FTy->isVarArg()) {
664 FunctionType::param_iterator It = FTy->param_begin();
665
666 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
667 if (It == FTy->param_end())
668 error("Invalid call instruction!");
669 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
670 }
671 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000672 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000673 } else {
674 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
675
676 unsigned FirstVariableOperand;
677 if (Oprnds.size() < FTy->getNumParams())
678 error("Call instruction missing operands!");
679
680 // Read all of the fixed arguments
681 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
682 Params.push_back(
683 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
684
685 FirstVariableOperand = FTy->getNumParams();
686
687 if ((Oprnds.size()-FirstVariableOperand) & 1)
688 error("Invalid call instruction!"); // Must be pairs of type/value
689
690 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
691 i != e; i += 2)
692 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000693 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000694
Reid Spencer1628cec2006-10-26 06:15:43 +0000695 Result = new CallInst(F, Params);
696 if (isTailCall) cast<CallInst>(Result)->setTailCall();
697 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
698 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000699 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000700 case Instruction::Invoke: { // Invoke C CC
701 if (Oprnds.size() < 3)
702 error("Invalid invoke instruction!");
703 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000704
Reid Spencer1628cec2006-10-26 06:15:43 +0000705 // Check to make sure we have a pointer to function type
706 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
707 if (PTy == 0)
708 error("Invoke to non function pointer value!");
709 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
710 if (FTy == 0)
711 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000712
Reid Spencer1628cec2006-10-26 06:15:43 +0000713 std::vector<Value *> Params;
714 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000715 unsigned CallingConv = Oprnds.back();
716 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000717
Reid Spencer1628cec2006-10-26 06:15:43 +0000718 if (!FTy->isVarArg()) {
719 Normal = getBasicBlock(Oprnds[1]);
720 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000721
Reid Spencer1628cec2006-10-26 06:15:43 +0000722 FunctionType::param_iterator It = FTy->param_begin();
723 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
724 if (It == FTy->param_end())
725 error("Invalid invoke instruction!");
726 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
727 }
728 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000729 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000730 } else {
731 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
732
733 Normal = getBasicBlock(Oprnds[0]);
734 Except = getBasicBlock(Oprnds[1]);
735
736 unsigned FirstVariableArgument = FTy->getNumParams()+2;
737 for (unsigned i = 2; i != FirstVariableArgument; ++i)
738 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
739 Oprnds[i]));
740
741 // Must be type/value pairs. If not, error out.
742 if (Oprnds.size()-FirstVariableArgument & 1)
743 error("Invalid invoke instruction!");
744
745 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
746 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000747 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000748
Reid Spencer1628cec2006-10-26 06:15:43 +0000749 Result = new InvokeInst(F, Normal, Except, Params);
750 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
751 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000752 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000753 case Instruction::Malloc: {
754 unsigned Align = 0;
755 if (Oprnds.size() == 2)
756 Align = (1 << Oprnds[1]) >> 1;
757 else if (Oprnds.size() > 2)
758 error("Invalid malloc instruction!");
759 if (!isa<PointerType>(InstTy))
760 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000761
Reid Spencer1628cec2006-10-26 06:15:43 +0000762 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000763 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000764 break;
765 }
766 case Instruction::Alloca: {
767 unsigned Align = 0;
768 if (Oprnds.size() == 2)
769 Align = (1 << Oprnds[1]) >> 1;
770 else if (Oprnds.size() > 2)
771 error("Invalid alloca instruction!");
772 if (!isa<PointerType>(InstTy))
773 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000774
Reid Spencer1628cec2006-10-26 06:15:43 +0000775 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000776 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000777 break;
778 }
779 case Instruction::Free:
780 if (!isa<PointerType>(InstTy))
781 error("Invalid free instruction!");
782 Result = new FreeInst(getValue(iType, Oprnds[0]));
783 break;
784 case Instruction::GetElementPtr: {
785 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000786 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000787
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000788 SmallVector<Value*, 8> Idx;
Reid Spencer1628cec2006-10-26 06:15:43 +0000789
790 const Type *NextTy = InstTy;
791 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
792 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
793 if (!TopTy)
794 error("Invalid getelementptr instruction!");
795
796 unsigned ValIdx = Oprnds[i];
797 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000798 // Struct indices are always uints, sequential type indices can be
799 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000800 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000801 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000802 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000803 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000804 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000805 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000806 case 0: IdxTy = Int32TySlot; break;
807 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000808 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000809 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000810 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000811 Idx.push_back(getValue(IdxTy, ValIdx));
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000812 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
813 true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000814 }
815
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000816 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
817 &Idx[0], Idx.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000818 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000819 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000820 case 62: // volatile load
821 case Instruction::Load:
822 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
823 error("Invalid load instruction!");
824 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
825 break;
826 case 63: // volatile store
827 case Instruction::Store: {
828 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
829 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000830
Reid Spencer1628cec2006-10-26 06:15:43 +0000831 Value *Ptr = getValue(iType, Oprnds[1]);
832 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
833 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
834 Opcode == 63);
835 break;
836 }
837 case Instruction::Unwind:
838 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
839 Result = new UnwindInst();
840 break;
841 case Instruction::Unreachable:
842 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
843 Result = new UnreachableInst();
844 break;
845 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000846 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000847
Reid Spencere1e96c02006-01-19 07:02:16 +0000848 BB->getInstList().push_back(Result);
849
Reid Spencer060d25d2004-06-29 23:29:38 +0000850 unsigned TypeSlot;
851 if (Result->getType() == InstTy)
852 TypeSlot = iType;
853 else
854 TypeSlot = getTypeSlot(Result->getType());
855
Reid Spenceref9b9a72007-02-05 20:47:22 +0000856 // We have enough info to inform the handler now.
857 if (Handler)
Chris Lattner63cf59e2007-02-07 05:08:39 +0000858 Handler->handleInstruction(Opcode, InstTy, &Oprnds[0], Oprnds.size(),
859 Result, At-SaveAt);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000860
Reid Spencer060d25d2004-06-29 23:29:38 +0000861 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000862}
863
Reid Spencer04cde2c2004-07-04 11:33:49 +0000864/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000865/// This works together with ParseInstructionList to handle these forward
866/// references in a clean manner. This function is used when constructing
867/// phi, br, switch, and other instructions that reference basic blocks.
868/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000869BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000870 // Make sure there is room in the table...
871 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
872
Reid Spencerd798a512006-11-14 04:47:22 +0000873 // First check to see if this is a backwards reference, i.e. this block
874 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000875 // been created.
876 if (ParsedBasicBlocks[ID])
877 return ParsedBasicBlocks[ID];
878
879 // Otherwise, the basic block has not yet been created. Do so and add it to
880 // the ParsedBasicBlocks list.
881 return ParsedBasicBlocks[ID] = new BasicBlock();
882}
883
Reid Spencer04cde2c2004-07-04 11:33:49 +0000884/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000885/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000886/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000887/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000888unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000889 unsigned BlockNo = 0;
Chris Lattner63cf59e2007-02-07 05:08:39 +0000890 SmallVector<unsigned, 8> Args;
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000891
Reid Spencer46b002c2004-07-11 17:28:43 +0000892 while (moreInBlock()) {
893 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000894 BasicBlock *BB;
895 if (ParsedBasicBlocks.size() == BlockNo)
896 ParsedBasicBlocks.push_back(BB = new BasicBlock());
897 else if (ParsedBasicBlocks[BlockNo] == 0)
898 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
899 else
900 BB = ParsedBasicBlocks[BlockNo];
901 ++BlockNo;
902 F->getBasicBlockList().push_back(BB);
903
904 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000905 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000906 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000907
908 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000909 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000910
Reid Spencer46b002c2004-07-11 17:28:43 +0000911 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000912 }
913
914 return BlockNo;
915}
916
Reid Spencer78d033e2007-01-06 07:24:44 +0000917/// Parse a type symbol table.
918void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
919 // Type Symtab block header: [num entries]
920 unsigned NumEntries = read_vbr_uint();
921 for (unsigned i = 0; i < NumEntries; ++i) {
922 // Symtab entry: [type slot #][name]
923 unsigned slot = read_vbr_uint();
924 std::string Name = read_str();
925 const Type* T = getType(slot);
926 TST->insert(Name, T);
927 }
928}
929
930/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000931/// level symbol tables. For function level symbol tables, the CurrentFunction
932/// parameter must be non-zero and the ST parameter must correspond to
933/// CurrentFunction's symbol table. For Module level symbol tables, the
934/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000935void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000936 ValueSymbolTable *VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000937
Reid Spenceref9b9a72007-02-05 20:47:22 +0000938 if (Handler) Handler->handleValueSymbolTableBegin(CurrentFunction,VST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000939
Chris Lattner39cacce2003-10-10 05:43:47 +0000940 // Allow efficient basic block lookup by number.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000941 SmallVector<BasicBlock*, 32> BBMap;
Chris Lattner39cacce2003-10-10 05:43:47 +0000942 if (CurrentFunction)
943 for (Function::iterator I = CurrentFunction->begin(),
944 E = CurrentFunction->end(); I != E; ++I)
945 BBMap.push_back(I);
946
Reid Spencer46b002c2004-07-11 17:28:43 +0000947 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000948 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000949 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000950 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000951
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000952 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000953 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000954 unsigned slot = read_vbr_uint();
955 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +0000956 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000957 if (Typ == LabelTySlot) {
Reid Spencerd798a512006-11-14 04:47:22 +0000958 if (slot < BBMap.size())
959 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +0000960 } else {
Reid Spencerd798a512006-11-14 04:47:22 +0000961 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +0000962 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000963 if (Handler) Handler->handleSymbolTableValue(Typ, slot, Name);
Reid Spencerd798a512006-11-14 04:47:22 +0000964 if (V == 0)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000965 error("Failed value look-up for name '" + Name + "', type #" +
966 utostr(Typ) + " slot #" + utostr(slot));
Reid Spencerd798a512006-11-14 04:47:22 +0000967 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +0000968 }
969 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000970 checkPastBlockEnd("Symbol Table");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000971 if (Handler) Handler->handleValueSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000972}
973
Reid Spencer46b002c2004-07-11 17:28:43 +0000974// Parse a single type. The typeid is read in first. If its a primitive type
975// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +0000976// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +0000977// definition.
978const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +0000979 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000980 const Type *Result = 0;
981 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
982 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +0000983
Reid Spencer060d25d2004-06-29 23:29:38 +0000984 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000985 case Type::IntegerTyID: {
986 unsigned NumBits = read_vbr_uint();
987 Result = IntegerType::get(NumBits);
988 break;
989 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000990 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +0000991 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +0000992 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000993
994 unsigned NumParams = read_vbr_uint();
995
996 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +0000997 std::vector<FunctionType::ParameterAttributes> Attrs;
998 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
999 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001000 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001001 if (Params.back() != Type::VoidTy)
1002 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1003 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001004
1005 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1006 if (isVarArg) Params.pop_back();
1007
Reid Spencer88cfda22006-12-31 05:44:24 +00001008 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001009 break;
1010 }
1011 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001012 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001013 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001014 Result = ArrayType::get(ElementType, NumElements);
1015 break;
1016 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001017 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001018 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001019 unsigned NumElements = read_vbr_uint();
1020 Result = PackedType::get(ElementType, NumElements);
1021 break;
1022 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001023 case Type::StructTyID: {
1024 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001025 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001026 while (Typ) { // List is terminated by void/0 typeid
1027 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001028 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001029 }
1030
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001031 Result = StructType::get(Elements, false);
1032 break;
1033 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001034 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001035 std::vector<const Type*> Elements;
1036 unsigned Typ = read_vbr_uint();
1037 while (Typ) { // List is terminated by void/0 typeid
1038 Elements.push_back(getType(Typ));
1039 Typ = read_vbr_uint();
1040 }
1041
1042 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001043 break;
1044 }
1045 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001046 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001047 break;
1048 }
1049
1050 case Type::OpaqueTyID: {
1051 Result = OpaqueType::get();
1052 break;
1053 }
1054
1055 default:
Reid Spencer24399722004-07-09 22:21:33 +00001056 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001057 break;
1058 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001059 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001060 return Result;
1061}
1062
Reid Spencer5b472d92004-08-21 20:49:23 +00001063// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001064// types. We know that recursive types will only reference the current slab of
1065// values in the type plane, but they can forward reference types before they
1066// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1067// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1068// this ugly problem, we pessimistically insert an opaque type for each type we
1069// are about to read. This means that forward references will resolve to
1070// something and when we reread the type later, we can replace the opaque type
1071// with a new resolved concrete type.
1072//
Reid Spencer46b002c2004-07-11 17:28:43 +00001073void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001074 assert(Tab.size() == 0 && "should not have read type constants in before!");
1075
1076 // Insert a bunch of opaque types to be resolved later...
1077 Tab.reserve(NumEntries);
1078 for (unsigned i = 0; i != NumEntries; ++i)
1079 Tab.push_back(OpaqueType::get());
1080
Misha Brukman8a96c532005-04-21 21:44:41 +00001081 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001082 Handler->handleTypeList(NumEntries);
1083
Chris Lattnereebac5f2005-10-03 21:26:53 +00001084 // If we are about to resolve types, make sure the type cache is clear.
1085 if (NumEntries)
1086 ModuleTypeIDCache.clear();
1087
Reid Spencer060d25d2004-06-29 23:29:38 +00001088 // Loop through reading all of the types. Forward types will make use of the
1089 // opaque types just inserted.
1090 //
1091 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001092 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001093 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001094 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001095 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001096
Misha Brukman8a96c532005-04-21 21:44:41 +00001097 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001098 // the opaque type we previously inserted with the new concrete value. This
1099 // approach helps with forward references to types. The refinement from the
1100 // abstract (opaque) type to the new type causes all uses of the abstract
1101 // type to use the concrete type (NewTy). This will also cause the opaque
1102 // type to be deleted.
1103 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1104
1105 // This should have replaced the old opaque type with the new type in the
1106 // value table... or with a preexisting type that was already in the system.
1107 // Let's just make sure it did.
1108 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1109 }
1110}
1111
Reid Spencer04cde2c2004-07-04 11:33:49 +00001112/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001113Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001114 // We must check for a ConstantExpr before switching by type because
1115 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001116 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001117 // 0 if not expr; numArgs if is expr
1118 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001119
Reid Spencer060d25d2004-06-29 23:29:38 +00001120 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001121 // 'undef' is encoded with 'exprnumargs' == 1.
1122 if (isExprNumArgs == 1)
1123 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001124
Reid Spencerd798a512006-11-14 04:47:22 +00001125 // Inline asm is encoded with exprnumargs == ~0U.
1126 if (isExprNumArgs == ~0U) {
1127 std::string AsmStr = read_str();
1128 std::string ConstraintStr = read_str();
1129 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001130
Reid Spencerd798a512006-11-14 04:47:22 +00001131 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1132 const FunctionType *FTy =
1133 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1134
1135 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1136 error("Invalid constraints for inline asm");
1137 if (Flags & ~1U)
1138 error("Invalid flags for inline asm");
1139 bool HasSideEffects = Flags & 1;
1140 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001141 }
Reid Spencerd798a512006-11-14 04:47:22 +00001142
1143 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001144
Reid Spencer060d25d2004-06-29 23:29:38 +00001145 // FIXME: Encoding of constant exprs could be much more compact!
Chris Lattner670ccfe2007-02-07 05:15:28 +00001146 SmallVector<Constant*, 8> ArgVec;
Reid Spencer060d25d2004-06-29 23:29:38 +00001147 ArgVec.reserve(isExprNumArgs);
1148 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001149
Reid Spencer060d25d2004-06-29 23:29:38 +00001150 // Read the slot number and types of each of the arguments
1151 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1152 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001153 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001154
Reid Spencer060d25d2004-06-29 23:29:38 +00001155 // Get the arg value from its slot if it exists, otherwise a placeholder
1156 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1157 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001158
Reid Spencer060d25d2004-06-29 23:29:38 +00001159 // Construct a ConstantExpr of the appropriate kind
1160 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001161 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001162 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001163
Reid Spencera77fa7e2006-12-11 23:20:20 +00001164 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1165 getType(TypeID));
Chris Lattner63cf59e2007-02-07 05:08:39 +00001166 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1167 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001168 return Result;
1169 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
Chris Lattnere0135402007-01-31 04:43:46 +00001170 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], &ArgVec[1],
1171 ArgVec.size()-1);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001172 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1173 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001174 return Result;
1175 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001176 if (ArgVec.size() != 3)
1177 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001178 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001179 ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001180 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1181 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001182 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001183 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001184 if (ArgVec.size() != 2 ||
1185 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1186 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001187 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001188 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1189 ArgVec.size(), Result);
Robert Bocchinofee31b32006-01-10 19:04:39 +00001190 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001191 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001192 if (ArgVec.size() != 3 ||
1193 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1194 error("Invalid insertelement constand expr arguments");
1195
1196 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001197 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001198 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1199 ArgVec.size(), Result);
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001200 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001201 } else if (Opcode == Instruction::ShuffleVector) {
1202 if (ArgVec.size() != 3 ||
1203 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001204 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001205 Constant *Result =
1206 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001207 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1208 ArgVec.size(), Result);
Chris Lattner30b44b62006-04-08 01:17:59 +00001209 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001210 } else if (Opcode == Instruction::ICmp) {
1211 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001212 error("Invalid ICmp constant expr arguments.");
1213 unsigned predicate = read_vbr_uint();
1214 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001215 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1216 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001217 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001218 } else if (Opcode == Instruction::FCmp) {
1219 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001220 error("Invalid FCmp constant expr arguments.");
1221 unsigned predicate = read_vbr_uint();
1222 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001223 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1224 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001225 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001226 } else { // All other 2-operand expressions
1227 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001228 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1229 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001230 return Result;
1231 }
1232 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001233
Reid Spencer060d25d2004-06-29 23:29:38 +00001234 // Ok, not an ConstantExpr. We now know how to read the given type...
1235 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001236 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001237 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001238 case Type::IntegerTyID: {
1239 const IntegerType *IT = cast<IntegerType>(Ty);
1240 if (IT->getBitWidth() <= 32) {
1241 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001242 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1243 error("Integer value read is invalid for type.");
1244 Result = ConstantInt::get(IT, Val);
1245 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001246 } else if (IT->getBitWidth() <= 64) {
1247 uint64_t Val = read_vbr_uint64();
1248 if (!ConstantInt::isValueValidForType(Ty, Val))
1249 error("Invalid constant integer read.");
1250 Result = ConstantInt::get(IT, Val);
1251 if (Handler) Handler->handleConstantValue(Result);
1252 } else
1253 assert("Integer types > 64 bits not supported");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001254 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001255 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001256 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001257 float Val;
1258 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001259 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001260 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001261 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001262 }
1263
1264 case Type::DoubleTyID: {
1265 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001266 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001267 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001268 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001269 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001270 }
1271
Reid Spencer060d25d2004-06-29 23:29:38 +00001272 case Type::ArrayTyID: {
1273 const ArrayType *AT = cast<ArrayType>(Ty);
1274 unsigned NumElements = AT->getNumElements();
1275 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1276 std::vector<Constant*> Elements;
1277 Elements.reserve(NumElements);
1278 while (NumElements--) // Read all of the elements of the constant.
1279 Elements.push_back(getConstantValue(TypeSlot,
1280 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001281 Result = ConstantArray::get(AT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001282 if (Handler) Handler->handleConstantArray(AT, &Elements[0], Elements.size(),
1283 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001284 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001285 }
1286
1287 case Type::StructTyID: {
1288 const StructType *ST = cast<StructType>(Ty);
1289
1290 std::vector<Constant *> Elements;
1291 Elements.reserve(ST->getNumElements());
1292 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1293 Elements.push_back(getConstantValue(ST->getElementType(i),
1294 read_vbr_uint()));
1295
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001296 Result = ConstantStruct::get(ST, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001297 if (Handler) Handler->handleConstantStruct(ST, &Elements[0],Elements.size(),
1298 Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001299 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001300 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001301
Brian Gaeke715c90b2004-08-20 06:00:58 +00001302 case Type::PackedTyID: {
1303 const PackedType *PT = cast<PackedType>(Ty);
1304 unsigned NumElements = PT->getNumElements();
1305 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1306 std::vector<Constant*> Elements;
1307 Elements.reserve(NumElements);
1308 while (NumElements--) // Read all of the elements of the constant.
1309 Elements.push_back(getConstantValue(TypeSlot,
1310 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001311 Result = ConstantPacked::get(PT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001312 if (Handler) Handler->handleConstantPacked(PT, &Elements[0],Elements.size(),
1313 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001314 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001315 }
1316
Chris Lattner638c3812004-11-19 16:24:05 +00001317 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001318 const PointerType *PT = cast<PointerType>(Ty);
1319 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001320
Reid Spencer060d25d2004-06-29 23:29:38 +00001321 // Check to see if we have already read this global variable...
1322 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001323 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001324 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1325 if (!GV) error("GlobalValue not in ValueTable!");
1326 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1327 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001328 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001329 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001330 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001331 }
1332
1333 default:
Reid Spencer24399722004-07-09 22:21:33 +00001334 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001335 Ty->getDescription());
1336 break;
1337 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001338
1339 // Check that we didn't read a null constant if they are implicit for this
1340 // type plane. Do not do this check for constantexprs, as they may be folded
1341 // to a null value in a way that isn't predicted when a .bc file is initially
1342 // produced.
1343 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1344 !hasImplicitNull(TypeID) &&
1345 "Cannot read null values from bytecode!");
1346 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001347}
1348
Misha Brukman8a96c532005-04-21 21:44:41 +00001349/// Resolve references for constants. This function resolves the forward
1350/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001351/// replaceAllUsesWith method of Value class to substitute the placeholder
1352/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001353void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1354 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001355 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001356 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001357 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001358
Chris Lattner29b789b2003-11-19 17:27:18 +00001359 Value *PH = I->second; // Get the placeholder...
1360 PH->replaceAllUsesWith(NewV);
1361 delete PH; // Delete the old placeholder
1362 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001363}
1364
Reid Spencer04cde2c2004-07-04 11:33:49 +00001365/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001366void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1367 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001368 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001369 const Type *Ty = getType(Typ);
1370 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001371 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001372
Reid Spencer060d25d2004-06-29 23:29:38 +00001373 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001374 if (ATy->getElementType() != Type::Int8Ty &&
1375 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001376 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001377
Reid Spencer060d25d2004-06-29 23:29:38 +00001378 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001379 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001380 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001381
Reid Spencer060d25d2004-06-29 23:29:38 +00001382 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001383 const Type* ElemType = ATy->getElementType();
1384 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1385 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001386
Reid Spencer060d25d2004-06-29 23:29:38 +00001387 // Create the constant, inserting it as needed.
1388 Constant *C = ConstantArray::get(ATy, Elements);
1389 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001390 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001391 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001392 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001393}
1394
Reid Spencer04cde2c2004-07-04 11:33:49 +00001395/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001396void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001397 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001398 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001399 if (Handler) Handler->handleGlobalConstantsBegin();
1400
1401 /// In LLVM 1.3 Type does not derive from Value so the types
1402 /// do not occupy a plane. Consequently, we read the types
1403 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001404 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001405 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001406 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001407 }
1408
Reid Spencer46b002c2004-07-11 17:28:43 +00001409 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001410 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001411 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001412
Reid Spencerd798a512006-11-14 04:47:22 +00001413 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001414 /// Use of Type::VoidTyID is a misnomer. It actually means
1415 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001416 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1417 ParseStringConstants(NumEntries, Tab);
1418 } else {
1419 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001420 Value *V = ParseConstantPoolValue(Typ);
1421 assert(V && "ParseConstantPoolValue returned NULL!");
1422 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001423
Reid Spencer060d25d2004-06-29 23:29:38 +00001424 // If we are reading a function constant table, make sure that we adjust
1425 // the slot number to be the real global constant number.
1426 //
1427 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1428 ModuleValues[Typ])
1429 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001430 if (Constant *C = dyn_cast<Constant>(V))
1431 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001432 }
1433 }
1434 }
Chris Lattner02dce162004-12-04 05:28:27 +00001435
1436 // After we have finished parsing the constant pool, we had better not have
1437 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001438 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001439 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001440 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001441 error(utostr(ConstantFwdRefs.size()) +
1442 " unresolved constant reference exist. First one is '" +
1443 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001444 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001445 }
Chris Lattner02dce162004-12-04 05:28:27 +00001446
Reid Spencer060d25d2004-06-29 23:29:38 +00001447 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001448 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001449}
Chris Lattner00950542001-06-06 20:29:01 +00001450
Reid Spencer04cde2c2004-07-04 11:33:49 +00001451/// Parse the contents of a function. Note that this function can be
1452/// called lazily by materializeFunction
1453/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001454void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001455
1456 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001457 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001458 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001459
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001460 unsigned rWord = read_vbr_uint();
1461 unsigned LinkageID = rWord & 65535;
1462 unsigned VisibilityID = rWord >> 16;
1463 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001464 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1465 case 1: Linkage = GlobalValue::WeakLinkage; break;
1466 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1467 case 3: Linkage = GlobalValue::InternalLinkage; break;
1468 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001469 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1470 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1471 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001472 default:
Reid Spencer24399722004-07-09 22:21:33 +00001473 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001474 Linkage = GlobalValue::InternalLinkage;
1475 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001476 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001477 switch (VisibilityID) {
1478 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1479 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1480 default:
1481 error("Unknown visibility type: " + utostr(VisibilityID));
1482 Visibility = GlobalValue::DefaultVisibility;
1483 break;
1484 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001485
Reid Spencer46b002c2004-07-11 17:28:43 +00001486 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001487 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001488 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001489
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001490 // Keep track of how many basic blocks we have read in...
1491 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001492 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001493
Reid Spencer060d25d2004-06-29 23:29:38 +00001494 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001495 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001496 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001497 BufPtr OldAt = At;
1498 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001499
1500 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001501 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001502 if (!InsertedArguments) {
1503 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001504 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001505 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001506 InsertedArguments = true;
1507 }
1508
Reid Spencer04cde2c2004-07-04 11:33:49 +00001509 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001510 break;
1511
Reid Spencerad89bd62004-07-25 18:07:36 +00001512 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001513 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001514 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001515 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001516 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001517 InsertedArguments = true;
1518 }
1519
Misha Brukman8a96c532005-04-21 21:44:41 +00001520 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001521 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001522 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001523 break;
1524 }
1525
Reid Spencer78d033e2007-01-06 07:24:44 +00001526 case BytecodeFormat::ValueSymbolTableBlockID:
1527 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1528 break;
1529
1530 case BytecodeFormat::TypeSymbolTableBlockID:
1531 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001532 break;
1533
1534 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001535 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001536 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001537 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001538 break;
1539 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001540 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001541 }
1542
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001543 // Make sure there were no references to non-existant basic blocks.
1544 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001545 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001546
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001547 ParsedBasicBlocks.clear();
1548
Chris Lattner97330cf2003-10-09 23:10:14 +00001549 // Resolve forward references. Replace any uses of a forward reference value
1550 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001551 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001552 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1553 I = ForwardReferences.begin();
1554 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001555 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001556 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001557 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001558 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001559 }
Chris Lattner00950542001-06-06 20:29:01 +00001560
Misha Brukman12c29d12003-09-22 23:38:23 +00001561 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001562 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001563 freeTable(FunctionValues);
1564
Reid Spencer04cde2c2004-07-04 11:33:49 +00001565 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001566}
1567
Reid Spencer04cde2c2004-07-04 11:33:49 +00001568/// This function parses LLVM functions lazily. It obtains the type of the
1569/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001570/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001571/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001572void BytecodeReader::ParseFunctionLazily() {
1573 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001574 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001575
Reid Spencer060d25d2004-06-29 23:29:38 +00001576 Function *Func = FunctionSignatureList.back();
1577 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001578
Reid Spencer060d25d2004-06-29 23:29:38 +00001579 // Save the information for future reading of the function
1580 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001581
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001582 // This function has a body but it's not loaded so it appears `External'.
1583 // Mark it as a `Ghost' instead to notify the users that it has a body.
1584 Func->setLinkage(GlobalValue::GhostLinkage);
1585
Reid Spencer060d25d2004-06-29 23:29:38 +00001586 // Pretend we've `parsed' this function
1587 At = BlockEnd;
1588}
Chris Lattner89e02532004-01-18 21:08:15 +00001589
Misha Brukman8a96c532005-04-21 21:44:41 +00001590/// The ParserFunction method lazily parses one function. Use this method to
1591/// casue the parser to parse a specific function in the module. Note that
1592/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001593/// ParseAllFunctionBodies.
1594/// @see ParseAllFunctionBodies
1595/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001596bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1597
Reid Spencer9b84ad12006-12-15 19:49:23 +00001598 if (setjmp(context)) {
1599 // Set caller's error message, if requested
1600 if (ErrMsg)
1601 *ErrMsg = ErrorMsg;
1602 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001603 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001604 }
Reid Spencer99655e12006-08-25 19:54:53 +00001605
Reid Spencer060d25d2004-06-29 23:29:38 +00001606 // Find {start, end} pointers and slot in the map. If not there, we're done.
1607 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001608
Reid Spencer060d25d2004-06-29 23:29:38 +00001609 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001610 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001611 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001612 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001613 }
1614
Reid Spencer060d25d2004-06-29 23:29:38 +00001615 BlockStart = At = Fi->second.Buf;
1616 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001617 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001618
1619 LazyFunctionLoadMap.erase(Fi);
1620
Reid Spencer46b002c2004-07-11 17:28:43 +00001621 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001622 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001623}
1624
Reid Spencer04cde2c2004-07-04 11:33:49 +00001625/// The ParseAllFunctionBodies method parses through all the previously
1626/// unparsed functions in the bytecode file. If you want to completely parse
1627/// a bytecode file, this method should be called after Parsebytecode because
1628/// Parsebytecode only records the locations in the bytecode file of where
1629/// the function definitions are located. This function uses that information
1630/// to materialize the functions.
1631/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001632bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001633 if (setjmp(context)) {
1634 // Set caller's error message, if requested
1635 if (ErrMsg)
1636 *ErrMsg = ErrorMsg;
1637 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001638 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001639 }
Reid Spencer99655e12006-08-25 19:54:53 +00001640
Reid Spencer060d25d2004-06-29 23:29:38 +00001641 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1642 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001643
Reid Spencer46b002c2004-07-11 17:28:43 +00001644 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001645 Function* Func = Fi->first;
1646 BlockStart = At = Fi->second.Buf;
1647 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001648 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001649 ++Fi;
1650 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001651 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001652 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001653}
Chris Lattner89e02532004-01-18 21:08:15 +00001654
Reid Spencer04cde2c2004-07-04 11:33:49 +00001655/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001656void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001657 // Read the number of types
1658 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001659 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001660}
1661
Reid Spencer04cde2c2004-07-04 11:33:49 +00001662/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001663void BytecodeReader::ParseModuleGlobalInfo() {
1664
Reid Spencer04cde2c2004-07-04 11:33:49 +00001665 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001666
Chris Lattner404cddf2005-11-12 01:33:40 +00001667 // SectionID - If a global has an explicit section specified, this map
1668 // remembers the ID until we can translate it into a string.
1669 std::map<GlobalValue*, unsigned> SectionID;
1670
Chris Lattner70cc3392001-09-10 07:58:01 +00001671 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001672 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001673 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001674 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1675 // Linkage, bit4+ = slot#
1676 unsigned SlotNo = VarType >> 5;
1677 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001678 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001679 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001680 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001681 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001682 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001683
1684 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1685 if (LinkageID == 3 && !hasInitializer) {
1686 unsigned ExtWord = read_vbr_uint();
1687 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001688 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1689 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001690 hasInitializer = ExtWord & 1;
1691 LinkageID = (ExtWord >> 1) & 7;
1692 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001693 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001694
1695 if (ExtWord & (1 << 9)) // Has a section ID.
1696 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001697 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001698
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001699 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001700 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001701 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1702 case 1: Linkage = GlobalValue::WeakLinkage; break;
1703 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1704 case 3: Linkage = GlobalValue::InternalLinkage; break;
1705 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001706 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1707 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1708 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001709 default:
Reid Spencer24399722004-07-09 22:21:33 +00001710 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001711 Linkage = GlobalValue::InternalLinkage;
1712 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001713 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001714 GlobalValue::VisibilityTypes Visibility;
1715 switch (VisibilityID) {
1716 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1717 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1718 default:
1719 error("Unknown visibility type: " + utostr(VisibilityID));
1720 Visibility = GlobalValue::DefaultVisibility;
1721 break;
1722 }
1723
Chris Lattnere3869c82003-04-16 21:16:05 +00001724 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001725 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001726 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001727
Chris Lattnere73bd452005-11-06 07:43:39 +00001728 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001729 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001730
Chris Lattner52e20b02003-03-19 20:54:26 +00001731 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001732
Chris Lattner70cc3392001-09-10 07:58:01 +00001733 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001734 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001735 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001736 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001737 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001738 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001739
Chris Lattner404cddf2005-11-12 01:33:40 +00001740 if (GlobalSectionID != 0)
1741 SectionID[GV] = GlobalSectionID;
1742
Reid Spencer060d25d2004-06-29 23:29:38 +00001743 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001744 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001745 initSlot = read_vbr_uint();
1746 GlobalInits.push_back(std::make_pair(GV, initSlot));
1747 }
1748
1749 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001750 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001751 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1752 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001753
1754 // Get next item
1755 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001756 }
1757
Chris Lattner52e20b02003-03-19 20:54:26 +00001758 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001759 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001760
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001761 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001762 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1763 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001764 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001765 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001766 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001767 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001768 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001769
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001770 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001771 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001772 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001773
Chris Lattner18549c22004-11-15 21:43:03 +00001774 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001775 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001776 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001777
Chris Lattnere73bd452005-11-06 07:43:39 +00001778 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001779
1780 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001781 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001782
Chris Lattner97fbc502004-11-15 22:38:52 +00001783 // Save this for later so we know type of lazily instantiated functions.
1784 // Note that known-external functions do not have FunctionInfo blocks, so we
1785 // do not add them to the FunctionSignatureList.
1786 if ((Flags & (1 << 4)) == 0)
1787 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001788
Chris Lattnere73bd452005-11-06 07:43:39 +00001789 // Get the calling convention from the low bits.
1790 unsigned CC = Flags & 15;
1791 unsigned Alignment = 0;
1792 if (FnSignature & (1 << 31)) { // Has extension word?
1793 unsigned ExtWord = read_vbr_uint();
1794 Alignment = (1 << (ExtWord & 31)) >> 1;
1795 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001796
1797 if (ExtWord & (1 << 10)) // Has a section ID.
1798 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001799
1800 // Parse external declaration linkage
1801 switch ((ExtWord >> 11) & 3) {
1802 case 0: break;
1803 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1804 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1805 default: assert(0 && "Unsupported external linkage");
1806 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001807 }
1808
Chris Lattner54b369e2005-11-06 07:46:13 +00001809 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001810 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001811
Reid Spencer04cde2c2004-07-04 11:33:49 +00001812 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001813
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001814 // Get the next function signature.
1815 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001816 }
1817
Misha Brukman8a96c532005-04-21 21:44:41 +00001818 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001819 // remove elements efficiently from the back of the vector.
1820 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001821
Chris Lattner404cddf2005-11-12 01:33:40 +00001822 /// SectionNames - This contains the list of section names encoded in the
1823 /// moduleinfoblock. Functions and globals with an explicit section index
1824 /// into this to get their section name.
1825 std::vector<std::string> SectionNames;
1826
Reid Spencerd798a512006-11-14 04:47:22 +00001827 // Read in the dependent library information.
1828 unsigned num_dep_libs = read_vbr_uint();
1829 std::string dep_lib;
1830 while (num_dep_libs--) {
1831 dep_lib = read_str();
1832 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001833 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001834 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001835 }
1836
Reid Spencerd798a512006-11-14 04:47:22 +00001837 // Read target triple and place into the module.
1838 std::string triple = read_str();
1839 TheModule->setTargetTriple(triple);
1840 if (Handler)
1841 Handler->handleTargetTriple(triple);
1842
Reid Spenceraacc35a2007-01-26 08:10:24 +00001843 // Read the data layout string and place into the module.
1844 std::string datalayout = read_str();
1845 TheModule->setDataLayout(datalayout);
1846 // FIXME: Implement
1847 // if (Handler)
1848 // Handler->handleDataLayout(datalayout);
1849
Reid Spencerd798a512006-11-14 04:47:22 +00001850 if (At != BlockEnd) {
1851 // If the file has section info in it, read the section names now.
1852 unsigned NumSections = read_vbr_uint();
1853 while (NumSections--)
1854 SectionNames.push_back(read_str());
1855 }
1856
1857 // If the file has module-level inline asm, read it now.
1858 if (At != BlockEnd)
1859 TheModule->setModuleInlineAsm(read_str());
1860
Chris Lattner404cddf2005-11-12 01:33:40 +00001861 // If any globals are in specified sections, assign them now.
1862 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1863 SectionID.end(); I != E; ++I)
1864 if (I->second) {
1865 if (I->second > SectionID.size())
1866 error("SectionID out of range for global!");
1867 I->first->setSection(SectionNames[I->second-1]);
1868 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001869
Chris Lattner00950542001-06-06 20:29:01 +00001870 // This is for future proofing... in the future extra fields may be added that
1871 // we don't understand, so we transparently ignore them.
1872 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001873 At = BlockEnd;
1874
Reid Spencer04cde2c2004-07-04 11:33:49 +00001875 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001876}
1877
Reid Spencer04cde2c2004-07-04 11:33:49 +00001878/// Parse the version information and decode it by setting flags on the
1879/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001880void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001881 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001882
Reid Spencer3795ad12006-12-03 05:47:10 +00001883 // We don't provide backwards compatibility in the Reader any more. To
1884 // upgrade, the user should use llvm-upgrade.
1885 if (RevisionNum < 7)
1886 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001887
Reid Spenceraacc35a2007-01-26 08:10:24 +00001888 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001889}
1890
Reid Spencer04cde2c2004-07-04 11:33:49 +00001891/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001892void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001893 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001894
Reid Spencer060d25d2004-06-29 23:29:38 +00001895 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001896
1897 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001898 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001899
Reid Spencer060d25d2004-06-29 23:29:38 +00001900 bool SeenModuleGlobalInfo = false;
1901 bool SeenGlobalTypePlane = false;
1902 BufPtr MyEnd = BlockEnd;
1903 while (At < MyEnd) {
1904 BufPtr OldAt = At;
1905 read_block(Type, Size);
1906
Chris Lattner00950542001-06-06 20:29:01 +00001907 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001908
Reid Spencerad89bd62004-07-25 18:07:36 +00001909 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001910 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001911 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001912
Reid Spencer5b472d92004-08-21 20:49:23 +00001913 if (Size > 0)
1914 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001915 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001916 break;
1917
Misha Brukman8a96c532005-04-21 21:44:41 +00001918 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001919 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001920 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001921 ParseModuleGlobalInfo();
1922 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001923 break;
1924
Reid Spencerad89bd62004-07-25 18:07:36 +00001925 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001926 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001927 break;
1928
Reid Spencerad89bd62004-07-25 18:07:36 +00001929 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001930 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001931 break;
Chris Lattner00950542001-06-06 20:29:01 +00001932
Reid Spencer78d033e2007-01-06 07:24:44 +00001933 case BytecodeFormat::ValueSymbolTableBlockID:
1934 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1935 break;
1936
1937 case BytecodeFormat::TypeSymbolTableBlockID:
1938 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001939 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001940
Chris Lattner00950542001-06-06 20:29:01 +00001941 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001942 At += Size;
1943 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001944 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001945 }
Chris Lattner00950542001-06-06 20:29:01 +00001946 break;
1947 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001948 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001949 }
1950
Chris Lattner52e20b02003-03-19 20:54:26 +00001951 // After the module constant pool has been read, we can safely initialize
1952 // global variables...
1953 while (!GlobalInits.empty()) {
1954 GlobalVariable *GV = GlobalInits.back().first;
1955 unsigned Slot = GlobalInits.back().second;
1956 GlobalInits.pop_back();
1957
1958 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001959 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001960
1961 const llvm::PointerType* GVType = GV->getType();
1962 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001963 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001964 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001965 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001966 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001967 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001968 } else
Reid Spencer24399722004-07-09 22:21:33 +00001969 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001970 }
1971
Chris Lattneraba5ff52005-05-05 20:57:00 +00001972 if (!ConstantFwdRefs.empty())
1973 error("Use of undefined constants in a module");
1974
Reid Spencer060d25d2004-06-29 23:29:38 +00001975 /// Make sure we pulled them all out. If we didn't then there's a declaration
1976 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001977 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001978 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001979}
1980
Reid Spencer04cde2c2004-07-04 11:33:49 +00001981/// This function completely parses a bytecode buffer given by the \p Buf
1982/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00001983bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00001984 const std::string &ModuleID,
1985 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.
2024 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2025 (char*)Buf+4,Length-4,decompressedBlock);
2026
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