blob: 718ba3e80032a332df9f1636f047fdb5c4b2ffa2 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000024#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000025#include "llvm/Instructions.h"
26#include "llvm/SymbolTable.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000027#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000048 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000049 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
57 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000078 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000079 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000080 At += 4;
81 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
82}
83
Reid Spencer04cde2c2004-07-04 11:33:49 +000084/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000085inline unsigned BytecodeReader::read_vbr_uint() {
86 unsigned Shift = 0;
87 unsigned Result = 0;
88 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +000089
Reid Spencer060d25d2004-06-29 23:29:38 +000090 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000091 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000092 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000093 Result |= (unsigned)((*At++) & 0x7F) << Shift;
94 Shift += 7;
95 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +000096 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000097 return Result;
98}
99
Reid Spencer04cde2c2004-07-04 11:33:49 +0000100/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000101inline uint64_t BytecodeReader::read_vbr_uint64() {
102 unsigned Shift = 0;
103 uint64_t Result = 0;
104 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000105
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000107 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000108 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
110 Shift += 7;
111 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000113 return Result;
114}
115
Reid Spencer04cde2c2004-07-04 11:33:49 +0000116/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000117inline int64_t BytecodeReader::read_vbr_int64() {
118 uint64_t R = read_vbr_uint64();
119 if (R & 1) {
120 if (R != 1)
121 return -(int64_t)(R >> 1);
122 else // There is no such thing as -0 with integers. "-0" really means
123 // 0x8000000000000000.
124 return 1LL << 63;
125 } else
126 return (int64_t)(R >> 1);
127}
128
Reid Spencer04cde2c2004-07-04 11:33:49 +0000129/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000130inline std::string BytecodeReader::read_str() {
131 unsigned Size = read_vbr_uint();
132 const unsigned char *OldAt = At;
133 At += Size;
134 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000135 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000136 return std::string((char*)OldAt, Size);
137}
138
Reid Spencer04cde2c2004-07-04 11:33:49 +0000139/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000140inline void BytecodeReader::read_data(void *Ptr, void *End) {
141 unsigned char *Start = (unsigned char *)Ptr;
142 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000143 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000144 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000145 std::copy(At, At+Amount, Start);
146 At += Amount;
147}
148
Reid Spencer46b002c2004-07-11 17:28:43 +0000149/// Read a float value in little-endian order
150inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000151 /// FIXME: This isn't optimal, it has size problems on some platforms
152 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000153 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000154 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000155}
156
157/// Read a double value in little-endian order
158inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000159 /// FIXME: This isn't optimal, it has size problems on some platforms
160 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000161 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
162 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
163 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
164 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000165 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000166}
167
Reid Spencer04cde2c2004-07-04 11:33:49 +0000168/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000169inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000170 Size = read_uint(); // Read the header
171 Type = Size & 0x1F; // mask low order five bits to get type
172 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000173 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000174 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000175 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000176 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000177 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000178}
179
Reid Spencer060d25d2004-06-29 23:29:38 +0000180//===----------------------------------------------------------------------===//
181// IR Lookup Methods
182//===----------------------------------------------------------------------===//
183
Reid Spencer04cde2c2004-07-04 11:33:49 +0000184/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000185inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000186 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000187}
188
Reid Spencerd2bb8872007-01-30 19:36:46 +0000189/// Obtain a type given a typeid and account for things like function level vs
190/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000191const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000192 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000193 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000194 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000195
196 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000197 ID -= Type::FirstDerivedTyID;
198
Chris Lattner36392bc2003-10-08 21:18:57 +0000199 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000200 if (ID < ModuleTypes.size())
201 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000202
Reid Spencer46b002c2004-07-11 17:28:43 +0000203 // Nope, is it a function-level type?
204 ID -= ModuleTypes.size();
205 if (ID < FunctionTypes.size())
206 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000207
Reid Spencer46b002c2004-07-11 17:28:43 +0000208 error("Illegal type reference!");
209 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000210}
211
Reid Spencer3795ad12006-12-03 05:47:10 +0000212/// This method just saves some coding. It uses read_vbr_uint to read in a
213/// type id, errors that its not the type type, and then calls getType to
214/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000215inline const Type* BytecodeReader::readType() {
216 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000217}
218
219/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000220/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000221unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
222 if (Ty->isPrimitiveType())
223 return Ty->getTypeID();
224
Reid Spencer060d25d2004-06-29 23:29:38 +0000225 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000226 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
227 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000228
229 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000230 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000231 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000232
Chris Lattnereebac5f2005-10-03 21:26:53 +0000233 // If we don't have our cache yet, build it now.
234 if (ModuleTypeIDCache.empty()) {
235 unsigned N = 0;
236 ModuleTypeIDCache.reserve(ModuleTypes.size());
237 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
238 I != E; ++I, ++N)
239 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
240
241 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
242 }
243
244 // Binary search the cache for the entry.
245 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
246 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
247 std::make_pair(Ty, 0U));
248 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000249 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000250
251 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000252}
253
Misha Brukman8a96c532005-04-21 21:44:41 +0000254/// Retrieve a value of a given type and slot number, possibly creating
255/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000256Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000257 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000258 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000259
Reid Spencerd2bb8872007-01-30 19:36:46 +0000260 // By default, the global type id is the type id passed in
261 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000262
Reid Spencerd2bb8872007-01-30 19:36:46 +0000263 if (hasImplicitNull(GlobalTyID)) {
264 const Type *Ty = getType(type);
265 if (!isa<OpaqueType>(Ty)) {
266 if (Num == 0)
267 return Constant::getNullValue(Ty);
268 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000269 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000270 }
Chris Lattner89e02532004-01-18 21:08:15 +0000271
Reid Spencerd2bb8872007-01-30 19:36:46 +0000272 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
273 if (Num < ModuleValues[GlobalTyID]->size())
274 return ModuleValues[GlobalTyID]->getOperand(Num);
275 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner52e20b02003-03-19 20:54:26 +0000276 }
277
Misha Brukman8a96c532005-04-21 21:44:41 +0000278 if (FunctionValues.size() > type &&
279 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000280 Num < FunctionValues[type]->size())
281 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000282
Chris Lattner74734132002-08-17 22:01:27 +0000283 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000284
Reid Spencer551ccae2004-09-01 22:55:40 +0000285 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000286 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000287 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000288 if (I != ForwardReferences.end() && I->first == KeyValue)
289 return I->second; // We have already created this placeholder
290
Reid Spencer551ccae2004-09-01 22:55:40 +0000291 // If the type exists (it should)
292 if (const Type* Ty = getType(type)) {
293 // Create the place holder
294 Value *Val = new Argument(Ty);
295 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
296 return Val;
297 }
Reid Spencer233fe722006-08-22 16:09:19 +0000298 error("Can't create placeholder for value of type slot #" + utostr(type));
299 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000300}
301
Reid Spencer060d25d2004-06-29 23:29:38 +0000302
Reid Spencer04cde2c2004-07-04 11:33:49 +0000303/// Just like getValue, except that it returns a null pointer
304/// only on error. It always returns a constant (meaning that if the value is
305/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000306/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000307/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000308Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
309 if (Value *V = getValue(TypeSlot, Slot, false))
310 if (Constant *C = dyn_cast<Constant>(V))
311 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000312 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000313 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000314 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000315
Chris Lattner389bd042004-12-09 06:19:44 +0000316 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000317 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
318
319 if (I != ConstantFwdRefs.end() && I->first == Key) {
320 return I->second;
321 } else {
322 // Create a placeholder for the constant reference and
323 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000324 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000325
Reid Spencer060d25d2004-06-29 23:29:38 +0000326 // Keep track of the fact that we have a forward ref to recycle it
327 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
328 return C;
329 }
330}
331
332//===----------------------------------------------------------------------===//
333// IR Construction Methods
334//===----------------------------------------------------------------------===//
335
Reid Spencer04cde2c2004-07-04 11:33:49 +0000336/// As values are created, they are inserted into the appropriate place
337/// with this method. The ValueTable argument must be one of ModuleValues
338/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000339unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000340 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000341 if (ValueTab.size() <= type)
342 ValueTab.resize(type+1);
343
344 if (!ValueTab[type]) ValueTab[type] = new ValueList();
345
346 ValueTab[type]->push_back(Val);
347
Chris Lattneraba5ff52005-05-05 20:57:00 +0000348 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000349 return ValueTab[type]->size()-1 + HasOffset;
350}
351
Reid Spencer04cde2c2004-07-04 11:33:49 +0000352/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000353void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000354 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000355 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000356 for (FunctionType::param_iterator It = FT->param_begin();
357 It != FT->param_end(); ++It, ++AI)
358 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
359}
360
361//===----------------------------------------------------------------------===//
362// Bytecode Parsing Methods
363//===----------------------------------------------------------------------===//
364
Reid Spencer04cde2c2004-07-04 11:33:49 +0000365/// This method parses a single instruction. The instruction is
366/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000367/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000368void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000369 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000370 BufPtr SaveAt = At;
371
372 // Clear instruction data
373 Oprnds.clear();
374 unsigned iType = 0;
375 unsigned Opcode = 0;
376 unsigned Op = read_uint();
377
378 // bits Instruction format: Common to all formats
379 // --------------------------
380 // 01-00: Opcode type, fixed to 1.
381 // 07-02: Opcode
382 Opcode = (Op >> 2) & 63;
383 Oprnds.resize((Op >> 0) & 03);
384
385 // Extract the operands
386 switch (Oprnds.size()) {
387 case 1:
388 // bits Instruction format:
389 // --------------------------
390 // 19-08: Resulting type plane
391 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
392 //
393 iType = (Op >> 8) & 4095;
394 Oprnds[0] = (Op >> 20) & 4095;
395 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
396 Oprnds.resize(0);
397 break;
398 case 2:
399 // bits Instruction format:
400 // --------------------------
401 // 15-08: Resulting type plane
402 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000403 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000404 //
405 iType = (Op >> 8) & 255;
406 Oprnds[0] = (Op >> 16) & 255;
407 Oprnds[1] = (Op >> 24) & 255;
408 break;
409 case 3:
410 // bits Instruction format:
411 // --------------------------
412 // 13-08: Resulting type plane
413 // 19-14: Operand #1
414 // 25-20: Operand #2
415 // 31-26: Operand #3
416 //
417 iType = (Op >> 8) & 63;
418 Oprnds[0] = (Op >> 14) & 63;
419 Oprnds[1] = (Op >> 20) & 63;
420 Oprnds[2] = (Op >> 26) & 63;
421 break;
422 case 0:
423 At -= 4; // Hrm, try this again...
424 Opcode = read_vbr_uint();
425 Opcode >>= 2;
426 iType = read_vbr_uint();
427
428 unsigned NumOprnds = read_vbr_uint();
429 Oprnds.resize(NumOprnds);
430
431 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000432 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000433
434 for (unsigned i = 0; i != NumOprnds; ++i)
435 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000436 break;
437 }
438
Reid Spencerd798a512006-11-14 04:47:22 +0000439 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000440
Reid Spencer1628cec2006-10-26 06:15:43 +0000441 // Make the necessary adjustments for dealing with backwards compatibility
442 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000443 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000444
Reid Spencer46b002c2004-07-11 17:28:43 +0000445 // We have enough info to inform the handler now.
Reid Spencer1628cec2006-10-26 06:15:43 +0000446 if (Handler)
447 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000448
Reid Spencer3795ad12006-12-03 05:47:10 +0000449 // First, handle the easy binary operators case
450 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000451 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000452 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
453 getValue(iType, Oprnds[0]),
454 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000455 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000456 // Indicate that we don't think this is a call instruction (yet).
457 // Process based on the Opcode read
458 switch (Opcode) {
459 default: // There was an error, this shouldn't happen.
460 if (Result == 0)
461 error("Illegal instruction read!");
462 break;
463 case Instruction::VAArg:
464 if (Oprnds.size() != 2)
465 error("Invalid VAArg instruction!");
466 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000467 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000468 break;
469 case Instruction::ExtractElement: {
470 if (Oprnds.size() != 2)
471 error("Invalid extractelement instruction!");
472 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000473 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000474
Reid Spencer1628cec2006-10-26 06:15:43 +0000475 if (!ExtractElementInst::isValidOperands(V1, V2))
476 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000477
Reid Spencer1628cec2006-10-26 06:15:43 +0000478 Result = new ExtractElementInst(V1, V2);
479 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000480 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000481 case Instruction::InsertElement: {
482 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
483 if (!PackedTy || Oprnds.size() != 3)
484 error("Invalid insertelement instruction!");
485
486 Value *V1 = getValue(iType, Oprnds[0]);
487 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000488 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000489
490 if (!InsertElementInst::isValidOperands(V1, V2, V3))
491 error("Invalid insertelement instruction!");
492 Result = new InsertElementInst(V1, V2, V3);
493 break;
494 }
495 case Instruction::ShuffleVector: {
496 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
497 if (!PackedTy || Oprnds.size() != 3)
498 error("Invalid shufflevector instruction!");
499 Value *V1 = getValue(iType, Oprnds[0]);
500 Value *V2 = getValue(iType, Oprnds[1]);
501 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000502 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000503 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
504 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
505 error("Invalid shufflevector instruction!");
506 Result = new ShuffleVectorInst(V1, V2, V3);
507 break;
508 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000509 case Instruction::Trunc:
510 if (Oprnds.size() != 2)
511 error("Invalid cast instruction!");
512 Result = new TruncInst(getValue(iType, Oprnds[0]),
513 getType(Oprnds[1]));
514 break;
515 case Instruction::ZExt:
516 if (Oprnds.size() != 2)
517 error("Invalid cast instruction!");
518 Result = new ZExtInst(getValue(iType, Oprnds[0]),
519 getType(Oprnds[1]));
520 break;
521 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000522 if (Oprnds.size() != 2)
523 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000524 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000525 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000526 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000527 case Instruction::FPTrunc:
528 if (Oprnds.size() != 2)
529 error("Invalid cast instruction!");
530 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
531 getType(Oprnds[1]));
532 break;
533 case Instruction::FPExt:
534 if (Oprnds.size() != 2)
535 error("Invalid cast instruction!");
536 Result = new FPExtInst(getValue(iType, Oprnds[0]),
537 getType(Oprnds[1]));
538 break;
539 case Instruction::UIToFP:
540 if (Oprnds.size() != 2)
541 error("Invalid cast instruction!");
542 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
543 getType(Oprnds[1]));
544 break;
545 case Instruction::SIToFP:
546 if (Oprnds.size() != 2)
547 error("Invalid cast instruction!");
548 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
549 getType(Oprnds[1]));
550 break;
551 case Instruction::FPToUI:
552 if (Oprnds.size() != 2)
553 error("Invalid cast instruction!");
554 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
555 getType(Oprnds[1]));
556 break;
557 case Instruction::FPToSI:
558 if (Oprnds.size() != 2)
559 error("Invalid cast instruction!");
560 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
561 getType(Oprnds[1]));
562 break;
563 case Instruction::IntToPtr:
564 if (Oprnds.size() != 2)
565 error("Invalid cast instruction!");
566 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
567 getType(Oprnds[1]));
568 break;
569 case Instruction::PtrToInt:
570 if (Oprnds.size() != 2)
571 error("Invalid cast instruction!");
572 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
573 getType(Oprnds[1]));
574 break;
575 case Instruction::BitCast:
576 if (Oprnds.size() != 2)
577 error("Invalid cast instruction!");
578 Result = new BitCastInst(getValue(iType, Oprnds[0]),
579 getType(Oprnds[1]));
580 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000581 case Instruction::Select:
582 if (Oprnds.size() != 3)
583 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000584 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000585 getValue(iType, Oprnds[1]),
586 getValue(iType, Oprnds[2]));
587 break;
588 case Instruction::PHI: {
589 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
590 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000591
Reid Spencer1628cec2006-10-26 06:15:43 +0000592 PHINode *PN = new PHINode(InstTy);
593 PN->reserveOperandSpace(Oprnds.size());
594 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
595 PN->addIncoming(
596 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
597 Result = PN;
598 break;
599 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000600 case Instruction::ICmp:
601 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000602 if (Oprnds.size() != 3)
603 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000604 // These instructions encode the comparison predicate as the 3rd operand.
605 Result = CmpInst::create(Instruction::OtherOps(Opcode),
606 static_cast<unsigned short>(Oprnds[2]),
607 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
608 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000609 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000610 case Instruction::LShr:
611 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000612 Result = new ShiftInst(Instruction::OtherOps(Opcode),
613 getValue(iType, Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000614 getValue(Int8TySlot, Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000615 break;
616 case Instruction::Ret:
617 if (Oprnds.size() == 0)
618 Result = new ReturnInst();
619 else if (Oprnds.size() == 1)
620 Result = new ReturnInst(getValue(iType, Oprnds[0]));
621 else
622 error("Unrecognized instruction!");
623 break;
624
625 case Instruction::Br:
626 if (Oprnds.size() == 1)
627 Result = new BranchInst(getBasicBlock(Oprnds[0]));
628 else if (Oprnds.size() == 3)
629 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000630 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000631 else
632 error("Invalid number of operands for a 'br' instruction!");
633 break;
634 case Instruction::Switch: {
635 if (Oprnds.size() & 1)
636 error("Switch statement with odd number of arguments!");
637
638 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
639 getBasicBlock(Oprnds[1]),
640 Oprnds.size()/2-1);
641 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
642 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
643 getBasicBlock(Oprnds[i+1]));
644 Result = I;
645 break;
646 }
647 case 58: // Call with extra operand for calling conv
648 case 59: // tail call, Fast CC
649 case 60: // normal call, Fast CC
650 case 61: // tail call, C Calling Conv
651 case Instruction::Call: { // Normal Call, C Calling Convention
652 if (Oprnds.size() == 0)
653 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000654 Value *F = getValue(iType, Oprnds[0]);
655
656 unsigned CallingConv = CallingConv::C;
657 bool isTailCall = false;
658
659 if (Opcode == 61 || Opcode == 59)
660 isTailCall = true;
661
662 if (Opcode == 58) {
663 isTailCall = Oprnds.back() & 1;
664 CallingConv = Oprnds.back() >> 1;
665 Oprnds.pop_back();
666 } else if (Opcode == 59 || Opcode == 60) {
667 CallingConv = CallingConv::Fast;
668 }
669
670 // Check to make sure we have a pointer to function type
671 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
672 if (PTy == 0) error("Call to non function pointer value!");
673 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
674 if (FTy == 0) error("Call to non function pointer value!");
675
676 std::vector<Value *> Params;
677 if (!FTy->isVarArg()) {
678 FunctionType::param_iterator It = FTy->param_begin();
679
680 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
681 if (It == FTy->param_end())
682 error("Invalid call instruction!");
683 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
684 }
685 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000686 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000687 } else {
688 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
689
690 unsigned FirstVariableOperand;
691 if (Oprnds.size() < FTy->getNumParams())
692 error("Call instruction missing operands!");
693
694 // Read all of the fixed arguments
695 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
696 Params.push_back(
697 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
698
699 FirstVariableOperand = FTy->getNumParams();
700
701 if ((Oprnds.size()-FirstVariableOperand) & 1)
702 error("Invalid call instruction!"); // Must be pairs of type/value
703
704 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
705 i != e; i += 2)
706 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000707 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000708
Reid Spencer1628cec2006-10-26 06:15:43 +0000709 Result = new CallInst(F, Params);
710 if (isTailCall) cast<CallInst>(Result)->setTailCall();
711 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
712 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000713 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000714 case Instruction::Invoke: { // Invoke C CC
715 if (Oprnds.size() < 3)
716 error("Invalid invoke instruction!");
717 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000718
Reid Spencer1628cec2006-10-26 06:15:43 +0000719 // Check to make sure we have a pointer to function type
720 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
721 if (PTy == 0)
722 error("Invoke to non function pointer value!");
723 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
724 if (FTy == 0)
725 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000726
Reid Spencer1628cec2006-10-26 06:15:43 +0000727 std::vector<Value *> Params;
728 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000729 unsigned CallingConv = Oprnds.back();
730 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000731
Reid Spencer1628cec2006-10-26 06:15:43 +0000732 if (!FTy->isVarArg()) {
733 Normal = getBasicBlock(Oprnds[1]);
734 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000735
Reid Spencer1628cec2006-10-26 06:15:43 +0000736 FunctionType::param_iterator It = FTy->param_begin();
737 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
738 if (It == FTy->param_end())
739 error("Invalid invoke instruction!");
740 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
741 }
742 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000743 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000744 } else {
745 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
746
747 Normal = getBasicBlock(Oprnds[0]);
748 Except = getBasicBlock(Oprnds[1]);
749
750 unsigned FirstVariableArgument = FTy->getNumParams()+2;
751 for (unsigned i = 2; i != FirstVariableArgument; ++i)
752 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
753 Oprnds[i]));
754
755 // Must be type/value pairs. If not, error out.
756 if (Oprnds.size()-FirstVariableArgument & 1)
757 error("Invalid invoke instruction!");
758
759 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
760 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000761 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000762
Reid Spencer1628cec2006-10-26 06:15:43 +0000763 Result = new InvokeInst(F, Normal, Except, Params);
764 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
765 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000766 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000767 case Instruction::Malloc: {
768 unsigned Align = 0;
769 if (Oprnds.size() == 2)
770 Align = (1 << Oprnds[1]) >> 1;
771 else if (Oprnds.size() > 2)
772 error("Invalid malloc instruction!");
773 if (!isa<PointerType>(InstTy))
774 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000775
Reid Spencer1628cec2006-10-26 06:15:43 +0000776 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000777 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000778 break;
779 }
780 case Instruction::Alloca: {
781 unsigned Align = 0;
782 if (Oprnds.size() == 2)
783 Align = (1 << Oprnds[1]) >> 1;
784 else if (Oprnds.size() > 2)
785 error("Invalid alloca instruction!");
786 if (!isa<PointerType>(InstTy))
787 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000788
Reid Spencer1628cec2006-10-26 06:15:43 +0000789 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000790 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000791 break;
792 }
793 case Instruction::Free:
794 if (!isa<PointerType>(InstTy))
795 error("Invalid free instruction!");
796 Result = new FreeInst(getValue(iType, Oprnds[0]));
797 break;
798 case Instruction::GetElementPtr: {
799 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000800 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000801
Reid Spencer1628cec2006-10-26 06:15:43 +0000802 std::vector<Value*> Idx;
803
804 const Type *NextTy = InstTy;
805 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
806 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
807 if (!TopTy)
808 error("Invalid getelementptr instruction!");
809
810 unsigned ValIdx = Oprnds[i];
811 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000812 // Struct indices are always uints, sequential type indices can be
813 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000814 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000815 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000816 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000817 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000818 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000819 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000820 case 0: IdxTy = Int32TySlot; break;
821 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000822 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000823 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000824 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000825 Idx.push_back(getValue(IdxTy, ValIdx));
Reid Spencer1628cec2006-10-26 06:15:43 +0000826 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000827 }
828
Reid Spencer1628cec2006-10-26 06:15:43 +0000829 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
830 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000831 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000832 case 62: // volatile load
833 case Instruction::Load:
834 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
835 error("Invalid load instruction!");
836 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
837 break;
838 case 63: // volatile store
839 case Instruction::Store: {
840 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
841 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000842
Reid Spencer1628cec2006-10-26 06:15:43 +0000843 Value *Ptr = getValue(iType, Oprnds[1]);
844 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
845 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
846 Opcode == 63);
847 break;
848 }
849 case Instruction::Unwind:
850 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
851 Result = new UnwindInst();
852 break;
853 case Instruction::Unreachable:
854 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
855 Result = new UnreachableInst();
856 break;
857 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000858 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000859
Reid Spencere1e96c02006-01-19 07:02:16 +0000860 BB->getInstList().push_back(Result);
861
Reid Spencer060d25d2004-06-29 23:29:38 +0000862 unsigned TypeSlot;
863 if (Result->getType() == InstTy)
864 TypeSlot = iType;
865 else
866 TypeSlot = getTypeSlot(Result->getType());
867
868 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000869}
870
Reid Spencer04cde2c2004-07-04 11:33:49 +0000871/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000872/// This works together with ParseInstructionList to handle these forward
873/// references in a clean manner. This function is used when constructing
874/// phi, br, switch, and other instructions that reference basic blocks.
875/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000876BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000877 // Make sure there is room in the table...
878 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
879
Reid Spencerd798a512006-11-14 04:47:22 +0000880 // First check to see if this is a backwards reference, i.e. this block
881 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000882 // been created.
883 if (ParsedBasicBlocks[ID])
884 return ParsedBasicBlocks[ID];
885
886 // Otherwise, the basic block has not yet been created. Do so and add it to
887 // the ParsedBasicBlocks list.
888 return ParsedBasicBlocks[ID] = new BasicBlock();
889}
890
Reid Spencer04cde2c2004-07-04 11:33:49 +0000891/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000892/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000893/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000894/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000895unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000896 unsigned BlockNo = 0;
897 std::vector<unsigned> Args;
898
Reid Spencer46b002c2004-07-11 17:28:43 +0000899 while (moreInBlock()) {
900 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000901 BasicBlock *BB;
902 if (ParsedBasicBlocks.size() == BlockNo)
903 ParsedBasicBlocks.push_back(BB = new BasicBlock());
904 else if (ParsedBasicBlocks[BlockNo] == 0)
905 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
906 else
907 BB = ParsedBasicBlocks[BlockNo];
908 ++BlockNo;
909 F->getBasicBlockList().push_back(BB);
910
911 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000912 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000913 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000914
915 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000916 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000917
Reid Spencer46b002c2004-07-11 17:28:43 +0000918 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000919 }
920
921 return BlockNo;
922}
923
Reid Spencer78d033e2007-01-06 07:24:44 +0000924/// Parse a type symbol table.
925void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
926 // Type Symtab block header: [num entries]
927 unsigned NumEntries = read_vbr_uint();
928 for (unsigned i = 0; i < NumEntries; ++i) {
929 // Symtab entry: [type slot #][name]
930 unsigned slot = read_vbr_uint();
931 std::string Name = read_str();
932 const Type* T = getType(slot);
933 TST->insert(Name, T);
934 }
935}
936
937/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000938/// level symbol tables. For function level symbol tables, the CurrentFunction
939/// parameter must be non-zero and the ST parameter must correspond to
940/// CurrentFunction's symbol table. For Module level symbol tables, the
941/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000942void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
943 SymbolTable *ST) {
944
Reid Spencer04cde2c2004-07-04 11:33:49 +0000945 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000946
Chris Lattner39cacce2003-10-10 05:43:47 +0000947 // Allow efficient basic block lookup by number.
948 std::vector<BasicBlock*> BBMap;
949 if (CurrentFunction)
950 for (Function::iterator I = CurrentFunction->begin(),
951 E = CurrentFunction->end(); I != E; ++I)
952 BBMap.push_back(I);
953
Reid Spencer46b002c2004-07-11 17:28:43 +0000954 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000955 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000956 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000957 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000958
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000959 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000960 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000961 unsigned slot = read_vbr_uint();
962 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +0000963 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000964 if (Typ == LabelTySlot) {
Reid Spencerd798a512006-11-14 04:47:22 +0000965 if (slot < BBMap.size())
966 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +0000967 } else {
Reid Spencerd798a512006-11-14 04:47:22 +0000968 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +0000969 }
Reid Spencerd798a512006-11-14 04:47:22 +0000970 if (V == 0)
971 error("Failed value look-up for name '" + Name + "'");
972 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +0000973 }
974 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000975 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000976 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000977}
978
Reid Spencer46b002c2004-07-11 17:28:43 +0000979// Parse a single type. The typeid is read in first. If its a primitive type
980// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +0000981// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +0000982// definition.
983const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +0000984 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000985 const Type *Result = 0;
986 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
987 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +0000988
Reid Spencer060d25d2004-06-29 23:29:38 +0000989 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000990 case Type::IntegerTyID: {
991 unsigned NumBits = read_vbr_uint();
992 Result = IntegerType::get(NumBits);
993 break;
994 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000995 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +0000996 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +0000997 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000998
999 unsigned NumParams = read_vbr_uint();
1000
1001 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +00001002 std::vector<FunctionType::ParameterAttributes> Attrs;
1003 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1004 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001005 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001006 if (Params.back() != Type::VoidTy)
1007 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1008 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001009
1010 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1011 if (isVarArg) Params.pop_back();
1012
Reid Spencer88cfda22006-12-31 05:44:24 +00001013 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001014 break;
1015 }
1016 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001017 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001018 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001019 Result = ArrayType::get(ElementType, NumElements);
1020 break;
1021 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001022 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001023 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001024 unsigned NumElements = read_vbr_uint();
1025 Result = PackedType::get(ElementType, NumElements);
1026 break;
1027 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001028 case Type::StructTyID: {
1029 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001030 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001031 while (Typ) { // List is terminated by void/0 typeid
1032 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001033 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001034 }
1035
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001036 Result = StructType::get(Elements, false);
1037 break;
1038 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001039 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001040 std::vector<const Type*> Elements;
1041 unsigned Typ = read_vbr_uint();
1042 while (Typ) { // List is terminated by void/0 typeid
1043 Elements.push_back(getType(Typ));
1044 Typ = read_vbr_uint();
1045 }
1046
1047 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001048 break;
1049 }
1050 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001051 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001052 break;
1053 }
1054
1055 case Type::OpaqueTyID: {
1056 Result = OpaqueType::get();
1057 break;
1058 }
1059
1060 default:
Reid Spencer24399722004-07-09 22:21:33 +00001061 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001062 break;
1063 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001064 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001065 return Result;
1066}
1067
Reid Spencer5b472d92004-08-21 20:49:23 +00001068// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001069// types. We know that recursive types will only reference the current slab of
1070// values in the type plane, but they can forward reference types before they
1071// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1072// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1073// this ugly problem, we pessimistically insert an opaque type for each type we
1074// are about to read. This means that forward references will resolve to
1075// something and when we reread the type later, we can replace the opaque type
1076// with a new resolved concrete type.
1077//
Reid Spencer46b002c2004-07-11 17:28:43 +00001078void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001079 assert(Tab.size() == 0 && "should not have read type constants in before!");
1080
1081 // Insert a bunch of opaque types to be resolved later...
1082 Tab.reserve(NumEntries);
1083 for (unsigned i = 0; i != NumEntries; ++i)
1084 Tab.push_back(OpaqueType::get());
1085
Misha Brukman8a96c532005-04-21 21:44:41 +00001086 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001087 Handler->handleTypeList(NumEntries);
1088
Chris Lattnereebac5f2005-10-03 21:26:53 +00001089 // If we are about to resolve types, make sure the type cache is clear.
1090 if (NumEntries)
1091 ModuleTypeIDCache.clear();
1092
Reid Spencer060d25d2004-06-29 23:29:38 +00001093 // Loop through reading all of the types. Forward types will make use of the
1094 // opaque types just inserted.
1095 //
1096 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001097 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001098 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001099 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001100 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001101
Misha Brukman8a96c532005-04-21 21:44:41 +00001102 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001103 // the opaque type we previously inserted with the new concrete value. This
1104 // approach helps with forward references to types. The refinement from the
1105 // abstract (opaque) type to the new type causes all uses of the abstract
1106 // type to use the concrete type (NewTy). This will also cause the opaque
1107 // type to be deleted.
1108 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1109
1110 // This should have replaced the old opaque type with the new type in the
1111 // value table... or with a preexisting type that was already in the system.
1112 // Let's just make sure it did.
1113 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1114 }
1115}
1116
Reid Spencer04cde2c2004-07-04 11:33:49 +00001117/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001118Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001119 // We must check for a ConstantExpr before switching by type because
1120 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001121 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001122 // 0 if not expr; numArgs if is expr
1123 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001124
Reid Spencer060d25d2004-06-29 23:29:38 +00001125 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001126 // 'undef' is encoded with 'exprnumargs' == 1.
1127 if (isExprNumArgs == 1)
1128 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001129
Reid Spencerd798a512006-11-14 04:47:22 +00001130 // Inline asm is encoded with exprnumargs == ~0U.
1131 if (isExprNumArgs == ~0U) {
1132 std::string AsmStr = read_str();
1133 std::string ConstraintStr = read_str();
1134 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001135
Reid Spencerd798a512006-11-14 04:47:22 +00001136 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1137 const FunctionType *FTy =
1138 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1139
1140 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1141 error("Invalid constraints for inline asm");
1142 if (Flags & ~1U)
1143 error("Invalid flags for inline asm");
1144 bool HasSideEffects = Flags & 1;
1145 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001146 }
Reid Spencerd798a512006-11-14 04:47:22 +00001147
1148 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001149
Reid Spencer060d25d2004-06-29 23:29:38 +00001150 // FIXME: Encoding of constant exprs could be much more compact!
1151 std::vector<Constant*> ArgVec;
1152 ArgVec.reserve(isExprNumArgs);
1153 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001154
Reid Spencer060d25d2004-06-29 23:29:38 +00001155 // Read the slot number and types of each of the arguments
1156 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1157 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001158 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001159
Reid Spencer060d25d2004-06-29 23:29:38 +00001160 // Get the arg value from its slot if it exists, otherwise a placeholder
1161 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1162 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001163
Reid Spencer060d25d2004-06-29 23:29:38 +00001164 // Construct a ConstantExpr of the appropriate kind
1165 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001166 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001167 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001168
Reid Spencera77fa7e2006-12-11 23:20:20 +00001169 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1170 getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001171 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001172 return Result;
1173 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1174 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
Reid Spencer3da59db2006-11-27 01:05:10 +00001175 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001176 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001177 return Result;
1178 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001179 if (ArgVec.size() != 3)
1180 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001181 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001182 ArgVec[2]);
1183 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001184 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001185 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001186 if (ArgVec.size() != 2 ||
1187 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1188 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001189 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1190 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1191 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001192 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001193 if (ArgVec.size() != 3 ||
1194 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1195 error("Invalid insertelement constand expr arguments");
1196
1197 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001198 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1199 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1200 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001201 } else if (Opcode == Instruction::ShuffleVector) {
1202 if (ArgVec.size() != 3 ||
1203 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001204 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001205 Constant *Result =
1206 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1207 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1208 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001209 } else if (Opcode == Instruction::ICmp) {
1210 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001211 error("Invalid ICmp constant expr arguments.");
1212 unsigned predicate = read_vbr_uint();
1213 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
1214 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1215 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001216 } else if (Opcode == Instruction::FCmp) {
1217 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001218 error("Invalid FCmp constant expr arguments.");
1219 unsigned predicate = read_vbr_uint();
1220 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
1221 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1222 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001223 } else { // All other 2-operand expressions
1224 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001225 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001226 return Result;
1227 }
1228 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001229
Reid Spencer060d25d2004-06-29 23:29:38 +00001230 // Ok, not an ConstantExpr. We now know how to read the given type...
1231 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001232 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001233 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001234 case Type::IntegerTyID: {
1235 const IntegerType *IT = cast<IntegerType>(Ty);
1236 if (IT->getBitWidth() <= 32) {
1237 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001238 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1239 error("Integer value read is invalid for type.");
1240 Result = ConstantInt::get(IT, Val);
1241 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001242 } else if (IT->getBitWidth() <= 64) {
1243 uint64_t Val = read_vbr_uint64();
1244 if (!ConstantInt::isValueValidForType(Ty, Val))
1245 error("Invalid constant integer read.");
1246 Result = ConstantInt::get(IT, Val);
1247 if (Handler) Handler->handleConstantValue(Result);
1248 } else
1249 assert("Integer types > 64 bits not supported");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001250 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001251 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001252 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001253 float Val;
1254 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001255 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001256 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001257 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001258 }
1259
1260 case Type::DoubleTyID: {
1261 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001262 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001263 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001264 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001265 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001266 }
1267
Reid Spencer060d25d2004-06-29 23:29:38 +00001268 case Type::ArrayTyID: {
1269 const ArrayType *AT = cast<ArrayType>(Ty);
1270 unsigned NumElements = AT->getNumElements();
1271 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1272 std::vector<Constant*> Elements;
1273 Elements.reserve(NumElements);
1274 while (NumElements--) // Read all of the elements of the constant.
1275 Elements.push_back(getConstantValue(TypeSlot,
1276 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001277 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001278 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001279 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001280 }
1281
1282 case Type::StructTyID: {
1283 const StructType *ST = cast<StructType>(Ty);
1284
1285 std::vector<Constant *> Elements;
1286 Elements.reserve(ST->getNumElements());
1287 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1288 Elements.push_back(getConstantValue(ST->getElementType(i),
1289 read_vbr_uint()));
1290
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001291 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001292 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001293 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001294 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001295
Brian Gaeke715c90b2004-08-20 06:00:58 +00001296 case Type::PackedTyID: {
1297 const PackedType *PT = cast<PackedType>(Ty);
1298 unsigned NumElements = PT->getNumElements();
1299 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1300 std::vector<Constant*> Elements;
1301 Elements.reserve(NumElements);
1302 while (NumElements--) // Read all of the elements of the constant.
1303 Elements.push_back(getConstantValue(TypeSlot,
1304 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001305 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001306 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001307 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001308 }
1309
Chris Lattner638c3812004-11-19 16:24:05 +00001310 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001311 const PointerType *PT = cast<PointerType>(Ty);
1312 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001313
Reid Spencer060d25d2004-06-29 23:29:38 +00001314 // Check to see if we have already read this global variable...
1315 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001316 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001317 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1318 if (!GV) error("GlobalValue not in ValueTable!");
1319 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1320 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001321 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001322 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001323 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001324 }
1325
1326 default:
Reid Spencer24399722004-07-09 22:21:33 +00001327 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001328 Ty->getDescription());
1329 break;
1330 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001331
1332 // Check that we didn't read a null constant if they are implicit for this
1333 // type plane. Do not do this check for constantexprs, as they may be folded
1334 // to a null value in a way that isn't predicted when a .bc file is initially
1335 // produced.
1336 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1337 !hasImplicitNull(TypeID) &&
1338 "Cannot read null values from bytecode!");
1339 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001340}
1341
Misha Brukman8a96c532005-04-21 21:44:41 +00001342/// Resolve references for constants. This function resolves the forward
1343/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001344/// replaceAllUsesWith method of Value class to substitute the placeholder
1345/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001346void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1347 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001348 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001349 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001350 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001351
Chris Lattner29b789b2003-11-19 17:27:18 +00001352 Value *PH = I->second; // Get the placeholder...
1353 PH->replaceAllUsesWith(NewV);
1354 delete PH; // Delete the old placeholder
1355 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001356}
1357
Reid Spencer04cde2c2004-07-04 11:33:49 +00001358/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001359void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1360 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001361 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001362 const Type *Ty = getType(Typ);
1363 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001364 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001365
Reid Spencer060d25d2004-06-29 23:29:38 +00001366 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001367 if (ATy->getElementType() != Type::Int8Ty &&
1368 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001369 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001370
Reid Spencer060d25d2004-06-29 23:29:38 +00001371 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001372 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001373 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001374
Reid Spencer060d25d2004-06-29 23:29:38 +00001375 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001376 const Type* ElemType = ATy->getElementType();
1377 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1378 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001379
Reid Spencer060d25d2004-06-29 23:29:38 +00001380 // Create the constant, inserting it as needed.
1381 Constant *C = ConstantArray::get(ATy, Elements);
1382 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001383 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001384 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001385 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001386}
1387
Reid Spencer04cde2c2004-07-04 11:33:49 +00001388/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001389void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001390 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001391 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001392 if (Handler) Handler->handleGlobalConstantsBegin();
1393
1394 /// In LLVM 1.3 Type does not derive from Value so the types
1395 /// do not occupy a plane. Consequently, we read the types
1396 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001397 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001398 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001399 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001400 }
1401
Reid Spencer46b002c2004-07-11 17:28:43 +00001402 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001404 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001405
Reid Spencerd798a512006-11-14 04:47:22 +00001406 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001407 /// Use of Type::VoidTyID is a misnomer. It actually means
1408 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1410 ParseStringConstants(NumEntries, Tab);
1411 } else {
1412 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001413 Value *V = ParseConstantPoolValue(Typ);
1414 assert(V && "ParseConstantPoolValue returned NULL!");
1415 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001416
Reid Spencer060d25d2004-06-29 23:29:38 +00001417 // If we are reading a function constant table, make sure that we adjust
1418 // the slot number to be the real global constant number.
1419 //
1420 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1421 ModuleValues[Typ])
1422 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001423 if (Constant *C = dyn_cast<Constant>(V))
1424 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001425 }
1426 }
1427 }
Chris Lattner02dce162004-12-04 05:28:27 +00001428
1429 // After we have finished parsing the constant pool, we had better not have
1430 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001431 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001432 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001433 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001434 error(utostr(ConstantFwdRefs.size()) +
1435 " unresolved constant reference exist. First one is '" +
1436 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001437 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001438 }
Chris Lattner02dce162004-12-04 05:28:27 +00001439
Reid Spencer060d25d2004-06-29 23:29:38 +00001440 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001441 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001442}
Chris Lattner00950542001-06-06 20:29:01 +00001443
Reid Spencer04cde2c2004-07-04 11:33:49 +00001444/// Parse the contents of a function. Note that this function can be
1445/// called lazily by materializeFunction
1446/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001447void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001448
1449 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001450 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001451 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001452
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001453 unsigned rWord = read_vbr_uint();
1454 unsigned LinkageID = rWord & 65535;
1455 unsigned VisibilityID = rWord >> 16;
1456 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001457 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1458 case 1: Linkage = GlobalValue::WeakLinkage; break;
1459 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1460 case 3: Linkage = GlobalValue::InternalLinkage; break;
1461 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001462 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1463 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1464 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001465 default:
Reid Spencer24399722004-07-09 22:21:33 +00001466 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 Linkage = GlobalValue::InternalLinkage;
1468 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001469 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001470 switch (VisibilityID) {
1471 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1472 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1473 default:
1474 error("Unknown visibility type: " + utostr(VisibilityID));
1475 Visibility = GlobalValue::DefaultVisibility;
1476 break;
1477 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001478
Reid Spencer46b002c2004-07-11 17:28:43 +00001479 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001480 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001481 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001482
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001483 // Keep track of how many basic blocks we have read in...
1484 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001485 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001486
Reid Spencer060d25d2004-06-29 23:29:38 +00001487 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001488 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001489 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001490 BufPtr OldAt = At;
1491 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001492
1493 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001494 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001495 if (!InsertedArguments) {
1496 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001497 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001498 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001499 InsertedArguments = true;
1500 }
1501
Reid Spencer04cde2c2004-07-04 11:33:49 +00001502 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001503 break;
1504
Reid Spencerad89bd62004-07-25 18:07:36 +00001505 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001506 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001507 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001508 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001509 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001510 InsertedArguments = true;
1511 }
1512
Misha Brukman8a96c532005-04-21 21:44:41 +00001513 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001514 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001515 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001516 break;
1517 }
1518
Reid Spencer78d033e2007-01-06 07:24:44 +00001519 case BytecodeFormat::ValueSymbolTableBlockID:
1520 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1521 break;
1522
1523 case BytecodeFormat::TypeSymbolTableBlockID:
1524 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001525 break;
1526
1527 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001528 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001529 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001530 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001531 break;
1532 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001533 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001534 }
1535
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001536 // Make sure there were no references to non-existant basic blocks.
1537 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001538 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001539
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001540 ParsedBasicBlocks.clear();
1541
Chris Lattner97330cf2003-10-09 23:10:14 +00001542 // Resolve forward references. Replace any uses of a forward reference value
1543 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001544 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001545 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1546 I = ForwardReferences.begin();
1547 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001548 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001549 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001550 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001551 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001552 }
Chris Lattner00950542001-06-06 20:29:01 +00001553
Misha Brukman12c29d12003-09-22 23:38:23 +00001554 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001555 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001556 freeTable(FunctionValues);
1557
Reid Spencer04cde2c2004-07-04 11:33:49 +00001558 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001559}
1560
Reid Spencer04cde2c2004-07-04 11:33:49 +00001561/// This function parses LLVM functions lazily. It obtains the type of the
1562/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001563/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001564/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001565void BytecodeReader::ParseFunctionLazily() {
1566 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001567 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001568
Reid Spencer060d25d2004-06-29 23:29:38 +00001569 Function *Func = FunctionSignatureList.back();
1570 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001571
Reid Spencer060d25d2004-06-29 23:29:38 +00001572 // Save the information for future reading of the function
1573 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001574
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001575 // This function has a body but it's not loaded so it appears `External'.
1576 // Mark it as a `Ghost' instead to notify the users that it has a body.
1577 Func->setLinkage(GlobalValue::GhostLinkage);
1578
Reid Spencer060d25d2004-06-29 23:29:38 +00001579 // Pretend we've `parsed' this function
1580 At = BlockEnd;
1581}
Chris Lattner89e02532004-01-18 21:08:15 +00001582
Misha Brukman8a96c532005-04-21 21:44:41 +00001583/// The ParserFunction method lazily parses one function. Use this method to
1584/// casue the parser to parse a specific function in the module. Note that
1585/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001586/// ParseAllFunctionBodies.
1587/// @see ParseAllFunctionBodies
1588/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001589bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1590
Reid Spencer9b84ad12006-12-15 19:49:23 +00001591 if (setjmp(context)) {
1592 // Set caller's error message, if requested
1593 if (ErrMsg)
1594 *ErrMsg = ErrorMsg;
1595 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001596 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001597 }
Reid Spencer99655e12006-08-25 19:54:53 +00001598
Reid Spencer060d25d2004-06-29 23:29:38 +00001599 // Find {start, end} pointers and slot in the map. If not there, we're done.
1600 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001601
Reid Spencer060d25d2004-06-29 23:29:38 +00001602 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001603 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001604 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001605 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001606 }
1607
Reid Spencer060d25d2004-06-29 23:29:38 +00001608 BlockStart = At = Fi->second.Buf;
1609 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001610 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001611
1612 LazyFunctionLoadMap.erase(Fi);
1613
Reid Spencer46b002c2004-07-11 17:28:43 +00001614 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001615 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001616}
1617
Reid Spencer04cde2c2004-07-04 11:33:49 +00001618/// The ParseAllFunctionBodies method parses through all the previously
1619/// unparsed functions in the bytecode file. If you want to completely parse
1620/// a bytecode file, this method should be called after Parsebytecode because
1621/// Parsebytecode only records the locations in the bytecode file of where
1622/// the function definitions are located. This function uses that information
1623/// to materialize the functions.
1624/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001625bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001626 if (setjmp(context)) {
1627 // Set caller's error message, if requested
1628 if (ErrMsg)
1629 *ErrMsg = ErrorMsg;
1630 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001631 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001632 }
Reid Spencer99655e12006-08-25 19:54:53 +00001633
Reid Spencer060d25d2004-06-29 23:29:38 +00001634 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1635 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001636
Reid Spencer46b002c2004-07-11 17:28:43 +00001637 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001638 Function* Func = Fi->first;
1639 BlockStart = At = Fi->second.Buf;
1640 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001641 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001642 ++Fi;
1643 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001644 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001645 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001646}
Chris Lattner89e02532004-01-18 21:08:15 +00001647
Reid Spencer04cde2c2004-07-04 11:33:49 +00001648/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001649void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001650 // Read the number of types
1651 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001652 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001653}
1654
Reid Spencer04cde2c2004-07-04 11:33:49 +00001655/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001656void BytecodeReader::ParseModuleGlobalInfo() {
1657
Reid Spencer04cde2c2004-07-04 11:33:49 +00001658 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001659
Chris Lattner404cddf2005-11-12 01:33:40 +00001660 // SectionID - If a global has an explicit section specified, this map
1661 // remembers the ID until we can translate it into a string.
1662 std::map<GlobalValue*, unsigned> SectionID;
1663
Chris Lattner70cc3392001-09-10 07:58:01 +00001664 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001665 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001666 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001667 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1668 // Linkage, bit4+ = slot#
1669 unsigned SlotNo = VarType >> 5;
1670 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001671 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001672 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001673 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001674 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001675 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001676
1677 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1678 if (LinkageID == 3 && !hasInitializer) {
1679 unsigned ExtWord = read_vbr_uint();
1680 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001681 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1682 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001683 hasInitializer = ExtWord & 1;
1684 LinkageID = (ExtWord >> 1) & 7;
1685 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001686 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001687
1688 if (ExtWord & (1 << 9)) // Has a section ID.
1689 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001690 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001691
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001692 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001693 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001694 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1695 case 1: Linkage = GlobalValue::WeakLinkage; break;
1696 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1697 case 3: Linkage = GlobalValue::InternalLinkage; break;
1698 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001699 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1700 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1701 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001702 default:
Reid Spencer24399722004-07-09 22:21:33 +00001703 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001704 Linkage = GlobalValue::InternalLinkage;
1705 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001706 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001707 GlobalValue::VisibilityTypes Visibility;
1708 switch (VisibilityID) {
1709 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1710 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1711 default:
1712 error("Unknown visibility type: " + utostr(VisibilityID));
1713 Visibility = GlobalValue::DefaultVisibility;
1714 break;
1715 }
1716
Chris Lattnere3869c82003-04-16 21:16:05 +00001717 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001718 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001719 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001720
Chris Lattnere73bd452005-11-06 07:43:39 +00001721 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001722 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001723
Chris Lattner52e20b02003-03-19 20:54:26 +00001724 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001725
Chris Lattner70cc3392001-09-10 07:58:01 +00001726 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001727 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001728 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001729 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001730 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001731 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001732
Chris Lattner404cddf2005-11-12 01:33:40 +00001733 if (GlobalSectionID != 0)
1734 SectionID[GV] = GlobalSectionID;
1735
Reid Spencer060d25d2004-06-29 23:29:38 +00001736 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001737 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001738 initSlot = read_vbr_uint();
1739 GlobalInits.push_back(std::make_pair(GV, initSlot));
1740 }
1741
1742 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001743 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001744 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1745 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001746
1747 // Get next item
1748 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001749 }
1750
Chris Lattner52e20b02003-03-19 20:54:26 +00001751 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001752 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001753
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001754 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001755 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1756 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001757 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001758 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001759 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001760 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001761 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001762
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001763 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001764 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001765 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001766
Chris Lattner18549c22004-11-15 21:43:03 +00001767 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001768 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001769 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001770
Chris Lattnere73bd452005-11-06 07:43:39 +00001771 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001772
1773 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001774 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001775
Chris Lattner97fbc502004-11-15 22:38:52 +00001776 // Save this for later so we know type of lazily instantiated functions.
1777 // Note that known-external functions do not have FunctionInfo blocks, so we
1778 // do not add them to the FunctionSignatureList.
1779 if ((Flags & (1 << 4)) == 0)
1780 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001781
Chris Lattnere73bd452005-11-06 07:43:39 +00001782 // Get the calling convention from the low bits.
1783 unsigned CC = Flags & 15;
1784 unsigned Alignment = 0;
1785 if (FnSignature & (1 << 31)) { // Has extension word?
1786 unsigned ExtWord = read_vbr_uint();
1787 Alignment = (1 << (ExtWord & 31)) >> 1;
1788 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001789
1790 if (ExtWord & (1 << 10)) // Has a section ID.
1791 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001792
1793 // Parse external declaration linkage
1794 switch ((ExtWord >> 11) & 3) {
1795 case 0: break;
1796 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1797 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1798 default: assert(0 && "Unsupported external linkage");
1799 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001800 }
1801
Chris Lattner54b369e2005-11-06 07:46:13 +00001802 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001803 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001804
Reid Spencer04cde2c2004-07-04 11:33:49 +00001805 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001806
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001807 // Get the next function signature.
1808 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001809 }
1810
Misha Brukman8a96c532005-04-21 21:44:41 +00001811 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001812 // remove elements efficiently from the back of the vector.
1813 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001814
Chris Lattner404cddf2005-11-12 01:33:40 +00001815 /// SectionNames - This contains the list of section names encoded in the
1816 /// moduleinfoblock. Functions and globals with an explicit section index
1817 /// into this to get their section name.
1818 std::vector<std::string> SectionNames;
1819
Reid Spencerd798a512006-11-14 04:47:22 +00001820 // Read in the dependent library information.
1821 unsigned num_dep_libs = read_vbr_uint();
1822 std::string dep_lib;
1823 while (num_dep_libs--) {
1824 dep_lib = read_str();
1825 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001826 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001827 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001828 }
1829
Reid Spencerd798a512006-11-14 04:47:22 +00001830 // Read target triple and place into the module.
1831 std::string triple = read_str();
1832 TheModule->setTargetTriple(triple);
1833 if (Handler)
1834 Handler->handleTargetTriple(triple);
1835
Reid Spenceraacc35a2007-01-26 08:10:24 +00001836 // Read the data layout string and place into the module.
1837 std::string datalayout = read_str();
1838 TheModule->setDataLayout(datalayout);
1839 // FIXME: Implement
1840 // if (Handler)
1841 // Handler->handleDataLayout(datalayout);
1842
Reid Spencerd798a512006-11-14 04:47:22 +00001843 if (At != BlockEnd) {
1844 // If the file has section info in it, read the section names now.
1845 unsigned NumSections = read_vbr_uint();
1846 while (NumSections--)
1847 SectionNames.push_back(read_str());
1848 }
1849
1850 // If the file has module-level inline asm, read it now.
1851 if (At != BlockEnd)
1852 TheModule->setModuleInlineAsm(read_str());
1853
Chris Lattner404cddf2005-11-12 01:33:40 +00001854 // If any globals are in specified sections, assign them now.
1855 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1856 SectionID.end(); I != E; ++I)
1857 if (I->second) {
1858 if (I->second > SectionID.size())
1859 error("SectionID out of range for global!");
1860 I->first->setSection(SectionNames[I->second-1]);
1861 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001862
Chris Lattner00950542001-06-06 20:29:01 +00001863 // This is for future proofing... in the future extra fields may be added that
1864 // we don't understand, so we transparently ignore them.
1865 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001866 At = BlockEnd;
1867
Reid Spencer04cde2c2004-07-04 11:33:49 +00001868 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001869}
1870
Reid Spencer04cde2c2004-07-04 11:33:49 +00001871/// Parse the version information and decode it by setting flags on the
1872/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001873void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001874 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001875
Reid Spencer3795ad12006-12-03 05:47:10 +00001876 // We don't provide backwards compatibility in the Reader any more. To
1877 // upgrade, the user should use llvm-upgrade.
1878 if (RevisionNum < 7)
1879 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001880
Reid Spenceraacc35a2007-01-26 08:10:24 +00001881 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001882}
1883
Reid Spencer04cde2c2004-07-04 11:33:49 +00001884/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001885void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001886 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001887
Reid Spencer060d25d2004-06-29 23:29:38 +00001888 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001889
1890 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001891 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001892
Reid Spencer060d25d2004-06-29 23:29:38 +00001893 bool SeenModuleGlobalInfo = false;
1894 bool SeenGlobalTypePlane = false;
1895 BufPtr MyEnd = BlockEnd;
1896 while (At < MyEnd) {
1897 BufPtr OldAt = At;
1898 read_block(Type, Size);
1899
Chris Lattner00950542001-06-06 20:29:01 +00001900 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001901
Reid Spencerad89bd62004-07-25 18:07:36 +00001902 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001903 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001904 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001905
Reid Spencer5b472d92004-08-21 20:49:23 +00001906 if (Size > 0)
1907 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001908 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001909 break;
1910
Misha Brukman8a96c532005-04-21 21:44:41 +00001911 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001912 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001913 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001914 ParseModuleGlobalInfo();
1915 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001916 break;
1917
Reid Spencerad89bd62004-07-25 18:07:36 +00001918 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001919 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001920 break;
1921
Reid Spencerad89bd62004-07-25 18:07:36 +00001922 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001923 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001924 break;
Chris Lattner00950542001-06-06 20:29:01 +00001925
Reid Spencer78d033e2007-01-06 07:24:44 +00001926 case BytecodeFormat::ValueSymbolTableBlockID:
1927 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1928 break;
1929
1930 case BytecodeFormat::TypeSymbolTableBlockID:
1931 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001932 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001933
Chris Lattner00950542001-06-06 20:29:01 +00001934 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001935 At += Size;
1936 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001937 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001938 }
Chris Lattner00950542001-06-06 20:29:01 +00001939 break;
1940 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001941 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001942 }
1943
Chris Lattner52e20b02003-03-19 20:54:26 +00001944 // After the module constant pool has been read, we can safely initialize
1945 // global variables...
1946 while (!GlobalInits.empty()) {
1947 GlobalVariable *GV = GlobalInits.back().first;
1948 unsigned Slot = GlobalInits.back().second;
1949 GlobalInits.pop_back();
1950
1951 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001952 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001953
1954 const llvm::PointerType* GVType = GV->getType();
1955 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001956 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001957 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001958 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001959 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001960 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001961 } else
Reid Spencer24399722004-07-09 22:21:33 +00001962 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001963 }
1964
Chris Lattneraba5ff52005-05-05 20:57:00 +00001965 if (!ConstantFwdRefs.empty())
1966 error("Use of undefined constants in a module");
1967
Reid Spencer060d25d2004-06-29 23:29:38 +00001968 /// Make sure we pulled them all out. If we didn't then there's a declaration
1969 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001970 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001971 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001972}
1973
Reid Spencer04cde2c2004-07-04 11:33:49 +00001974/// This function completely parses a bytecode buffer given by the \p Buf
1975/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00001976bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00001977 const std::string &ModuleID,
1978 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001979
Reid Spencer233fe722006-08-22 16:09:19 +00001980 /// We handle errors by
1981 if (setjmp(context)) {
1982 // Cleanup after error
1983 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00001984 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001985 delete TheModule;
1986 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00001987 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00001988 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00001989 decompressedBlock = 0;
1990 }
Reid Spencer233fe722006-08-22 16:09:19 +00001991 // Set caller's error message, if requested
1992 if (ErrMsg)
1993 *ErrMsg = ErrorMsg;
1994 // Indicate an error occurred
1995 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001996 }
Reid Spencer233fe722006-08-22 16:09:19 +00001997
1998 RevisionNum = 0;
1999 At = MemStart = BlockStart = Buf;
2000 MemEnd = BlockEnd = Buf + Length;
2001
2002 // Create the module
2003 TheModule = new Module(ModuleID);
2004
2005 if (Handler) Handler->handleStart(TheModule, Length);
2006
2007 // Read the four bytes of the signature.
2008 unsigned Sig = read_uint();
2009
2010 // If this is a compressed file
2011 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2012
2013 // Invoke the decompression of the bytecode. Note that we have to skip the
2014 // file's magic number which is not part of the compressed block. Hence,
2015 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2016 // member for retention until BytecodeReader is destructed.
2017 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2018 (char*)Buf+4,Length-4,decompressedBlock);
2019
2020 // We must adjust the buffer pointers used by the bytecode reader to point
2021 // into the new decompressed block. After decompression, the
2022 // decompressedBlock will point to a contiguous memory area that has
2023 // the decompressed data.
2024 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2025 MemEnd = BlockEnd = Buf + decompressedLength;
2026
2027 // else if this isn't a regular (uncompressed) bytecode file, then its
2028 // and error, generate that now.
2029 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2030 error("Invalid bytecode signature: " + utohexstr(Sig));
2031 }
2032
2033 // Tell the handler we're starting a module
2034 if (Handler) Handler->handleModuleBegin(ModuleID);
2035
2036 // Get the module block and size and verify. This is handled specially
2037 // because the module block/size is always written in long format. Other
2038 // blocks are written in short format so the read_block method is used.
2039 unsigned Type, Size;
2040 Type = read_uint();
2041 Size = read_uint();
2042 if (Type != BytecodeFormat::ModuleBlockID) {
2043 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2044 + utostr(Size));
2045 }
2046
2047 // It looks like the darwin ranlib program is broken, and adds trailing
2048 // garbage to the end of some bytecode files. This hack allows the bc
2049 // reader to ignore trailing garbage on bytecode files.
2050 if (At + Size < MemEnd)
2051 MemEnd = BlockEnd = At+Size;
2052
2053 if (At + Size != MemEnd)
2054 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2055 + ", Size:" + utostr(Size));
2056
2057 // Parse the module contents
2058 this->ParseModule();
2059
2060 // Check for missing functions
2061 if (hasFunctions())
2062 error("Function expected, but bytecode stream ended!");
2063
Reid Spencer233fe722006-08-22 16:09:19 +00002064 // Tell the handler we're done with the module
2065 if (Handler)
2066 Handler->handleModuleEnd(ModuleID);
2067
2068 // Tell the handler we're finished the parse
2069 if (Handler) Handler->handleFinish();
2070
2071 return false;
2072
Chris Lattner00950542001-06-06 20:29:01 +00002073}
Reid Spencer060d25d2004-06-29 23:29:38 +00002074
2075//===----------------------------------------------------------------------===//
2076//=== Default Implementations of Handler Methods
2077//===----------------------------------------------------------------------===//
2078
2079BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002080