blob: e2505cc81e8b6a261e0e3c08a61857bdb4803a66 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000024#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000025#include "llvm/Instructions.h"
26#include "llvm/SymbolTable.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000027#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Chris Lattner4c3d3a92007-01-31 19:56:15 +000033#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000035#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000036#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Reid Spencer46b002c2004-07-11 17:28:43 +000039namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000040 /// @brief A class for maintaining the slot number definition
41 /// as a placeholder for the actual definition for forward constants defs.
42 class ConstantPlaceHolder : public ConstantExpr {
43 ConstantPlaceHolder(); // DO NOT IMPLEMENT
44 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
45 public:
Chris Lattner61323322005-01-31 01:11:13 +000046 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000047 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000048 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000049 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000050 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000051 };
Reid Spencer46b002c2004-07-11 17:28:43 +000052}
Reid Spencer060d25d2004-06-29 23:29:38 +000053
Reid Spencer24399722004-07-09 22:21:33 +000054// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000055inline void BytecodeReader::error(const std::string& err) {
56 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
57 + itostr(At-MemStart) + ")";
58 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;
89 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +000090
Reid Spencer060d25d2004-06-29 23:29:38 +000091 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000092 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000093 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000094 Result |= (unsigned)((*At++) & 0x7F) << Shift;
95 Shift += 7;
96 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +000097 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000098 return Result;
99}
100
Reid Spencer04cde2c2004-07-04 11:33:49 +0000101/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000102inline uint64_t BytecodeReader::read_vbr_uint64() {
103 unsigned Shift = 0;
104 uint64_t Result = 0;
105 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000106
Reid Spencer060d25d2004-06-29 23:29:38 +0000107 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000108 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000109 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000110 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
111 Shift += 7;
112 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000113 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000114 return Result;
115}
116
Reid Spencer04cde2c2004-07-04 11:33:49 +0000117/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000118inline int64_t BytecodeReader::read_vbr_int64() {
119 uint64_t R = read_vbr_uint64();
120 if (R & 1) {
121 if (R != 1)
122 return -(int64_t)(R >> 1);
123 else // There is no such thing as -0 with integers. "-0" really means
124 // 0x8000000000000000.
125 return 1LL << 63;
126 } else
127 return (int64_t)(R >> 1);
128}
129
Reid Spencer04cde2c2004-07-04 11:33:49 +0000130/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000131inline std::string BytecodeReader::read_str() {
132 unsigned Size = read_vbr_uint();
133 const unsigned char *OldAt = At;
134 At += Size;
135 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000136 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000137 return std::string((char*)OldAt, Size);
138}
139
Reid Spencer04cde2c2004-07-04 11:33:49 +0000140/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000141inline void BytecodeReader::read_data(void *Ptr, void *End) {
142 unsigned char *Start = (unsigned char *)Ptr;
143 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000144 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000145 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000146 std::copy(At, At+Amount, Start);
147 At += Amount;
148}
149
Reid Spencer46b002c2004-07-11 17:28:43 +0000150/// Read a float value in little-endian order
151inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000154 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000155 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000156}
157
158/// Read a double value in little-endian order
159inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000160 /// FIXME: This isn't optimal, it has size problems on some platforms
161 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000162 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
163 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
164 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
165 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000166 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000167}
168
Reid Spencer04cde2c2004-07-04 11:33:49 +0000169/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000170inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000171 Size = read_uint(); // Read the header
172 Type = Size & 0x1F; // mask low order five bits to get type
173 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000174 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000175 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000176 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000177 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000178 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000179}
180
Reid Spencer060d25d2004-06-29 23:29:38 +0000181//===----------------------------------------------------------------------===//
182// IR Lookup Methods
183//===----------------------------------------------------------------------===//
184
Reid Spencer04cde2c2004-07-04 11:33:49 +0000185/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000186inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000187 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000188}
189
Reid Spencerd2bb8872007-01-30 19:36:46 +0000190/// Obtain a type given a typeid and account for things like function level vs
191/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000192const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000193 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000194 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000195 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000196
197 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000198 ID -= Type::FirstDerivedTyID;
199
Chris Lattner36392bc2003-10-08 21:18:57 +0000200 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000201 if (ID < ModuleTypes.size())
202 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000203
Reid Spencer46b002c2004-07-11 17:28:43 +0000204 // Nope, is it a function-level type?
205 ID -= ModuleTypes.size();
206 if (ID < FunctionTypes.size())
207 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000208
Reid Spencer46b002c2004-07-11 17:28:43 +0000209 error("Illegal type reference!");
210 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000211}
212
Reid Spencer3795ad12006-12-03 05:47:10 +0000213/// This method just saves some coding. It uses read_vbr_uint to read in a
214/// type id, errors that its not the type type, and then calls getType to
215/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000216inline const Type* BytecodeReader::readType() {
217 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000218}
219
220/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000221/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000222unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
223 if (Ty->isPrimitiveType())
224 return Ty->getTypeID();
225
Reid Spencer060d25d2004-06-29 23:29:38 +0000226 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000227 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
228 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000229
230 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000231 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000232 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000233
Chris Lattnereebac5f2005-10-03 21:26:53 +0000234 // If we don't have our cache yet, build it now.
235 if (ModuleTypeIDCache.empty()) {
236 unsigned N = 0;
237 ModuleTypeIDCache.reserve(ModuleTypes.size());
238 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
239 I != E; ++I, ++N)
240 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
241
242 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
243 }
244
245 // Binary search the cache for the entry.
246 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
247 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
248 std::make_pair(Ty, 0U));
249 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000250 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000251
252 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000253}
254
Misha Brukman8a96c532005-04-21 21:44:41 +0000255/// Retrieve a value of a given type and slot number, possibly creating
256/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000257Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000258 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000259 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000260
Reid Spencerd2bb8872007-01-30 19:36:46 +0000261 // By default, the global type id is the type id passed in
262 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000263
Reid Spencerd2bb8872007-01-30 19:36:46 +0000264 if (hasImplicitNull(GlobalTyID)) {
265 const Type *Ty = getType(type);
266 if (!isa<OpaqueType>(Ty)) {
267 if (Num == 0)
268 return Constant::getNullValue(Ty);
269 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000270 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000271 }
Chris Lattner89e02532004-01-18 21:08:15 +0000272
Reid Spencerd2bb8872007-01-30 19:36:46 +0000273 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
274 if (Num < ModuleValues[GlobalTyID]->size())
275 return ModuleValues[GlobalTyID]->getOperand(Num);
276 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner52e20b02003-03-19 20:54:26 +0000277 }
278
Misha Brukman8a96c532005-04-21 21:44:41 +0000279 if (FunctionValues.size() > type &&
280 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000281 Num < FunctionValues[type]->size())
282 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000283
Chris Lattner74734132002-08-17 22:01:27 +0000284 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000285
Reid Spencer551ccae2004-09-01 22:55:40 +0000286 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000287 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000288 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000289 if (I != ForwardReferences.end() && I->first == KeyValue)
290 return I->second; // We have already created this placeholder
291
Reid Spencer551ccae2004-09-01 22:55:40 +0000292 // If the type exists (it should)
293 if (const Type* Ty = getType(type)) {
294 // Create the place holder
295 Value *Val = new Argument(Ty);
296 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
297 return Val;
298 }
Reid Spencer233fe722006-08-22 16:09:19 +0000299 error("Can't create placeholder for value of type slot #" + utostr(type));
300 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000301}
302
Reid Spencer060d25d2004-06-29 23:29:38 +0000303
Reid Spencer04cde2c2004-07-04 11:33:49 +0000304/// Just like getValue, except that it returns a null pointer
305/// only on error. It always returns a constant (meaning that if the value is
306/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000307/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000308/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000309Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
310 if (Value *V = getValue(TypeSlot, Slot, false))
311 if (Constant *C = dyn_cast<Constant>(V))
312 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000313 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000314 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000315 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000316
Chris Lattner389bd042004-12-09 06:19:44 +0000317 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000318 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
319
320 if (I != ConstantFwdRefs.end() && I->first == Key) {
321 return I->second;
322 } else {
323 // Create a placeholder for the constant reference and
324 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000325 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000326
Reid Spencer060d25d2004-06-29 23:29:38 +0000327 // Keep track of the fact that we have a forward ref to recycle it
328 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
329 return C;
330 }
331}
332
333//===----------------------------------------------------------------------===//
334// IR Construction Methods
335//===----------------------------------------------------------------------===//
336
Reid Spencer04cde2c2004-07-04 11:33:49 +0000337/// As values are created, they are inserted into the appropriate place
338/// with this method. The ValueTable argument must be one of ModuleValues
339/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000340unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000341 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000342 if (ValueTab.size() <= type)
343 ValueTab.resize(type+1);
344
345 if (!ValueTab[type]) ValueTab[type] = new ValueList();
346
347 ValueTab[type]->push_back(Val);
348
Chris Lattneraba5ff52005-05-05 20:57:00 +0000349 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000350 return ValueTab[type]->size()-1 + HasOffset;
351}
352
Reid Spencer04cde2c2004-07-04 11:33:49 +0000353/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000354void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000355 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000356 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000357 for (FunctionType::param_iterator It = FT->param_begin();
358 It != FT->param_end(); ++It, ++AI)
359 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
360}
361
362//===----------------------------------------------------------------------===//
363// Bytecode Parsing Methods
364//===----------------------------------------------------------------------===//
365
Reid Spencer04cde2c2004-07-04 11:33:49 +0000366/// This method parses a single instruction. The instruction is
367/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000368/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000369void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000370 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000371 BufPtr SaveAt = At;
372
373 // Clear instruction data
374 Oprnds.clear();
375 unsigned iType = 0;
376 unsigned Opcode = 0;
377 unsigned Op = read_uint();
378
379 // bits Instruction format: Common to all formats
380 // --------------------------
381 // 01-00: Opcode type, fixed to 1.
382 // 07-02: Opcode
383 Opcode = (Op >> 2) & 63;
384 Oprnds.resize((Op >> 0) & 03);
385
386 // Extract the operands
387 switch (Oprnds.size()) {
388 case 1:
389 // bits Instruction format:
390 // --------------------------
391 // 19-08: Resulting type plane
392 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
393 //
394 iType = (Op >> 8) & 4095;
395 Oprnds[0] = (Op >> 20) & 4095;
396 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
397 Oprnds.resize(0);
398 break;
399 case 2:
400 // bits Instruction format:
401 // --------------------------
402 // 15-08: Resulting type plane
403 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000404 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000405 //
406 iType = (Op >> 8) & 255;
407 Oprnds[0] = (Op >> 16) & 255;
408 Oprnds[1] = (Op >> 24) & 255;
409 break;
410 case 3:
411 // bits Instruction format:
412 // --------------------------
413 // 13-08: Resulting type plane
414 // 19-14: Operand #1
415 // 25-20: Operand #2
416 // 31-26: Operand #3
417 //
418 iType = (Op >> 8) & 63;
419 Oprnds[0] = (Op >> 14) & 63;
420 Oprnds[1] = (Op >> 20) & 63;
421 Oprnds[2] = (Op >> 26) & 63;
422 break;
423 case 0:
424 At -= 4; // Hrm, try this again...
425 Opcode = read_vbr_uint();
426 Opcode >>= 2;
427 iType = read_vbr_uint();
428
429 unsigned NumOprnds = read_vbr_uint();
430 Oprnds.resize(NumOprnds);
431
432 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000433 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000434
435 for (unsigned i = 0; i != NumOprnds; ++i)
436 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000437 break;
438 }
439
Reid Spencerd798a512006-11-14 04:47:22 +0000440 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000441
Reid Spencer1628cec2006-10-26 06:15:43 +0000442 // Make the necessary adjustments for dealing with backwards compatibility
443 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000444 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000445
Reid Spencer46b002c2004-07-11 17:28:43 +0000446 // We have enough info to inform the handler now.
Reid Spencer1628cec2006-10-26 06:15:43 +0000447 if (Handler)
448 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000449
Reid Spencer3795ad12006-12-03 05:47:10 +0000450 // First, handle the easy binary operators case
451 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000452 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000453 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
454 getValue(iType, Oprnds[0]),
455 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000456 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000457 // Indicate that we don't think this is a call instruction (yet).
458 // Process based on the Opcode read
459 switch (Opcode) {
460 default: // There was an error, this shouldn't happen.
461 if (Result == 0)
462 error("Illegal instruction read!");
463 break;
464 case Instruction::VAArg:
465 if (Oprnds.size() != 2)
466 error("Invalid VAArg instruction!");
467 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000468 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000469 break;
470 case Instruction::ExtractElement: {
471 if (Oprnds.size() != 2)
472 error("Invalid extractelement instruction!");
473 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000474 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000475
Reid Spencer1628cec2006-10-26 06:15:43 +0000476 if (!ExtractElementInst::isValidOperands(V1, V2))
477 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000478
Reid Spencer1628cec2006-10-26 06:15:43 +0000479 Result = new ExtractElementInst(V1, V2);
480 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000481 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000482 case Instruction::InsertElement: {
483 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
484 if (!PackedTy || Oprnds.size() != 3)
485 error("Invalid insertelement instruction!");
486
487 Value *V1 = getValue(iType, Oprnds[0]);
488 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000489 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000490
491 if (!InsertElementInst::isValidOperands(V1, V2, V3))
492 error("Invalid insertelement instruction!");
493 Result = new InsertElementInst(V1, V2, V3);
494 break;
495 }
496 case Instruction::ShuffleVector: {
497 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
498 if (!PackedTy || Oprnds.size() != 3)
499 error("Invalid shufflevector instruction!");
500 Value *V1 = getValue(iType, Oprnds[0]);
501 Value *V2 = getValue(iType, Oprnds[1]);
502 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000503 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000504 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
505 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
506 error("Invalid shufflevector instruction!");
507 Result = new ShuffleVectorInst(V1, V2, V3);
508 break;
509 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000510 case Instruction::Trunc:
511 if (Oprnds.size() != 2)
512 error("Invalid cast instruction!");
513 Result = new TruncInst(getValue(iType, Oprnds[0]),
514 getType(Oprnds[1]));
515 break;
516 case Instruction::ZExt:
517 if (Oprnds.size() != 2)
518 error("Invalid cast instruction!");
519 Result = new ZExtInst(getValue(iType, Oprnds[0]),
520 getType(Oprnds[1]));
521 break;
522 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000523 if (Oprnds.size() != 2)
524 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000525 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000526 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000527 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000528 case Instruction::FPTrunc:
529 if (Oprnds.size() != 2)
530 error("Invalid cast instruction!");
531 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
532 getType(Oprnds[1]));
533 break;
534 case Instruction::FPExt:
535 if (Oprnds.size() != 2)
536 error("Invalid cast instruction!");
537 Result = new FPExtInst(getValue(iType, Oprnds[0]),
538 getType(Oprnds[1]));
539 break;
540 case Instruction::UIToFP:
541 if (Oprnds.size() != 2)
542 error("Invalid cast instruction!");
543 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
544 getType(Oprnds[1]));
545 break;
546 case Instruction::SIToFP:
547 if (Oprnds.size() != 2)
548 error("Invalid cast instruction!");
549 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
550 getType(Oprnds[1]));
551 break;
552 case Instruction::FPToUI:
553 if (Oprnds.size() != 2)
554 error("Invalid cast instruction!");
555 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
556 getType(Oprnds[1]));
557 break;
558 case Instruction::FPToSI:
559 if (Oprnds.size() != 2)
560 error("Invalid cast instruction!");
561 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
562 getType(Oprnds[1]));
563 break;
564 case Instruction::IntToPtr:
565 if (Oprnds.size() != 2)
566 error("Invalid cast instruction!");
567 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
568 getType(Oprnds[1]));
569 break;
570 case Instruction::PtrToInt:
571 if (Oprnds.size() != 2)
572 error("Invalid cast instruction!");
573 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
574 getType(Oprnds[1]));
575 break;
576 case Instruction::BitCast:
577 if (Oprnds.size() != 2)
578 error("Invalid cast instruction!");
579 Result = new BitCastInst(getValue(iType, Oprnds[0]),
580 getType(Oprnds[1]));
581 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000582 case Instruction::Select:
583 if (Oprnds.size() != 3)
584 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000585 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000586 getValue(iType, Oprnds[1]),
587 getValue(iType, Oprnds[2]));
588 break;
589 case Instruction::PHI: {
590 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
591 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000592
Reid Spencer1628cec2006-10-26 06:15:43 +0000593 PHINode *PN = new PHINode(InstTy);
594 PN->reserveOperandSpace(Oprnds.size());
595 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
596 PN->addIncoming(
597 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
598 Result = PN;
599 break;
600 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000601 case Instruction::ICmp:
602 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000603 if (Oprnds.size() != 3)
604 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000605 // These instructions encode the comparison predicate as the 3rd operand.
606 Result = CmpInst::create(Instruction::OtherOps(Opcode),
607 static_cast<unsigned short>(Oprnds[2]),
608 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
609 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000610 case Instruction::Ret:
611 if (Oprnds.size() == 0)
612 Result = new ReturnInst();
613 else if (Oprnds.size() == 1)
614 Result = new ReturnInst(getValue(iType, Oprnds[0]));
615 else
616 error("Unrecognized instruction!");
617 break;
618
619 case Instruction::Br:
620 if (Oprnds.size() == 1)
621 Result = new BranchInst(getBasicBlock(Oprnds[0]));
622 else if (Oprnds.size() == 3)
623 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000624 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000625 else
626 error("Invalid number of operands for a 'br' instruction!");
627 break;
628 case Instruction::Switch: {
629 if (Oprnds.size() & 1)
630 error("Switch statement with odd number of arguments!");
631
632 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
633 getBasicBlock(Oprnds[1]),
634 Oprnds.size()/2-1);
635 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
636 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
637 getBasicBlock(Oprnds[i+1]));
638 Result = I;
639 break;
640 }
641 case 58: // Call with extra operand for calling conv
642 case 59: // tail call, Fast CC
643 case 60: // normal call, Fast CC
644 case 61: // tail call, C Calling Conv
645 case Instruction::Call: { // Normal Call, C Calling Convention
646 if (Oprnds.size() == 0)
647 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000648 Value *F = getValue(iType, Oprnds[0]);
649
650 unsigned CallingConv = CallingConv::C;
651 bool isTailCall = false;
652
653 if (Opcode == 61 || Opcode == 59)
654 isTailCall = true;
655
656 if (Opcode == 58) {
657 isTailCall = Oprnds.back() & 1;
658 CallingConv = Oprnds.back() >> 1;
659 Oprnds.pop_back();
660 } else if (Opcode == 59 || Opcode == 60) {
661 CallingConv = CallingConv::Fast;
662 }
663
664 // Check to make sure we have a pointer to function type
665 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
666 if (PTy == 0) error("Call to non function pointer value!");
667 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
668 if (FTy == 0) error("Call to non function pointer value!");
669
670 std::vector<Value *> Params;
671 if (!FTy->isVarArg()) {
672 FunctionType::param_iterator It = FTy->param_begin();
673
674 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
675 if (It == FTy->param_end())
676 error("Invalid call instruction!");
677 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
678 }
679 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000680 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000681 } else {
682 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
683
684 unsigned FirstVariableOperand;
685 if (Oprnds.size() < FTy->getNumParams())
686 error("Call instruction missing operands!");
687
688 // Read all of the fixed arguments
689 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
690 Params.push_back(
691 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
692
693 FirstVariableOperand = FTy->getNumParams();
694
695 if ((Oprnds.size()-FirstVariableOperand) & 1)
696 error("Invalid call instruction!"); // Must be pairs of type/value
697
698 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
699 i != e; i += 2)
700 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000701 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000702
Reid Spencer1628cec2006-10-26 06:15:43 +0000703 Result = new CallInst(F, Params);
704 if (isTailCall) cast<CallInst>(Result)->setTailCall();
705 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
706 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000707 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000708 case Instruction::Invoke: { // Invoke C CC
709 if (Oprnds.size() < 3)
710 error("Invalid invoke instruction!");
711 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000712
Reid Spencer1628cec2006-10-26 06:15:43 +0000713 // Check to make sure we have a pointer to function type
714 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
715 if (PTy == 0)
716 error("Invoke to non function pointer value!");
717 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
718 if (FTy == 0)
719 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000720
Reid Spencer1628cec2006-10-26 06:15:43 +0000721 std::vector<Value *> Params;
722 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000723 unsigned CallingConv = Oprnds.back();
724 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000725
Reid Spencer1628cec2006-10-26 06:15:43 +0000726 if (!FTy->isVarArg()) {
727 Normal = getBasicBlock(Oprnds[1]);
728 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000729
Reid Spencer1628cec2006-10-26 06:15:43 +0000730 FunctionType::param_iterator It = FTy->param_begin();
731 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
732 if (It == FTy->param_end())
733 error("Invalid invoke instruction!");
734 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
735 }
736 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000737 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000738 } else {
739 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
740
741 Normal = getBasicBlock(Oprnds[0]);
742 Except = getBasicBlock(Oprnds[1]);
743
744 unsigned FirstVariableArgument = FTy->getNumParams()+2;
745 for (unsigned i = 2; i != FirstVariableArgument; ++i)
746 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
747 Oprnds[i]));
748
749 // Must be type/value pairs. If not, error out.
750 if (Oprnds.size()-FirstVariableArgument & 1)
751 error("Invalid invoke instruction!");
752
753 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
754 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000755 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000756
Reid Spencer1628cec2006-10-26 06:15:43 +0000757 Result = new InvokeInst(F, Normal, Except, Params);
758 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
759 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000760 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000761 case Instruction::Malloc: {
762 unsigned Align = 0;
763 if (Oprnds.size() == 2)
764 Align = (1 << Oprnds[1]) >> 1;
765 else if (Oprnds.size() > 2)
766 error("Invalid malloc instruction!");
767 if (!isa<PointerType>(InstTy))
768 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000769
Reid Spencer1628cec2006-10-26 06:15:43 +0000770 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000771 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000772 break;
773 }
774 case Instruction::Alloca: {
775 unsigned Align = 0;
776 if (Oprnds.size() == 2)
777 Align = (1 << Oprnds[1]) >> 1;
778 else if (Oprnds.size() > 2)
779 error("Invalid alloca instruction!");
780 if (!isa<PointerType>(InstTy))
781 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000782
Reid Spencer1628cec2006-10-26 06:15:43 +0000783 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000784 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000785 break;
786 }
787 case Instruction::Free:
788 if (!isa<PointerType>(InstTy))
789 error("Invalid free instruction!");
790 Result = new FreeInst(getValue(iType, Oprnds[0]));
791 break;
792 case Instruction::GetElementPtr: {
793 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000794 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000795
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000796 SmallVector<Value*, 8> Idx;
Reid Spencer1628cec2006-10-26 06:15:43 +0000797
798 const Type *NextTy = InstTy;
799 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
800 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
801 if (!TopTy)
802 error("Invalid getelementptr instruction!");
803
804 unsigned ValIdx = Oprnds[i];
805 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000806 // Struct indices are always uints, sequential type indices can be
807 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000808 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000809 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000810 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000811 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000812 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000813 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000814 case 0: IdxTy = Int32TySlot; break;
815 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000816 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000817 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000818 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000819 Idx.push_back(getValue(IdxTy, ValIdx));
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000820 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
821 true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000822 }
823
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000824 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
825 &Idx[0], Idx.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000826 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000827 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000828 case 62: // volatile load
829 case Instruction::Load:
830 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
831 error("Invalid load instruction!");
832 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
833 break;
834 case 63: // volatile store
835 case Instruction::Store: {
836 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
837 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000838
Reid Spencer1628cec2006-10-26 06:15:43 +0000839 Value *Ptr = getValue(iType, Oprnds[1]);
840 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
841 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
842 Opcode == 63);
843 break;
844 }
845 case Instruction::Unwind:
846 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
847 Result = new UnwindInst();
848 break;
849 case Instruction::Unreachable:
850 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
851 Result = new UnreachableInst();
852 break;
853 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000854 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000855
Reid Spencere1e96c02006-01-19 07:02:16 +0000856 BB->getInstList().push_back(Result);
857
Reid Spencer060d25d2004-06-29 23:29:38 +0000858 unsigned TypeSlot;
859 if (Result->getType() == InstTy)
860 TypeSlot = iType;
861 else
862 TypeSlot = getTypeSlot(Result->getType());
863
864 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000865}
866
Reid Spencer04cde2c2004-07-04 11:33:49 +0000867/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000868/// This works together with ParseInstructionList to handle these forward
869/// references in a clean manner. This function is used when constructing
870/// phi, br, switch, and other instructions that reference basic blocks.
871/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000872BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000873 // Make sure there is room in the table...
874 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
875
Reid Spencerd798a512006-11-14 04:47:22 +0000876 // First check to see if this is a backwards reference, i.e. this block
877 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000878 // been created.
879 if (ParsedBasicBlocks[ID])
880 return ParsedBasicBlocks[ID];
881
882 // Otherwise, the basic block has not yet been created. Do so and add it to
883 // the ParsedBasicBlocks list.
884 return ParsedBasicBlocks[ID] = new BasicBlock();
885}
886
Reid Spencer04cde2c2004-07-04 11:33:49 +0000887/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000888/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000889/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000890/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000891unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000892 unsigned BlockNo = 0;
893 std::vector<unsigned> Args;
894
Reid Spencer46b002c2004-07-11 17:28:43 +0000895 while (moreInBlock()) {
896 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000897 BasicBlock *BB;
898 if (ParsedBasicBlocks.size() == BlockNo)
899 ParsedBasicBlocks.push_back(BB = new BasicBlock());
900 else if (ParsedBasicBlocks[BlockNo] == 0)
901 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
902 else
903 BB = ParsedBasicBlocks[BlockNo];
904 ++BlockNo;
905 F->getBasicBlockList().push_back(BB);
906
907 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000908 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000909 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000910
911 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000912 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000913
Reid Spencer46b002c2004-07-11 17:28:43 +0000914 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000915 }
916
917 return BlockNo;
918}
919
Reid Spencer78d033e2007-01-06 07:24:44 +0000920/// Parse a type symbol table.
921void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
922 // Type Symtab block header: [num entries]
923 unsigned NumEntries = read_vbr_uint();
924 for (unsigned i = 0; i < NumEntries; ++i) {
925 // Symtab entry: [type slot #][name]
926 unsigned slot = read_vbr_uint();
927 std::string Name = read_str();
928 const Type* T = getType(slot);
929 TST->insert(Name, T);
930 }
931}
932
933/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000934/// level symbol tables. For function level symbol tables, the CurrentFunction
935/// parameter must be non-zero and the ST parameter must correspond to
936/// CurrentFunction's symbol table. For Module level symbol tables, the
937/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000938void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
939 SymbolTable *ST) {
940
Reid Spencer04cde2c2004-07-04 11:33:49 +0000941 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000942
Chris Lattner39cacce2003-10-10 05:43:47 +0000943 // Allow efficient basic block lookup by number.
944 std::vector<BasicBlock*> BBMap;
945 if (CurrentFunction)
946 for (Function::iterator I = CurrentFunction->begin(),
947 E = CurrentFunction->end(); I != E; ++I)
948 BBMap.push_back(I);
949
Reid Spencer46b002c2004-07-11 17:28:43 +0000950 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000951 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000952 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000953 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000954
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000955 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000956 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000957 unsigned slot = read_vbr_uint();
958 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +0000959 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000960 if (Typ == LabelTySlot) {
Reid Spencerd798a512006-11-14 04:47:22 +0000961 if (slot < BBMap.size())
962 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +0000963 } else {
Reid Spencerd798a512006-11-14 04:47:22 +0000964 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +0000965 }
Reid Spencerd798a512006-11-14 04:47:22 +0000966 if (V == 0)
967 error("Failed value look-up for name '" + Name + "'");
968 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +0000969 }
970 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000971 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000972 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000973}
974
Reid Spencer46b002c2004-07-11 17:28:43 +0000975// Parse a single type. The typeid is read in first. If its a primitive type
976// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +0000977// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +0000978// definition.
979const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +0000980 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000981 const Type *Result = 0;
982 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
983 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +0000984
Reid Spencer060d25d2004-06-29 23:29:38 +0000985 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000986 case Type::IntegerTyID: {
987 unsigned NumBits = read_vbr_uint();
988 Result = IntegerType::get(NumBits);
989 break;
990 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000991 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +0000992 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +0000993 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000994
995 unsigned NumParams = read_vbr_uint();
996
997 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +0000998 std::vector<FunctionType::ParameterAttributes> Attrs;
999 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1000 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001001 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001002 if (Params.back() != Type::VoidTy)
1003 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1004 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001005
1006 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1007 if (isVarArg) Params.pop_back();
1008
Reid Spencer88cfda22006-12-31 05:44:24 +00001009 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001010 break;
1011 }
1012 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001013 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001014 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001015 Result = ArrayType::get(ElementType, NumElements);
1016 break;
1017 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001018 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001019 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001020 unsigned NumElements = read_vbr_uint();
1021 Result = PackedType::get(ElementType, NumElements);
1022 break;
1023 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001024 case Type::StructTyID: {
1025 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001026 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001027 while (Typ) { // List is terminated by void/0 typeid
1028 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001029 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001030 }
1031
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001032 Result = StructType::get(Elements, false);
1033 break;
1034 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001035 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001036 std::vector<const Type*> Elements;
1037 unsigned Typ = read_vbr_uint();
1038 while (Typ) { // List is terminated by void/0 typeid
1039 Elements.push_back(getType(Typ));
1040 Typ = read_vbr_uint();
1041 }
1042
1043 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001044 break;
1045 }
1046 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001047 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001048 break;
1049 }
1050
1051 case Type::OpaqueTyID: {
1052 Result = OpaqueType::get();
1053 break;
1054 }
1055
1056 default:
Reid Spencer24399722004-07-09 22:21:33 +00001057 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001058 break;
1059 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001060 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001061 return Result;
1062}
1063
Reid Spencer5b472d92004-08-21 20:49:23 +00001064// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001065// types. We know that recursive types will only reference the current slab of
1066// values in the type plane, but they can forward reference types before they
1067// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1068// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1069// this ugly problem, we pessimistically insert an opaque type for each type we
1070// are about to read. This means that forward references will resolve to
1071// something and when we reread the type later, we can replace the opaque type
1072// with a new resolved concrete type.
1073//
Reid Spencer46b002c2004-07-11 17:28:43 +00001074void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001075 assert(Tab.size() == 0 && "should not have read type constants in before!");
1076
1077 // Insert a bunch of opaque types to be resolved later...
1078 Tab.reserve(NumEntries);
1079 for (unsigned i = 0; i != NumEntries; ++i)
1080 Tab.push_back(OpaqueType::get());
1081
Misha Brukman8a96c532005-04-21 21:44:41 +00001082 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001083 Handler->handleTypeList(NumEntries);
1084
Chris Lattnereebac5f2005-10-03 21:26:53 +00001085 // If we are about to resolve types, make sure the type cache is clear.
1086 if (NumEntries)
1087 ModuleTypeIDCache.clear();
1088
Reid Spencer060d25d2004-06-29 23:29:38 +00001089 // Loop through reading all of the types. Forward types will make use of the
1090 // opaque types just inserted.
1091 //
1092 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001093 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001094 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001095 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001096 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001097
Misha Brukman8a96c532005-04-21 21:44:41 +00001098 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001099 // the opaque type we previously inserted with the new concrete value. This
1100 // approach helps with forward references to types. The refinement from the
1101 // abstract (opaque) type to the new type causes all uses of the abstract
1102 // type to use the concrete type (NewTy). This will also cause the opaque
1103 // type to be deleted.
1104 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1105
1106 // This should have replaced the old opaque type with the new type in the
1107 // value table... or with a preexisting type that was already in the system.
1108 // Let's just make sure it did.
1109 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1110 }
1111}
1112
Reid Spencer04cde2c2004-07-04 11:33:49 +00001113/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001114Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001115 // We must check for a ConstantExpr before switching by type because
1116 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001117 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 // 0 if not expr; numArgs if is expr
1119 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001120
Reid Spencer060d25d2004-06-29 23:29:38 +00001121 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001122 // 'undef' is encoded with 'exprnumargs' == 1.
1123 if (isExprNumArgs == 1)
1124 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001125
Reid Spencerd798a512006-11-14 04:47:22 +00001126 // Inline asm is encoded with exprnumargs == ~0U.
1127 if (isExprNumArgs == ~0U) {
1128 std::string AsmStr = read_str();
1129 std::string ConstraintStr = read_str();
1130 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001131
Reid Spencerd798a512006-11-14 04:47:22 +00001132 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1133 const FunctionType *FTy =
1134 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1135
1136 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1137 error("Invalid constraints for inline asm");
1138 if (Flags & ~1U)
1139 error("Invalid flags for inline asm");
1140 bool HasSideEffects = Flags & 1;
1141 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001142 }
Reid Spencerd798a512006-11-14 04:47:22 +00001143
1144 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001145
Reid Spencer060d25d2004-06-29 23:29:38 +00001146 // FIXME: Encoding of constant exprs could be much more compact!
1147 std::vector<Constant*> ArgVec;
1148 ArgVec.reserve(isExprNumArgs);
1149 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001150
Reid Spencer060d25d2004-06-29 23:29:38 +00001151 // Read the slot number and types of each of the arguments
1152 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1153 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001154 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001155
Reid Spencer060d25d2004-06-29 23:29:38 +00001156 // Get the arg value from its slot if it exists, otherwise a placeholder
1157 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1158 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001159
Reid Spencer060d25d2004-06-29 23:29:38 +00001160 // Construct a ConstantExpr of the appropriate kind
1161 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001162 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001163 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001164
Reid Spencera77fa7e2006-12-11 23:20:20 +00001165 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1166 getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001167 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, 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);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001172 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001173 return Result;
1174 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001175 if (ArgVec.size() != 3)
1176 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001177 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001178 ArgVec[2]);
1179 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001180 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001181 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001182 if (ArgVec.size() != 2 ||
1183 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1184 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001185 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1186 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1187 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001188 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001189 if (ArgVec.size() != 3 ||
1190 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1191 error("Invalid insertelement constand expr arguments");
1192
1193 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001194 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1195 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1196 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001197 } else if (Opcode == Instruction::ShuffleVector) {
1198 if (ArgVec.size() != 3 ||
1199 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001200 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001201 Constant *Result =
1202 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1203 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1204 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001205 } else if (Opcode == Instruction::ICmp) {
1206 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001207 error("Invalid ICmp constant expr arguments.");
1208 unsigned predicate = read_vbr_uint();
1209 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
1210 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1211 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001212 } else if (Opcode == Instruction::FCmp) {
1213 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001214 error("Invalid FCmp constant expr arguments.");
1215 unsigned predicate = read_vbr_uint();
1216 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
1217 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1218 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001219 } else { // All other 2-operand expressions
1220 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001221 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001222 return Result;
1223 }
1224 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001225
Reid Spencer060d25d2004-06-29 23:29:38 +00001226 // Ok, not an ConstantExpr. We now know how to read the given type...
1227 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001228 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001229 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001230 case Type::IntegerTyID: {
1231 const IntegerType *IT = cast<IntegerType>(Ty);
1232 if (IT->getBitWidth() <= 32) {
1233 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001234 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1235 error("Integer value read is invalid for type.");
1236 Result = ConstantInt::get(IT, Val);
1237 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001238 } else if (IT->getBitWidth() <= 64) {
1239 uint64_t Val = read_vbr_uint64();
1240 if (!ConstantInt::isValueValidForType(Ty, Val))
1241 error("Invalid constant integer read.");
1242 Result = ConstantInt::get(IT, Val);
1243 if (Handler) Handler->handleConstantValue(Result);
1244 } else
1245 assert("Integer types > 64 bits not supported");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001246 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001247 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001248 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001249 float Val;
1250 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001251 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001252 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001253 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001254 }
1255
1256 case Type::DoubleTyID: {
1257 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001258 read_double(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
Reid Spencer060d25d2004-06-29 23:29:38 +00001264 case Type::ArrayTyID: {
1265 const ArrayType *AT = cast<ArrayType>(Ty);
1266 unsigned NumElements = AT->getNumElements();
1267 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1268 std::vector<Constant*> Elements;
1269 Elements.reserve(NumElements);
1270 while (NumElements--) // Read all of the elements of the constant.
1271 Elements.push_back(getConstantValue(TypeSlot,
1272 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001273 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001274 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001275 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001276 }
1277
1278 case Type::StructTyID: {
1279 const StructType *ST = cast<StructType>(Ty);
1280
1281 std::vector<Constant *> Elements;
1282 Elements.reserve(ST->getNumElements());
1283 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1284 Elements.push_back(getConstantValue(ST->getElementType(i),
1285 read_vbr_uint()));
1286
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001287 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001288 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001289 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001290 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001291
Brian Gaeke715c90b2004-08-20 06:00:58 +00001292 case Type::PackedTyID: {
1293 const PackedType *PT = cast<PackedType>(Ty);
1294 unsigned NumElements = PT->getNumElements();
1295 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1296 std::vector<Constant*> Elements;
1297 Elements.reserve(NumElements);
1298 while (NumElements--) // Read all of the elements of the constant.
1299 Elements.push_back(getConstantValue(TypeSlot,
1300 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001301 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001302 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001303 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001304 }
1305
Chris Lattner638c3812004-11-19 16:24:05 +00001306 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001307 const PointerType *PT = cast<PointerType>(Ty);
1308 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001309
Reid Spencer060d25d2004-06-29 23:29:38 +00001310 // Check to see if we have already read this global variable...
1311 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001312 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001313 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1314 if (!GV) error("GlobalValue not in ValueTable!");
1315 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1316 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001317 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001318 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001319 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001320 }
1321
1322 default:
Reid Spencer24399722004-07-09 22:21:33 +00001323 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001324 Ty->getDescription());
1325 break;
1326 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001327
1328 // Check that we didn't read a null constant if they are implicit for this
1329 // type plane. Do not do this check for constantexprs, as they may be folded
1330 // to a null value in a way that isn't predicted when a .bc file is initially
1331 // produced.
1332 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1333 !hasImplicitNull(TypeID) &&
1334 "Cannot read null values from bytecode!");
1335 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001336}
1337
Misha Brukman8a96c532005-04-21 21:44:41 +00001338/// Resolve references for constants. This function resolves the forward
1339/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001340/// replaceAllUsesWith method of Value class to substitute the placeholder
1341/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001342void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1343 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001344 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001345 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001346 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001347
Chris Lattner29b789b2003-11-19 17:27:18 +00001348 Value *PH = I->second; // Get the placeholder...
1349 PH->replaceAllUsesWith(NewV);
1350 delete PH; // Delete the old placeholder
1351 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001352}
1353
Reid Spencer04cde2c2004-07-04 11:33:49 +00001354/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001355void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1356 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001357 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001358 const Type *Ty = getType(Typ);
1359 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001360 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001361
Reid Spencer060d25d2004-06-29 23:29:38 +00001362 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001363 if (ATy->getElementType() != Type::Int8Ty &&
1364 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001365 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001366
Reid Spencer060d25d2004-06-29 23:29:38 +00001367 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001368 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001369 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001370
Reid Spencer060d25d2004-06-29 23:29:38 +00001371 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001372 const Type* ElemType = ATy->getElementType();
1373 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1374 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001375
Reid Spencer060d25d2004-06-29 23:29:38 +00001376 // Create the constant, inserting it as needed.
1377 Constant *C = ConstantArray::get(ATy, Elements);
1378 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001379 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001380 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001381 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001382}
1383
Reid Spencer04cde2c2004-07-04 11:33:49 +00001384/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001385void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001386 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001387 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001388 if (Handler) Handler->handleGlobalConstantsBegin();
1389
1390 /// In LLVM 1.3 Type does not derive from Value so the types
1391 /// do not occupy a plane. Consequently, we read the types
1392 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001393 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001395 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001396 }
1397
Reid Spencer46b002c2004-07-11 17:28:43 +00001398 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001399 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001400 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001401
Reid Spencerd798a512006-11-14 04:47:22 +00001402 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001403 /// Use of Type::VoidTyID is a misnomer. It actually means
1404 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001405 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1406 ParseStringConstants(NumEntries, Tab);
1407 } else {
1408 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001409 Value *V = ParseConstantPoolValue(Typ);
1410 assert(V && "ParseConstantPoolValue returned NULL!");
1411 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001412
Reid Spencer060d25d2004-06-29 23:29:38 +00001413 // If we are reading a function constant table, make sure that we adjust
1414 // the slot number to be the real global constant number.
1415 //
1416 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1417 ModuleValues[Typ])
1418 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001419 if (Constant *C = dyn_cast<Constant>(V))
1420 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001421 }
1422 }
1423 }
Chris Lattner02dce162004-12-04 05:28:27 +00001424
1425 // After we have finished parsing the constant pool, we had better not have
1426 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001427 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001428 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001429 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001430 error(utostr(ConstantFwdRefs.size()) +
1431 " unresolved constant reference exist. First one is '" +
1432 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001433 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001434 }
Chris Lattner02dce162004-12-04 05:28:27 +00001435
Reid Spencer060d25d2004-06-29 23:29:38 +00001436 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001437 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001438}
Chris Lattner00950542001-06-06 20:29:01 +00001439
Reid Spencer04cde2c2004-07-04 11:33:49 +00001440/// Parse the contents of a function. Note that this function can be
1441/// called lazily by materializeFunction
1442/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001443void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001444
1445 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001446 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001447 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001448
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001449 unsigned rWord = read_vbr_uint();
1450 unsigned LinkageID = rWord & 65535;
1451 unsigned VisibilityID = rWord >> 16;
1452 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001453 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1454 case 1: Linkage = GlobalValue::WeakLinkage; break;
1455 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1456 case 3: Linkage = GlobalValue::InternalLinkage; break;
1457 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001458 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1459 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1460 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001461 default:
Reid Spencer24399722004-07-09 22:21:33 +00001462 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001463 Linkage = GlobalValue::InternalLinkage;
1464 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001465 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001466 switch (VisibilityID) {
1467 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1468 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1469 default:
1470 error("Unknown visibility type: " + utostr(VisibilityID));
1471 Visibility = GlobalValue::DefaultVisibility;
1472 break;
1473 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001474
Reid Spencer46b002c2004-07-11 17:28:43 +00001475 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001476 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001477 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001478
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001479 // Keep track of how many basic blocks we have read in...
1480 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001481 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001482
Reid Spencer060d25d2004-06-29 23:29:38 +00001483 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001484 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001485 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001486 BufPtr OldAt = At;
1487 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001488
1489 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001490 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001491 if (!InsertedArguments) {
1492 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001493 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001494 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001495 InsertedArguments = true;
1496 }
1497
Reid Spencer04cde2c2004-07-04 11:33:49 +00001498 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001499 break;
1500
Reid Spencerad89bd62004-07-25 18:07:36 +00001501 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001502 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001503 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001504 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001505 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001506 InsertedArguments = true;
1507 }
1508
Misha Brukman8a96c532005-04-21 21:44:41 +00001509 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001510 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001511 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001512 break;
1513 }
1514
Reid Spencer78d033e2007-01-06 07:24:44 +00001515 case BytecodeFormat::ValueSymbolTableBlockID:
1516 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1517 break;
1518
1519 case BytecodeFormat::TypeSymbolTableBlockID:
1520 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001521 break;
1522
1523 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001524 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001525 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001526 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001527 break;
1528 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001529 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001530 }
1531
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001532 // Make sure there were no references to non-existant basic blocks.
1533 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001534 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001535
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001536 ParsedBasicBlocks.clear();
1537
Chris Lattner97330cf2003-10-09 23:10:14 +00001538 // Resolve forward references. Replace any uses of a forward reference value
1539 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001540 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001541 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1542 I = ForwardReferences.begin();
1543 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001544 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001545 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001546 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001547 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001548 }
Chris Lattner00950542001-06-06 20:29:01 +00001549
Misha Brukman12c29d12003-09-22 23:38:23 +00001550 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001551 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001552 freeTable(FunctionValues);
1553
Reid Spencer04cde2c2004-07-04 11:33:49 +00001554 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001555}
1556
Reid Spencer04cde2c2004-07-04 11:33:49 +00001557/// This function parses LLVM functions lazily. It obtains the type of the
1558/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001559/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001560/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001561void BytecodeReader::ParseFunctionLazily() {
1562 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001563 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001564
Reid Spencer060d25d2004-06-29 23:29:38 +00001565 Function *Func = FunctionSignatureList.back();
1566 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001567
Reid Spencer060d25d2004-06-29 23:29:38 +00001568 // Save the information for future reading of the function
1569 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001570
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001571 // This function has a body but it's not loaded so it appears `External'.
1572 // Mark it as a `Ghost' instead to notify the users that it has a body.
1573 Func->setLinkage(GlobalValue::GhostLinkage);
1574
Reid Spencer060d25d2004-06-29 23:29:38 +00001575 // Pretend we've `parsed' this function
1576 At = BlockEnd;
1577}
Chris Lattner89e02532004-01-18 21:08:15 +00001578
Misha Brukman8a96c532005-04-21 21:44:41 +00001579/// The ParserFunction method lazily parses one function. Use this method to
1580/// casue the parser to parse a specific function in the module. Note that
1581/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001582/// ParseAllFunctionBodies.
1583/// @see ParseAllFunctionBodies
1584/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001585bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1586
Reid Spencer9b84ad12006-12-15 19:49:23 +00001587 if (setjmp(context)) {
1588 // Set caller's error message, if requested
1589 if (ErrMsg)
1590 *ErrMsg = ErrorMsg;
1591 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001592 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001593 }
Reid Spencer99655e12006-08-25 19:54:53 +00001594
Reid Spencer060d25d2004-06-29 23:29:38 +00001595 // Find {start, end} pointers and slot in the map. If not there, we're done.
1596 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001597
Reid Spencer060d25d2004-06-29 23:29:38 +00001598 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001599 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001600 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001601 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001602 }
1603
Reid Spencer060d25d2004-06-29 23:29:38 +00001604 BlockStart = At = Fi->second.Buf;
1605 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001606 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001607
1608 LazyFunctionLoadMap.erase(Fi);
1609
Reid Spencer46b002c2004-07-11 17:28:43 +00001610 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001611 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001612}
1613
Reid Spencer04cde2c2004-07-04 11:33:49 +00001614/// The ParseAllFunctionBodies method parses through all the previously
1615/// unparsed functions in the bytecode file. If you want to completely parse
1616/// a bytecode file, this method should be called after Parsebytecode because
1617/// Parsebytecode only records the locations in the bytecode file of where
1618/// the function definitions are located. This function uses that information
1619/// to materialize the functions.
1620/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001621bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001622 if (setjmp(context)) {
1623 // Set caller's error message, if requested
1624 if (ErrMsg)
1625 *ErrMsg = ErrorMsg;
1626 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001627 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001628 }
Reid Spencer99655e12006-08-25 19:54:53 +00001629
Reid Spencer060d25d2004-06-29 23:29:38 +00001630 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1631 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001632
Reid Spencer46b002c2004-07-11 17:28:43 +00001633 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001634 Function* Func = Fi->first;
1635 BlockStart = At = Fi->second.Buf;
1636 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001637 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001638 ++Fi;
1639 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001640 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001641 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001642}
Chris Lattner89e02532004-01-18 21:08:15 +00001643
Reid Spencer04cde2c2004-07-04 11:33:49 +00001644/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001645void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001646 // Read the number of types
1647 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001648 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001649}
1650
Reid Spencer04cde2c2004-07-04 11:33:49 +00001651/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001652void BytecodeReader::ParseModuleGlobalInfo() {
1653
Reid Spencer04cde2c2004-07-04 11:33:49 +00001654 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001655
Chris Lattner404cddf2005-11-12 01:33:40 +00001656 // SectionID - If a global has an explicit section specified, this map
1657 // remembers the ID until we can translate it into a string.
1658 std::map<GlobalValue*, unsigned> SectionID;
1659
Chris Lattner70cc3392001-09-10 07:58:01 +00001660 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001661 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001662 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001663 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1664 // Linkage, bit4+ = slot#
1665 unsigned SlotNo = VarType >> 5;
1666 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001667 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001668 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001669 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001670 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001671 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001672
1673 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1674 if (LinkageID == 3 && !hasInitializer) {
1675 unsigned ExtWord = read_vbr_uint();
1676 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001677 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1678 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001679 hasInitializer = ExtWord & 1;
1680 LinkageID = (ExtWord >> 1) & 7;
1681 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001682 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001683
1684 if (ExtWord & (1 << 9)) // Has a section ID.
1685 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001686 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001687
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001688 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001689 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001690 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1691 case 1: Linkage = GlobalValue::WeakLinkage; break;
1692 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1693 case 3: Linkage = GlobalValue::InternalLinkage; break;
1694 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001695 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1696 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1697 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001698 default:
Reid Spencer24399722004-07-09 22:21:33 +00001699 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001700 Linkage = GlobalValue::InternalLinkage;
1701 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001702 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001703 GlobalValue::VisibilityTypes Visibility;
1704 switch (VisibilityID) {
1705 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1706 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1707 default:
1708 error("Unknown visibility type: " + utostr(VisibilityID));
1709 Visibility = GlobalValue::DefaultVisibility;
1710 break;
1711 }
1712
Chris Lattnere3869c82003-04-16 21:16:05 +00001713 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001714 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001715 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001716
Chris Lattnere73bd452005-11-06 07:43:39 +00001717 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001718 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001719
Chris Lattner52e20b02003-03-19 20:54:26 +00001720 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001721
Chris Lattner70cc3392001-09-10 07:58:01 +00001722 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001723 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001724 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001725 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001726 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001727 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001728
Chris Lattner404cddf2005-11-12 01:33:40 +00001729 if (GlobalSectionID != 0)
1730 SectionID[GV] = GlobalSectionID;
1731
Reid Spencer060d25d2004-06-29 23:29:38 +00001732 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001733 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001734 initSlot = read_vbr_uint();
1735 GlobalInits.push_back(std::make_pair(GV, initSlot));
1736 }
1737
1738 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001739 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001740 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1741 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001742
1743 // Get next item
1744 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001745 }
1746
Chris Lattner52e20b02003-03-19 20:54:26 +00001747 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001748 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001749
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001750 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001751 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1752 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001753 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001754 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001755 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001756 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001757 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001758
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001759 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001760 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001761 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001762
Chris Lattner18549c22004-11-15 21:43:03 +00001763 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001764 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001765 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001766
Chris Lattnere73bd452005-11-06 07:43:39 +00001767 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001768
1769 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001770 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001771
Chris Lattner97fbc502004-11-15 22:38:52 +00001772 // Save this for later so we know type of lazily instantiated functions.
1773 // Note that known-external functions do not have FunctionInfo blocks, so we
1774 // do not add them to the FunctionSignatureList.
1775 if ((Flags & (1 << 4)) == 0)
1776 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001777
Chris Lattnere73bd452005-11-06 07:43:39 +00001778 // Get the calling convention from the low bits.
1779 unsigned CC = Flags & 15;
1780 unsigned Alignment = 0;
1781 if (FnSignature & (1 << 31)) { // Has extension word?
1782 unsigned ExtWord = read_vbr_uint();
1783 Alignment = (1 << (ExtWord & 31)) >> 1;
1784 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001785
1786 if (ExtWord & (1 << 10)) // Has a section ID.
1787 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001788
1789 // Parse external declaration linkage
1790 switch ((ExtWord >> 11) & 3) {
1791 case 0: break;
1792 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1793 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1794 default: assert(0 && "Unsupported external linkage");
1795 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001796 }
1797
Chris Lattner54b369e2005-11-06 07:46:13 +00001798 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001799 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001800
Reid Spencer04cde2c2004-07-04 11:33:49 +00001801 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001802
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001803 // Get the next function signature.
1804 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001805 }
1806
Misha Brukman8a96c532005-04-21 21:44:41 +00001807 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001808 // remove elements efficiently from the back of the vector.
1809 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001810
Chris Lattner404cddf2005-11-12 01:33:40 +00001811 /// SectionNames - This contains the list of section names encoded in the
1812 /// moduleinfoblock. Functions and globals with an explicit section index
1813 /// into this to get their section name.
1814 std::vector<std::string> SectionNames;
1815
Reid Spencerd798a512006-11-14 04:47:22 +00001816 // Read in the dependent library information.
1817 unsigned num_dep_libs = read_vbr_uint();
1818 std::string dep_lib;
1819 while (num_dep_libs--) {
1820 dep_lib = read_str();
1821 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001822 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001823 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001824 }
1825
Reid Spencerd798a512006-11-14 04:47:22 +00001826 // Read target triple and place into the module.
1827 std::string triple = read_str();
1828 TheModule->setTargetTriple(triple);
1829 if (Handler)
1830 Handler->handleTargetTriple(triple);
1831
Reid Spenceraacc35a2007-01-26 08:10:24 +00001832 // Read the data layout string and place into the module.
1833 std::string datalayout = read_str();
1834 TheModule->setDataLayout(datalayout);
1835 // FIXME: Implement
1836 // if (Handler)
1837 // Handler->handleDataLayout(datalayout);
1838
Reid Spencerd798a512006-11-14 04:47:22 +00001839 if (At != BlockEnd) {
1840 // If the file has section info in it, read the section names now.
1841 unsigned NumSections = read_vbr_uint();
1842 while (NumSections--)
1843 SectionNames.push_back(read_str());
1844 }
1845
1846 // If the file has module-level inline asm, read it now.
1847 if (At != BlockEnd)
1848 TheModule->setModuleInlineAsm(read_str());
1849
Chris Lattner404cddf2005-11-12 01:33:40 +00001850 // If any globals are in specified sections, assign them now.
1851 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1852 SectionID.end(); I != E; ++I)
1853 if (I->second) {
1854 if (I->second > SectionID.size())
1855 error("SectionID out of range for global!");
1856 I->first->setSection(SectionNames[I->second-1]);
1857 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001858
Chris Lattner00950542001-06-06 20:29:01 +00001859 // This is for future proofing... in the future extra fields may be added that
1860 // we don't understand, so we transparently ignore them.
1861 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001862 At = BlockEnd;
1863
Reid Spencer04cde2c2004-07-04 11:33:49 +00001864 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001865}
1866
Reid Spencer04cde2c2004-07-04 11:33:49 +00001867/// Parse the version information and decode it by setting flags on the
1868/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001869void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001870 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001871
Reid Spencer3795ad12006-12-03 05:47:10 +00001872 // We don't provide backwards compatibility in the Reader any more. To
1873 // upgrade, the user should use llvm-upgrade.
1874 if (RevisionNum < 7)
1875 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001876
Reid Spenceraacc35a2007-01-26 08:10:24 +00001877 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001878}
1879
Reid Spencer04cde2c2004-07-04 11:33:49 +00001880/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001881void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001882 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001883
Reid Spencer060d25d2004-06-29 23:29:38 +00001884 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001885
1886 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001887 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001888
Reid Spencer060d25d2004-06-29 23:29:38 +00001889 bool SeenModuleGlobalInfo = false;
1890 bool SeenGlobalTypePlane = false;
1891 BufPtr MyEnd = BlockEnd;
1892 while (At < MyEnd) {
1893 BufPtr OldAt = At;
1894 read_block(Type, Size);
1895
Chris Lattner00950542001-06-06 20:29:01 +00001896 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001897
Reid Spencerad89bd62004-07-25 18:07:36 +00001898 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001899 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001900 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001901
Reid Spencer5b472d92004-08-21 20:49:23 +00001902 if (Size > 0)
1903 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001904 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001905 break;
1906
Misha Brukman8a96c532005-04-21 21:44:41 +00001907 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001908 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001909 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001910 ParseModuleGlobalInfo();
1911 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001912 break;
1913
Reid Spencerad89bd62004-07-25 18:07:36 +00001914 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001915 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001916 break;
1917
Reid Spencerad89bd62004-07-25 18:07:36 +00001918 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001919 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001920 break;
Chris Lattner00950542001-06-06 20:29:01 +00001921
Reid Spencer78d033e2007-01-06 07:24:44 +00001922 case BytecodeFormat::ValueSymbolTableBlockID:
1923 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1924 break;
1925
1926 case BytecodeFormat::TypeSymbolTableBlockID:
1927 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001928 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001929
Chris Lattner00950542001-06-06 20:29:01 +00001930 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001931 At += Size;
1932 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001933 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001934 }
Chris Lattner00950542001-06-06 20:29:01 +00001935 break;
1936 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001937 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001938 }
1939
Chris Lattner52e20b02003-03-19 20:54:26 +00001940 // After the module constant pool has been read, we can safely initialize
1941 // global variables...
1942 while (!GlobalInits.empty()) {
1943 GlobalVariable *GV = GlobalInits.back().first;
1944 unsigned Slot = GlobalInits.back().second;
1945 GlobalInits.pop_back();
1946
1947 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001948 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001949
1950 const llvm::PointerType* GVType = GV->getType();
1951 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001952 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001953 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001954 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001955 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001956 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001957 } else
Reid Spencer24399722004-07-09 22:21:33 +00001958 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001959 }
1960
Chris Lattneraba5ff52005-05-05 20:57:00 +00001961 if (!ConstantFwdRefs.empty())
1962 error("Use of undefined constants in a module");
1963
Reid Spencer060d25d2004-06-29 23:29:38 +00001964 /// Make sure we pulled them all out. If we didn't then there's a declaration
1965 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001966 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001967 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001968}
1969
Reid Spencer04cde2c2004-07-04 11:33:49 +00001970/// This function completely parses a bytecode buffer given by the \p Buf
1971/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00001972bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00001973 const std::string &ModuleID,
1974 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001975
Reid Spencer233fe722006-08-22 16:09:19 +00001976 /// We handle errors by
1977 if (setjmp(context)) {
1978 // Cleanup after error
1979 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00001980 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001981 delete TheModule;
1982 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00001983 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00001984 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00001985 decompressedBlock = 0;
1986 }
Reid Spencer233fe722006-08-22 16:09:19 +00001987 // Set caller's error message, if requested
1988 if (ErrMsg)
1989 *ErrMsg = ErrorMsg;
1990 // Indicate an error occurred
1991 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001992 }
Reid Spencer233fe722006-08-22 16:09:19 +00001993
1994 RevisionNum = 0;
1995 At = MemStart = BlockStart = Buf;
1996 MemEnd = BlockEnd = Buf + Length;
1997
1998 // Create the module
1999 TheModule = new Module(ModuleID);
2000
2001 if (Handler) Handler->handleStart(TheModule, Length);
2002
2003 // Read the four bytes of the signature.
2004 unsigned Sig = read_uint();
2005
2006 // If this is a compressed file
2007 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2008
2009 // Invoke the decompression of the bytecode. Note that we have to skip the
2010 // file's magic number which is not part of the compressed block. Hence,
2011 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2012 // member for retention until BytecodeReader is destructed.
2013 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2014 (char*)Buf+4,Length-4,decompressedBlock);
2015
2016 // We must adjust the buffer pointers used by the bytecode reader to point
2017 // into the new decompressed block. After decompression, the
2018 // decompressedBlock will point to a contiguous memory area that has
2019 // the decompressed data.
2020 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2021 MemEnd = BlockEnd = Buf + decompressedLength;
2022
2023 // else if this isn't a regular (uncompressed) bytecode file, then its
2024 // and error, generate that now.
2025 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2026 error("Invalid bytecode signature: " + utohexstr(Sig));
2027 }
2028
2029 // Tell the handler we're starting a module
2030 if (Handler) Handler->handleModuleBegin(ModuleID);
2031
2032 // Get the module block and size and verify. This is handled specially
2033 // because the module block/size is always written in long format. Other
2034 // blocks are written in short format so the read_block method is used.
2035 unsigned Type, Size;
2036 Type = read_uint();
2037 Size = read_uint();
2038 if (Type != BytecodeFormat::ModuleBlockID) {
2039 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2040 + utostr(Size));
2041 }
2042
2043 // It looks like the darwin ranlib program is broken, and adds trailing
2044 // garbage to the end of some bytecode files. This hack allows the bc
2045 // reader to ignore trailing garbage on bytecode files.
2046 if (At + Size < MemEnd)
2047 MemEnd = BlockEnd = At+Size;
2048
2049 if (At + Size != MemEnd)
2050 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2051 + ", Size:" + utostr(Size));
2052
2053 // Parse the module contents
2054 this->ParseModule();
2055
2056 // Check for missing functions
2057 if (hasFunctions())
2058 error("Function expected, but bytecode stream ended!");
2059
Reid Spencer233fe722006-08-22 16:09:19 +00002060 // Tell the handler we're done with the module
2061 if (Handler)
2062 Handler->handleModuleEnd(ModuleID);
2063
2064 // Tell the handler we're finished the parse
2065 if (Handler) Handler->handleFinish();
2066
2067 return false;
2068
Chris Lattner00950542001-06-06 20:29:01 +00002069}
Reid Spencer060d25d2004-06-29 23:29:38 +00002070
2071//===----------------------------------------------------------------------===//
2072//=== Default Implementations of Handler Methods
2073//===----------------------------------------------------------------------===//
2074
2075BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002076