blob: 376c0702a3e77b36a7c9a29ccf1c7e7928210f96 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000024#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000025#include "llvm/Instructions.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000026#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000028#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000030#include "llvm/Support/MathExtras.h"
Chris Lattner4c3d3a92007-01-31 19:56:15 +000031#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000033#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000034#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Reid Spencer46b002c2004-07-11 17:28:43 +000037namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000038 /// @brief A class for maintaining the slot number definition
39 /// as a placeholder for the actual definition for forward constants defs.
40 class ConstantPlaceHolder : public ConstantExpr {
41 ConstantPlaceHolder(); // DO NOT IMPLEMENT
42 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
43 public:
Chris Lattner61323322005-01-31 01:11:13 +000044 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000045 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000046 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000047 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000048 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000049 };
Reid Spencer46b002c2004-07-11 17:28:43 +000050}
Reid Spencer060d25d2004-06-29 23:29:38 +000051
Reid Spencer24399722004-07-09 22:21:33 +000052// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000053inline void BytecodeReader::error(const std::string& err) {
54 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
55 + itostr(At-MemStart) + ")";
Reid Spenceref9b9a72007-02-05 20:47:22 +000056 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer233fe722006-08-22 16:09:19 +000057 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000078 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000079 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000080 At += 4;
81 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
82}
83
Reid Spencer04cde2c2004-07-04 11:33:49 +000084/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000085inline unsigned BytecodeReader::read_vbr_uint() {
86 unsigned Shift = 0;
87 unsigned Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +000088
Reid Spencer060d25d2004-06-29 23:29:38 +000089 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000090 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000091 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000092 Result |= (unsigned)((*At++) & 0x7F) << Shift;
93 Shift += 7;
94 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +000095 return Result;
96}
97
Reid Spencer04cde2c2004-07-04 11:33:49 +000098/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +000099inline uint64_t BytecodeReader::read_vbr_uint64() {
100 unsigned Shift = 0;
101 uint64_t Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +0000102
Reid Spencer060d25d2004-06-29 23:29:38 +0000103 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000104 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000105 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
107 Shift += 7;
108 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 return Result;
110}
111
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000113inline int64_t BytecodeReader::read_vbr_int64() {
114 uint64_t R = read_vbr_uint64();
115 if (R & 1) {
116 if (R != 1)
117 return -(int64_t)(R >> 1);
118 else // There is no such thing as -0 with integers. "-0" really means
119 // 0x8000000000000000.
120 return 1LL << 63;
121 } else
122 return (int64_t)(R >> 1);
123}
124
Reid Spencer04cde2c2004-07-04 11:33:49 +0000125/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000126inline std::string BytecodeReader::read_str() {
127 unsigned Size = read_vbr_uint();
128 const unsigned char *OldAt = At;
129 At += Size;
130 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000131 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000132 return std::string((char*)OldAt, Size);
133}
134
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000135void BytecodeReader::read_str(SmallVectorImpl<char> &StrData) {
136 StrData.clear();
137 unsigned Size = read_vbr_uint();
138 const unsigned char *OldAt = At;
139 At += Size;
140 if (At > BlockEnd) // Size invalid?
141 error("Ran out of data reading a string!");
142 StrData.append(OldAt, At);
143}
144
145
Reid Spencer04cde2c2004-07-04 11:33:49 +0000146/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000147inline void BytecodeReader::read_data(void *Ptr, void *End) {
148 unsigned char *Start = (unsigned char *)Ptr;
149 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000150 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000151 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000152 std::copy(At, At+Amount, Start);
153 At += Amount;
154}
155
Reid Spencer46b002c2004-07-11 17:28:43 +0000156/// Read a float value in little-endian order
157inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000158 /// FIXME: This isn't optimal, it has size problems on some platforms
159 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000160 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000161 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000162}
163
164/// Read a double value in little-endian order
165inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000166 /// FIXME: This isn't optimal, it has size problems on some platforms
167 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000168 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
169 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
170 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
171 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000172 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000173}
174
Reid Spencer04cde2c2004-07-04 11:33:49 +0000175/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000176inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000177 Size = read_uint(); // Read the header
178 Type = Size & 0x1F; // mask low order five bits to get type
179 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000180 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000181 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000182 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000183 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000184 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000185}
186
Reid Spencer060d25d2004-06-29 23:29:38 +0000187//===----------------------------------------------------------------------===//
188// IR Lookup Methods
189//===----------------------------------------------------------------------===//
190
Reid Spencer04cde2c2004-07-04 11:33:49 +0000191/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000192inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000193 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000194}
195
Reid Spencerd2bb8872007-01-30 19:36:46 +0000196/// Obtain a type given a typeid and account for things like function level vs
197/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000198const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000199 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000200 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000201 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000202
203 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000204 ID -= Type::FirstDerivedTyID;
205
Chris Lattner36392bc2003-10-08 21:18:57 +0000206 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000207 if (ID < ModuleTypes.size())
208 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000209
Reid Spencer46b002c2004-07-11 17:28:43 +0000210 // Nope, is it a function-level type?
211 ID -= ModuleTypes.size();
212 if (ID < FunctionTypes.size())
213 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000214
Reid Spencer46b002c2004-07-11 17:28:43 +0000215 error("Illegal type reference!");
216 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000217}
218
Reid Spencer3795ad12006-12-03 05:47:10 +0000219/// This method just saves some coding. It uses read_vbr_uint to read in a
220/// type id, errors that its not the type type, and then calls getType to
221/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000222inline const Type* BytecodeReader::readType() {
223 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000224}
225
226/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000227/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000228unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
229 if (Ty->isPrimitiveType())
230 return Ty->getTypeID();
231
Reid Spencer060d25d2004-06-29 23:29:38 +0000232 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000233 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
234 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000235
236 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000237 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000238 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000239
Chris Lattnereebac5f2005-10-03 21:26:53 +0000240 // If we don't have our cache yet, build it now.
241 if (ModuleTypeIDCache.empty()) {
242 unsigned N = 0;
243 ModuleTypeIDCache.reserve(ModuleTypes.size());
244 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
245 I != E; ++I, ++N)
246 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
247
248 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
249 }
250
251 // Binary search the cache for the entry.
252 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
253 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
254 std::make_pair(Ty, 0U));
255 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000256 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000257
258 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000259}
260
Misha Brukman8a96c532005-04-21 21:44:41 +0000261/// Retrieve a value of a given type and slot number, possibly creating
262/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000263Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000264 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000265 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000266
Reid Spencerd2bb8872007-01-30 19:36:46 +0000267 // By default, the global type id is the type id passed in
268 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000269
Reid Spencerd2bb8872007-01-30 19:36:46 +0000270 if (hasImplicitNull(GlobalTyID)) {
271 const Type *Ty = getType(type);
272 if (!isa<OpaqueType>(Ty)) {
273 if (Num == 0)
274 return Constant::getNullValue(Ty);
275 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000276 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000277 }
Chris Lattner89e02532004-01-18 21:08:15 +0000278
Reid Spencerd2bb8872007-01-30 19:36:46 +0000279 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
280 if (Num < ModuleValues[GlobalTyID]->size())
281 return ModuleValues[GlobalTyID]->getOperand(Num);
282 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner52e20b02003-03-19 20:54:26 +0000283 }
284
Misha Brukman8a96c532005-04-21 21:44:41 +0000285 if (FunctionValues.size() > type &&
286 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000287 Num < FunctionValues[type]->size())
288 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000289
Chris Lattner74734132002-08-17 22:01:27 +0000290 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000291
Reid Spencer551ccae2004-09-01 22:55:40 +0000292 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000293 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000294 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000295 if (I != ForwardReferences.end() && I->first == KeyValue)
296 return I->second; // We have already created this placeholder
297
Reid Spencer551ccae2004-09-01 22:55:40 +0000298 // If the type exists (it should)
299 if (const Type* Ty = getType(type)) {
300 // Create the place holder
301 Value *Val = new Argument(Ty);
302 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
303 return Val;
304 }
Reid Spencer233fe722006-08-22 16:09:19 +0000305 error("Can't create placeholder for value of type slot #" + utostr(type));
306 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000307}
308
Reid Spencer060d25d2004-06-29 23:29:38 +0000309
Reid Spencer04cde2c2004-07-04 11:33:49 +0000310/// Just like getValue, except that it returns a null pointer
311/// only on error. It always returns a constant (meaning that if the value is
312/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000313/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000314/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000315Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
316 if (Value *V = getValue(TypeSlot, Slot, false))
317 if (Constant *C = dyn_cast<Constant>(V))
318 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000319 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000320 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000321 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000322
Chris Lattner389bd042004-12-09 06:19:44 +0000323 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000324 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
325
326 if (I != ConstantFwdRefs.end() && I->first == Key) {
327 return I->second;
328 } else {
329 // Create a placeholder for the constant reference and
330 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000331 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000332
Reid Spencer060d25d2004-06-29 23:29:38 +0000333 // Keep track of the fact that we have a forward ref to recycle it
334 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
335 return C;
336 }
337}
338
339//===----------------------------------------------------------------------===//
340// IR Construction Methods
341//===----------------------------------------------------------------------===//
342
Reid Spencer04cde2c2004-07-04 11:33:49 +0000343/// As values are created, they are inserted into the appropriate place
344/// with this method. The ValueTable argument must be one of ModuleValues
345/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000346unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000347 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000348 if (ValueTab.size() <= type)
349 ValueTab.resize(type+1);
350
351 if (!ValueTab[type]) ValueTab[type] = new ValueList();
352
353 ValueTab[type]->push_back(Val);
354
Chris Lattneraba5ff52005-05-05 20:57:00 +0000355 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000356 return ValueTab[type]->size()-1 + HasOffset;
357}
358
Reid Spencer04cde2c2004-07-04 11:33:49 +0000359/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000360void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000361 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000362 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000363 for (FunctionType::param_iterator It = FT->param_begin();
364 It != FT->param_end(); ++It, ++AI)
365 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
366}
367
368//===----------------------------------------------------------------------===//
369// Bytecode Parsing Methods
370//===----------------------------------------------------------------------===//
371
Reid Spencer04cde2c2004-07-04 11:33:49 +0000372/// This method parses a single instruction. The instruction is
373/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000374/// the instruction are provided in the \p Oprnds vector.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000375void BytecodeReader::ParseInstruction(SmallVector<unsigned, 8> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000376 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000377 BufPtr SaveAt = At;
378
379 // Clear instruction data
380 Oprnds.clear();
381 unsigned iType = 0;
382 unsigned Opcode = 0;
383 unsigned Op = read_uint();
384
385 // bits Instruction format: Common to all formats
386 // --------------------------
387 // 01-00: Opcode type, fixed to 1.
388 // 07-02: Opcode
389 Opcode = (Op >> 2) & 63;
390 Oprnds.resize((Op >> 0) & 03);
391
392 // Extract the operands
393 switch (Oprnds.size()) {
394 case 1:
395 // bits Instruction format:
396 // --------------------------
397 // 19-08: Resulting type plane
398 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
399 //
400 iType = (Op >> 8) & 4095;
401 Oprnds[0] = (Op >> 20) & 4095;
402 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
403 Oprnds.resize(0);
404 break;
405 case 2:
406 // bits Instruction format:
407 // --------------------------
408 // 15-08: Resulting type plane
409 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000410 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000411 //
412 iType = (Op >> 8) & 255;
413 Oprnds[0] = (Op >> 16) & 255;
414 Oprnds[1] = (Op >> 24) & 255;
415 break;
416 case 3:
417 // bits Instruction format:
418 // --------------------------
419 // 13-08: Resulting type plane
420 // 19-14: Operand #1
421 // 25-20: Operand #2
422 // 31-26: Operand #3
423 //
424 iType = (Op >> 8) & 63;
425 Oprnds[0] = (Op >> 14) & 63;
426 Oprnds[1] = (Op >> 20) & 63;
427 Oprnds[2] = (Op >> 26) & 63;
428 break;
429 case 0:
430 At -= 4; // Hrm, try this again...
431 Opcode = read_vbr_uint();
432 Opcode >>= 2;
433 iType = read_vbr_uint();
434
435 unsigned NumOprnds = read_vbr_uint();
436 Oprnds.resize(NumOprnds);
437
438 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000439 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000440
441 for (unsigned i = 0; i != NumOprnds; ++i)
442 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000443 break;
444 }
445
Reid Spencerd798a512006-11-14 04:47:22 +0000446 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000447
Reid Spencer1628cec2006-10-26 06:15:43 +0000448 // Make the necessary adjustments for dealing with backwards compatibility
449 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000450 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000451
Reid Spencer3795ad12006-12-03 05:47:10 +0000452 // First, handle the easy binary operators case
453 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000454 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000455 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
456 getValue(iType, Oprnds[0]),
457 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000458 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000459 // Indicate that we don't think this is a call instruction (yet).
460 // Process based on the Opcode read
461 switch (Opcode) {
462 default: // There was an error, this shouldn't happen.
463 if (Result == 0)
464 error("Illegal instruction read!");
465 break;
466 case Instruction::VAArg:
467 if (Oprnds.size() != 2)
468 error("Invalid VAArg instruction!");
469 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000470 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000471 break;
472 case Instruction::ExtractElement: {
473 if (Oprnds.size() != 2)
474 error("Invalid extractelement instruction!");
475 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000476 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000477
Reid Spencer1628cec2006-10-26 06:15:43 +0000478 if (!ExtractElementInst::isValidOperands(V1, V2))
479 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000480
Reid Spencer1628cec2006-10-26 06:15:43 +0000481 Result = new ExtractElementInst(V1, V2);
482 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000483 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000484 case Instruction::InsertElement: {
485 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
486 if (!PackedTy || Oprnds.size() != 3)
487 error("Invalid insertelement instruction!");
488
489 Value *V1 = getValue(iType, Oprnds[0]);
490 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000491 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000492
493 if (!InsertElementInst::isValidOperands(V1, V2, V3))
494 error("Invalid insertelement instruction!");
495 Result = new InsertElementInst(V1, V2, V3);
496 break;
497 }
498 case Instruction::ShuffleVector: {
499 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
500 if (!PackedTy || Oprnds.size() != 3)
501 error("Invalid shufflevector instruction!");
502 Value *V1 = getValue(iType, Oprnds[0]);
503 Value *V2 = getValue(iType, Oprnds[1]);
504 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000505 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000506 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
507 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
508 error("Invalid shufflevector instruction!");
509 Result = new ShuffleVectorInst(V1, V2, V3);
510 break;
511 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000512 case Instruction::Trunc:
513 if (Oprnds.size() != 2)
514 error("Invalid cast instruction!");
515 Result = new TruncInst(getValue(iType, Oprnds[0]),
516 getType(Oprnds[1]));
517 break;
518 case Instruction::ZExt:
519 if (Oprnds.size() != 2)
520 error("Invalid cast instruction!");
521 Result = new ZExtInst(getValue(iType, Oprnds[0]),
522 getType(Oprnds[1]));
523 break;
524 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000525 if (Oprnds.size() != 2)
526 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000527 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000528 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000529 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000530 case Instruction::FPTrunc:
531 if (Oprnds.size() != 2)
532 error("Invalid cast instruction!");
533 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
534 getType(Oprnds[1]));
535 break;
536 case Instruction::FPExt:
537 if (Oprnds.size() != 2)
538 error("Invalid cast instruction!");
539 Result = new FPExtInst(getValue(iType, Oprnds[0]),
540 getType(Oprnds[1]));
541 break;
542 case Instruction::UIToFP:
543 if (Oprnds.size() != 2)
544 error("Invalid cast instruction!");
545 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
546 getType(Oprnds[1]));
547 break;
548 case Instruction::SIToFP:
549 if (Oprnds.size() != 2)
550 error("Invalid cast instruction!");
551 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
552 getType(Oprnds[1]));
553 break;
554 case Instruction::FPToUI:
555 if (Oprnds.size() != 2)
556 error("Invalid cast instruction!");
557 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
558 getType(Oprnds[1]));
559 break;
560 case Instruction::FPToSI:
561 if (Oprnds.size() != 2)
562 error("Invalid cast instruction!");
563 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
564 getType(Oprnds[1]));
565 break;
566 case Instruction::IntToPtr:
567 if (Oprnds.size() != 2)
568 error("Invalid cast instruction!");
569 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
570 getType(Oprnds[1]));
571 break;
572 case Instruction::PtrToInt:
573 if (Oprnds.size() != 2)
574 error("Invalid cast instruction!");
575 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
576 getType(Oprnds[1]));
577 break;
578 case Instruction::BitCast:
579 if (Oprnds.size() != 2)
580 error("Invalid cast instruction!");
581 Result = new BitCastInst(getValue(iType, Oprnds[0]),
582 getType(Oprnds[1]));
583 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000584 case Instruction::Select:
585 if (Oprnds.size() != 3)
586 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000587 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000588 getValue(iType, Oprnds[1]),
589 getValue(iType, Oprnds[2]));
590 break;
591 case Instruction::PHI: {
592 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
593 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000594
Reid Spencer1628cec2006-10-26 06:15:43 +0000595 PHINode *PN = new PHINode(InstTy);
596 PN->reserveOperandSpace(Oprnds.size());
597 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
598 PN->addIncoming(
599 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
600 Result = PN;
601 break;
602 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000603 case Instruction::ICmp:
604 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000605 if (Oprnds.size() != 3)
606 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000607 // These instructions encode the comparison predicate as the 3rd operand.
608 Result = CmpInst::create(Instruction::OtherOps(Opcode),
609 static_cast<unsigned short>(Oprnds[2]),
610 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
611 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000612 case Instruction::Ret:
613 if (Oprnds.size() == 0)
614 Result = new ReturnInst();
615 else if (Oprnds.size() == 1)
616 Result = new ReturnInst(getValue(iType, Oprnds[0]));
617 else
618 error("Unrecognized instruction!");
619 break;
620
621 case Instruction::Br:
622 if (Oprnds.size() == 1)
623 Result = new BranchInst(getBasicBlock(Oprnds[0]));
624 else if (Oprnds.size() == 3)
625 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000626 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000627 else
628 error("Invalid number of operands for a 'br' instruction!");
629 break;
630 case Instruction::Switch: {
631 if (Oprnds.size() & 1)
632 error("Switch statement with odd number of arguments!");
633
634 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
635 getBasicBlock(Oprnds[1]),
636 Oprnds.size()/2-1);
637 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
638 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
639 getBasicBlock(Oprnds[i+1]));
640 Result = I;
641 break;
642 }
643 case 58: // Call with extra operand for calling conv
644 case 59: // tail call, Fast CC
645 case 60: // normal call, Fast CC
646 case 61: // tail call, C Calling Conv
647 case Instruction::Call: { // Normal Call, C Calling Convention
648 if (Oprnds.size() == 0)
649 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000650 Value *F = getValue(iType, Oprnds[0]);
651
652 unsigned CallingConv = CallingConv::C;
653 bool isTailCall = false;
654
655 if (Opcode == 61 || Opcode == 59)
656 isTailCall = true;
657
658 if (Opcode == 58) {
659 isTailCall = Oprnds.back() & 1;
660 CallingConv = Oprnds.back() >> 1;
661 Oprnds.pop_back();
662 } else if (Opcode == 59 || Opcode == 60) {
663 CallingConv = CallingConv::Fast;
664 }
665
666 // Check to make sure we have a pointer to function type
667 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
668 if (PTy == 0) error("Call to non function pointer value!");
669 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
670 if (FTy == 0) error("Call to non function pointer value!");
671
672 std::vector<Value *> Params;
673 if (!FTy->isVarArg()) {
674 FunctionType::param_iterator It = FTy->param_begin();
675
676 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
677 if (It == FTy->param_end())
678 error("Invalid call instruction!");
679 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
680 }
681 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000682 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000683 } else {
684 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
685
686 unsigned FirstVariableOperand;
687 if (Oprnds.size() < FTy->getNumParams())
688 error("Call instruction missing operands!");
689
690 // Read all of the fixed arguments
691 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
692 Params.push_back(
693 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
694
695 FirstVariableOperand = FTy->getNumParams();
696
697 if ((Oprnds.size()-FirstVariableOperand) & 1)
698 error("Invalid call instruction!"); // Must be pairs of type/value
699
700 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
701 i != e; i += 2)
702 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000703 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000704
Reid Spencer1628cec2006-10-26 06:15:43 +0000705 Result = new CallInst(F, Params);
706 if (isTailCall) cast<CallInst>(Result)->setTailCall();
707 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
708 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000709 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000710 case Instruction::Invoke: { // Invoke C CC
711 if (Oprnds.size() < 3)
712 error("Invalid invoke instruction!");
713 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000714
Reid Spencer1628cec2006-10-26 06:15:43 +0000715 // Check to make sure we have a pointer to function type
716 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
717 if (PTy == 0)
718 error("Invoke to non function pointer value!");
719 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
720 if (FTy == 0)
721 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000722
Reid Spencer1628cec2006-10-26 06:15:43 +0000723 std::vector<Value *> Params;
724 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000725 unsigned CallingConv = Oprnds.back();
726 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000727
Reid Spencer1628cec2006-10-26 06:15:43 +0000728 if (!FTy->isVarArg()) {
729 Normal = getBasicBlock(Oprnds[1]);
730 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000731
Reid Spencer1628cec2006-10-26 06:15:43 +0000732 FunctionType::param_iterator It = FTy->param_begin();
733 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
734 if (It == FTy->param_end())
735 error("Invalid invoke instruction!");
736 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
737 }
738 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000739 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000740 } else {
741 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
742
743 Normal = getBasicBlock(Oprnds[0]);
744 Except = getBasicBlock(Oprnds[1]);
745
746 unsigned FirstVariableArgument = FTy->getNumParams()+2;
747 for (unsigned i = 2; i != FirstVariableArgument; ++i)
748 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
749 Oprnds[i]));
750
751 // Must be type/value pairs. If not, error out.
752 if (Oprnds.size()-FirstVariableArgument & 1)
753 error("Invalid invoke instruction!");
754
755 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
756 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000757 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000758
Reid Spencer1628cec2006-10-26 06:15:43 +0000759 Result = new InvokeInst(F, Normal, Except, Params);
760 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
761 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000762 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000763 case Instruction::Malloc: {
764 unsigned Align = 0;
765 if (Oprnds.size() == 2)
766 Align = (1 << Oprnds[1]) >> 1;
767 else if (Oprnds.size() > 2)
768 error("Invalid malloc instruction!");
769 if (!isa<PointerType>(InstTy))
770 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000771
Reid Spencer1628cec2006-10-26 06:15:43 +0000772 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000773 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000774 break;
775 }
776 case Instruction::Alloca: {
777 unsigned Align = 0;
778 if (Oprnds.size() == 2)
779 Align = (1 << Oprnds[1]) >> 1;
780 else if (Oprnds.size() > 2)
781 error("Invalid alloca instruction!");
782 if (!isa<PointerType>(InstTy))
783 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000784
Reid Spencer1628cec2006-10-26 06:15:43 +0000785 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000786 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000787 break;
788 }
789 case Instruction::Free:
790 if (!isa<PointerType>(InstTy))
791 error("Invalid free instruction!");
792 Result = new FreeInst(getValue(iType, Oprnds[0]));
793 break;
794 case Instruction::GetElementPtr: {
795 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000796 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000797
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000798 SmallVector<Value*, 8> Idx;
Reid Spencer1628cec2006-10-26 06:15:43 +0000799
800 const Type *NextTy = InstTy;
801 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
802 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
803 if (!TopTy)
804 error("Invalid getelementptr instruction!");
805
806 unsigned ValIdx = Oprnds[i];
807 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000808 // Struct indices are always uints, sequential type indices can be
809 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000810 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000811 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000812 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000813 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000814 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000815 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000816 case 0: IdxTy = Int32TySlot; break;
817 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000818 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000819 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000820 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000821 Idx.push_back(getValue(IdxTy, ValIdx));
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000822 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
823 true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000824 }
825
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000826 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
827 &Idx[0], Idx.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000828 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000829 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000830 case 62: // volatile load
831 case Instruction::Load:
832 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
833 error("Invalid load instruction!");
834 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
835 break;
836 case 63: // volatile store
837 case Instruction::Store: {
838 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
839 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000840
Reid Spencer1628cec2006-10-26 06:15:43 +0000841 Value *Ptr = getValue(iType, Oprnds[1]);
842 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
843 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
844 Opcode == 63);
845 break;
846 }
847 case Instruction::Unwind:
848 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
849 Result = new UnwindInst();
850 break;
851 case Instruction::Unreachable:
852 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
853 Result = new UnreachableInst();
854 break;
855 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000856 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000857
Reid Spencere1e96c02006-01-19 07:02:16 +0000858 BB->getInstList().push_back(Result);
859
Reid Spencer060d25d2004-06-29 23:29:38 +0000860 unsigned TypeSlot;
861 if (Result->getType() == InstTy)
862 TypeSlot = iType;
863 else
864 TypeSlot = getTypeSlot(Result->getType());
865
Reid Spenceref9b9a72007-02-05 20:47:22 +0000866 // We have enough info to inform the handler now.
867 if (Handler)
Chris Lattner63cf59e2007-02-07 05:08:39 +0000868 Handler->handleInstruction(Opcode, InstTy, &Oprnds[0], Oprnds.size(),
869 Result, At-SaveAt);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000870
Reid Spencer060d25d2004-06-29 23:29:38 +0000871 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000872}
873
Reid Spencer04cde2c2004-07-04 11:33:49 +0000874/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000875/// This works together with ParseInstructionList to handle these forward
876/// references in a clean manner. This function is used when constructing
877/// phi, br, switch, and other instructions that reference basic blocks.
878/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000879BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000880 // Make sure there is room in the table...
881 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
882
Reid Spencerd798a512006-11-14 04:47:22 +0000883 // First check to see if this is a backwards reference, i.e. this block
884 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000885 // been created.
886 if (ParsedBasicBlocks[ID])
887 return ParsedBasicBlocks[ID];
888
889 // Otherwise, the basic block has not yet been created. Do so and add it to
890 // the ParsedBasicBlocks list.
891 return ParsedBasicBlocks[ID] = new BasicBlock();
892}
893
Reid Spencer04cde2c2004-07-04 11:33:49 +0000894/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000895/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000896/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000897/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000898unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000899 unsigned BlockNo = 0;
Chris Lattner63cf59e2007-02-07 05:08:39 +0000900 SmallVector<unsigned, 8> Args;
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000901
Reid Spencer46b002c2004-07-11 17:28:43 +0000902 while (moreInBlock()) {
903 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000904 BasicBlock *BB;
905 if (ParsedBasicBlocks.size() == BlockNo)
906 ParsedBasicBlocks.push_back(BB = new BasicBlock());
907 else if (ParsedBasicBlocks[BlockNo] == 0)
908 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
909 else
910 BB = ParsedBasicBlocks[BlockNo];
911 ++BlockNo;
912 F->getBasicBlockList().push_back(BB);
913
914 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000915 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000916 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000917
918 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000919 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000920
Reid Spencer46b002c2004-07-11 17:28:43 +0000921 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000922 }
923
924 return BlockNo;
925}
926
Reid Spencer78d033e2007-01-06 07:24:44 +0000927/// Parse a type symbol table.
928void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
929 // Type Symtab block header: [num entries]
930 unsigned NumEntries = read_vbr_uint();
931 for (unsigned i = 0; i < NumEntries; ++i) {
932 // Symtab entry: [type slot #][name]
933 unsigned slot = read_vbr_uint();
934 std::string Name = read_str();
935 const Type* T = getType(slot);
936 TST->insert(Name, T);
937 }
938}
939
940/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000941/// level symbol tables. For function level symbol tables, the CurrentFunction
942/// parameter must be non-zero and the ST parameter must correspond to
943/// CurrentFunction's symbol table. For Module level symbol tables, the
944/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000945void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000946 ValueSymbolTable *VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000947
Reid Spenceref9b9a72007-02-05 20:47:22 +0000948 if (Handler) Handler->handleValueSymbolTableBegin(CurrentFunction,VST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000949
Chris Lattner39cacce2003-10-10 05:43:47 +0000950 // Allow efficient basic block lookup by number.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000951 SmallVector<BasicBlock*, 32> BBMap;
Chris Lattner39cacce2003-10-10 05:43:47 +0000952 if (CurrentFunction)
953 for (Function::iterator I = CurrentFunction->begin(),
954 E = CurrentFunction->end(); I != E; ++I)
955 BBMap.push_back(I);
956
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000957 SmallVector<char, 32> NameStr;
958
Reid Spencer46b002c2004-07-11 17:28:43 +0000959 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000960 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000961 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000962 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000963
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000964 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000965 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000966 unsigned slot = read_vbr_uint();
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000967 read_str(NameStr);
Reid Spencerd798a512006-11-14 04:47:22 +0000968 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000969 if (Typ == LabelTySlot) {
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000970 V = (slot < BBMap.size()) ? BBMap[slot] : 0;
Chris Lattner39cacce2003-10-10 05:43:47 +0000971 } else {
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000972 V = getValue(Typ, slot, false); // Find mapping.
Chris Lattner39cacce2003-10-10 05:43:47 +0000973 }
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000974 if (Handler) Handler->handleSymbolTableValue(Typ, slot,
975 &NameStr[0], NameStr.size());
Reid Spencerd798a512006-11-14 04:47:22 +0000976 if (V == 0)
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000977 error("Failed value look-up for name '" +
978 std::string(NameStr.begin(), NameStr.end()) + "', type #" +
Reid Spenceref9b9a72007-02-05 20:47:22 +0000979 utostr(Typ) + " slot #" + utostr(slot));
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000980 V->setName(&NameStr[0], NameStr.size());
981
982 NameStr.clear();
Chris Lattner00950542001-06-06 20:29:01 +0000983 }
984 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000985 checkPastBlockEnd("Symbol Table");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000986 if (Handler) Handler->handleValueSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000987}
988
Reid Spencer46b002c2004-07-11 17:28:43 +0000989// Parse a single type. The typeid is read in first. If its a primitive type
990// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +0000991// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +0000992// definition.
993const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +0000994 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000995 const Type *Result = 0;
996 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
997 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +0000998
Reid Spencer060d25d2004-06-29 23:29:38 +0000999 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001000 case Type::IntegerTyID: {
1001 unsigned NumBits = read_vbr_uint();
1002 Result = IntegerType::get(NumBits);
1003 break;
1004 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001005 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001006 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +00001007 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001008
1009 unsigned NumParams = read_vbr_uint();
1010
1011 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +00001012 std::vector<FunctionType::ParameterAttributes> Attrs;
1013 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1014 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001015 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001016 if (Params.back() != Type::VoidTy)
1017 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1018 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001019
1020 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1021 if (isVarArg) Params.pop_back();
1022
Reid Spencer88cfda22006-12-31 05:44:24 +00001023 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001024 break;
1025 }
1026 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001027 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001028 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001029 Result = ArrayType::get(ElementType, NumElements);
1030 break;
1031 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001032 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001033 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001034 unsigned NumElements = read_vbr_uint();
1035 Result = PackedType::get(ElementType, NumElements);
1036 break;
1037 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001038 case Type::StructTyID: {
1039 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001040 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001041 while (Typ) { // List is terminated by void/0 typeid
1042 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001043 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001044 }
1045
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001046 Result = StructType::get(Elements, false);
1047 break;
1048 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001049 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001050 std::vector<const Type*> Elements;
1051 unsigned Typ = read_vbr_uint();
1052 while (Typ) { // List is terminated by void/0 typeid
1053 Elements.push_back(getType(Typ));
1054 Typ = read_vbr_uint();
1055 }
1056
1057 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001058 break;
1059 }
1060 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001061 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001062 break;
1063 }
1064
1065 case Type::OpaqueTyID: {
1066 Result = OpaqueType::get();
1067 break;
1068 }
1069
1070 default:
Reid Spencer24399722004-07-09 22:21:33 +00001071 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001072 break;
1073 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001074 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001075 return Result;
1076}
1077
Reid Spencer5b472d92004-08-21 20:49:23 +00001078// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001079// types. We know that recursive types will only reference the current slab of
1080// values in the type plane, but they can forward reference types before they
1081// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1082// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1083// this ugly problem, we pessimistically insert an opaque type for each type we
1084// are about to read. This means that forward references will resolve to
1085// something and when we reread the type later, we can replace the opaque type
1086// with a new resolved concrete type.
1087//
Reid Spencer46b002c2004-07-11 17:28:43 +00001088void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001089 assert(Tab.size() == 0 && "should not have read type constants in before!");
1090
1091 // Insert a bunch of opaque types to be resolved later...
1092 Tab.reserve(NumEntries);
1093 for (unsigned i = 0; i != NumEntries; ++i)
1094 Tab.push_back(OpaqueType::get());
1095
Misha Brukman8a96c532005-04-21 21:44:41 +00001096 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001097 Handler->handleTypeList(NumEntries);
1098
Chris Lattnereebac5f2005-10-03 21:26:53 +00001099 // If we are about to resolve types, make sure the type cache is clear.
1100 if (NumEntries)
1101 ModuleTypeIDCache.clear();
1102
Reid Spencer060d25d2004-06-29 23:29:38 +00001103 // Loop through reading all of the types. Forward types will make use of the
1104 // opaque types just inserted.
1105 //
1106 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001107 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001108 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001109 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001110 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001111
Misha Brukman8a96c532005-04-21 21:44:41 +00001112 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 // the opaque type we previously inserted with the new concrete value. This
1114 // approach helps with forward references to types. The refinement from the
1115 // abstract (opaque) type to the new type causes all uses of the abstract
1116 // type to use the concrete type (NewTy). This will also cause the opaque
1117 // type to be deleted.
1118 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1119
1120 // This should have replaced the old opaque type with the new type in the
1121 // value table... or with a preexisting type that was already in the system.
1122 // Let's just make sure it did.
1123 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1124 }
1125}
1126
Reid Spencer04cde2c2004-07-04 11:33:49 +00001127/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001128Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001129 // We must check for a ConstantExpr before switching by type because
1130 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001131 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001132 // 0 if not expr; numArgs if is expr
1133 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001134
Reid Spencer060d25d2004-06-29 23:29:38 +00001135 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001136 // 'undef' is encoded with 'exprnumargs' == 1.
1137 if (isExprNumArgs == 1)
1138 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001139
Reid Spencerd798a512006-11-14 04:47:22 +00001140 // Inline asm is encoded with exprnumargs == ~0U.
1141 if (isExprNumArgs == ~0U) {
1142 std::string AsmStr = read_str();
1143 std::string ConstraintStr = read_str();
1144 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001145
Reid Spencerd798a512006-11-14 04:47:22 +00001146 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1147 const FunctionType *FTy =
1148 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1149
1150 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1151 error("Invalid constraints for inline asm");
1152 if (Flags & ~1U)
1153 error("Invalid flags for inline asm");
1154 bool HasSideEffects = Flags & 1;
1155 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001156 }
Reid Spencerd798a512006-11-14 04:47:22 +00001157
1158 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001159
Reid Spencer060d25d2004-06-29 23:29:38 +00001160 // FIXME: Encoding of constant exprs could be much more compact!
Chris Lattner670ccfe2007-02-07 05:15:28 +00001161 SmallVector<Constant*, 8> ArgVec;
Reid Spencer060d25d2004-06-29 23:29:38 +00001162 ArgVec.reserve(isExprNumArgs);
1163 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001164
Reid Spencer060d25d2004-06-29 23:29:38 +00001165 // Read the slot number and types of each of the arguments
1166 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1167 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001168 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001169
Reid Spencer060d25d2004-06-29 23:29:38 +00001170 // Get the arg value from its slot if it exists, otherwise a placeholder
1171 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1172 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001173
Reid Spencer060d25d2004-06-29 23:29:38 +00001174 // Construct a ConstantExpr of the appropriate kind
1175 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001176 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001177 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001178
Reid Spencera77fa7e2006-12-11 23:20:20 +00001179 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1180 getType(TypeID));
Chris Lattner63cf59e2007-02-07 05:08:39 +00001181 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1182 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001183 return Result;
1184 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
Chris Lattnere0135402007-01-31 04:43:46 +00001185 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], &ArgVec[1],
1186 ArgVec.size()-1);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001187 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1188 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001189 return Result;
1190 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001191 if (ArgVec.size() != 3)
1192 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001193 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001194 ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001195 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1196 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001197 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001198 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001199 if (ArgVec.size() != 2 ||
1200 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1201 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001202 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001203 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1204 ArgVec.size(), Result);
Robert Bocchinofee31b32006-01-10 19:04:39 +00001205 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001206 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001207 if (ArgVec.size() != 3 ||
1208 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1209 error("Invalid insertelement constand expr arguments");
1210
1211 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001212 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001213 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1214 ArgVec.size(), Result);
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001215 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001216 } else if (Opcode == Instruction::ShuffleVector) {
1217 if (ArgVec.size() != 3 ||
1218 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001219 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001220 Constant *Result =
1221 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001222 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1223 ArgVec.size(), Result);
Chris Lattner30b44b62006-04-08 01:17:59 +00001224 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001225 } else if (Opcode == Instruction::ICmp) {
1226 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001227 error("Invalid ICmp constant expr arguments.");
1228 unsigned predicate = read_vbr_uint();
1229 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001230 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1231 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001232 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001233 } else if (Opcode == Instruction::FCmp) {
1234 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001235 error("Invalid FCmp constant expr arguments.");
1236 unsigned predicate = read_vbr_uint();
1237 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001238 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1239 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001240 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001241 } else { // All other 2-operand expressions
1242 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001243 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1244 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001245 return Result;
1246 }
1247 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001248
Reid Spencer060d25d2004-06-29 23:29:38 +00001249 // Ok, not an ConstantExpr. We now know how to read the given type...
1250 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001251 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001252 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001253 case Type::IntegerTyID: {
1254 const IntegerType *IT = cast<IntegerType>(Ty);
1255 if (IT->getBitWidth() <= 32) {
1256 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001257 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1258 error("Integer value read is invalid for type.");
1259 Result = ConstantInt::get(IT, Val);
1260 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001261 } else if (IT->getBitWidth() <= 64) {
1262 uint64_t Val = read_vbr_uint64();
1263 if (!ConstantInt::isValueValidForType(Ty, Val))
1264 error("Invalid constant integer read.");
1265 Result = ConstantInt::get(IT, Val);
1266 if (Handler) Handler->handleConstantValue(Result);
1267 } else
1268 assert("Integer types > 64 bits not supported");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001269 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001270 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001271 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001272 float Val;
1273 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001274 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001275 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001276 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001277 }
1278
1279 case Type::DoubleTyID: {
1280 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001281 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001282 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001283 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001284 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001285 }
1286
Reid Spencer060d25d2004-06-29 23:29:38 +00001287 case Type::ArrayTyID: {
1288 const ArrayType *AT = cast<ArrayType>(Ty);
1289 unsigned NumElements = AT->getNumElements();
1290 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1291 std::vector<Constant*> Elements;
1292 Elements.reserve(NumElements);
1293 while (NumElements--) // Read all of the elements of the constant.
1294 Elements.push_back(getConstantValue(TypeSlot,
1295 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001296 Result = ConstantArray::get(AT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001297 if (Handler) Handler->handleConstantArray(AT, &Elements[0], Elements.size(),
1298 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001299 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001300 }
1301
1302 case Type::StructTyID: {
1303 const StructType *ST = cast<StructType>(Ty);
1304
1305 std::vector<Constant *> Elements;
1306 Elements.reserve(ST->getNumElements());
1307 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1308 Elements.push_back(getConstantValue(ST->getElementType(i),
1309 read_vbr_uint()));
1310
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001311 Result = ConstantStruct::get(ST, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001312 if (Handler) Handler->handleConstantStruct(ST, &Elements[0],Elements.size(),
1313 Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001314 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001315 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001316
Brian Gaeke715c90b2004-08-20 06:00:58 +00001317 case Type::PackedTyID: {
1318 const PackedType *PT = cast<PackedType>(Ty);
1319 unsigned NumElements = PT->getNumElements();
1320 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1321 std::vector<Constant*> Elements;
1322 Elements.reserve(NumElements);
1323 while (NumElements--) // Read all of the elements of the constant.
1324 Elements.push_back(getConstantValue(TypeSlot,
1325 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001326 Result = ConstantPacked::get(PT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001327 if (Handler) Handler->handleConstantPacked(PT, &Elements[0],Elements.size(),
1328 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001329 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001330 }
1331
Chris Lattner638c3812004-11-19 16:24:05 +00001332 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001333 const PointerType *PT = cast<PointerType>(Ty);
1334 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001335
Reid Spencer060d25d2004-06-29 23:29:38 +00001336 // Check to see if we have already read this global variable...
1337 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001338 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001339 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1340 if (!GV) error("GlobalValue not in ValueTable!");
1341 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1342 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001343 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001344 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001346 }
1347
1348 default:
Reid Spencer24399722004-07-09 22:21:33 +00001349 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001350 Ty->getDescription());
1351 break;
1352 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001353
1354 // Check that we didn't read a null constant if they are implicit for this
1355 // type plane. Do not do this check for constantexprs, as they may be folded
1356 // to a null value in a way that isn't predicted when a .bc file is initially
1357 // produced.
1358 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1359 !hasImplicitNull(TypeID) &&
1360 "Cannot read null values from bytecode!");
1361 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001362}
1363
Misha Brukman8a96c532005-04-21 21:44:41 +00001364/// Resolve references for constants. This function resolves the forward
1365/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001366/// replaceAllUsesWith method of Value class to substitute the placeholder
1367/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001368void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1369 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001370 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001371 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001372 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001373
Chris Lattner29b789b2003-11-19 17:27:18 +00001374 Value *PH = I->second; // Get the placeholder...
1375 PH->replaceAllUsesWith(NewV);
1376 delete PH; // Delete the old placeholder
1377 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001378}
1379
Reid Spencer04cde2c2004-07-04 11:33:49 +00001380/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001381void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1382 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001383 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001384 const Type *Ty = getType(Typ);
1385 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001386 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001387
Reid Spencer060d25d2004-06-29 23:29:38 +00001388 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001389 if (ATy->getElementType() != Type::Int8Ty &&
1390 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001391 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001392
Reid Spencer060d25d2004-06-29 23:29:38 +00001393 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001394 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001395 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001396
Reid Spencer060d25d2004-06-29 23:29:38 +00001397 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001398 const Type* ElemType = ATy->getElementType();
1399 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1400 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001401
Reid Spencer060d25d2004-06-29 23:29:38 +00001402 // Create the constant, inserting it as needed.
1403 Constant *C = ConstantArray::get(ATy, Elements);
1404 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001405 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001406 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001407 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001408}
1409
Reid Spencer04cde2c2004-07-04 11:33:49 +00001410/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001411void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001412 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001413 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001414 if (Handler) Handler->handleGlobalConstantsBegin();
1415
1416 /// In LLVM 1.3 Type does not derive from Value so the types
1417 /// do not occupy a plane. Consequently, we read the types
1418 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001419 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001420 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001421 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001422 }
1423
Reid Spencer46b002c2004-07-11 17:28:43 +00001424 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001425 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001426 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001427
Reid Spencerd798a512006-11-14 04:47:22 +00001428 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001429 /// Use of Type::VoidTyID is a misnomer. It actually means
1430 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001431 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1432 ParseStringConstants(NumEntries, Tab);
1433 } else {
1434 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001435 Value *V = ParseConstantPoolValue(Typ);
1436 assert(V && "ParseConstantPoolValue returned NULL!");
1437 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001438
Reid Spencer060d25d2004-06-29 23:29:38 +00001439 // If we are reading a function constant table, make sure that we adjust
1440 // the slot number to be the real global constant number.
1441 //
1442 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1443 ModuleValues[Typ])
1444 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001445 if (Constant *C = dyn_cast<Constant>(V))
1446 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001447 }
1448 }
1449 }
Chris Lattner02dce162004-12-04 05:28:27 +00001450
1451 // After we have finished parsing the constant pool, we had better not have
1452 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001453 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001454 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001455 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001456 error(utostr(ConstantFwdRefs.size()) +
1457 " unresolved constant reference exist. First one is '" +
1458 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001459 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001460 }
Chris Lattner02dce162004-12-04 05:28:27 +00001461
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001463 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001464}
Chris Lattner00950542001-06-06 20:29:01 +00001465
Reid Spencer04cde2c2004-07-04 11:33:49 +00001466/// Parse the contents of a function. Note that this function can be
1467/// called lazily by materializeFunction
1468/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001469void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001470
1471 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001472 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001473 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001474
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001475 unsigned rWord = read_vbr_uint();
1476 unsigned LinkageID = rWord & 65535;
1477 unsigned VisibilityID = rWord >> 16;
1478 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001479 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1480 case 1: Linkage = GlobalValue::WeakLinkage; break;
1481 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1482 case 3: Linkage = GlobalValue::InternalLinkage; break;
1483 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001484 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1485 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1486 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001487 default:
Reid Spencer24399722004-07-09 22:21:33 +00001488 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001489 Linkage = GlobalValue::InternalLinkage;
1490 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001491 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001492 switch (VisibilityID) {
1493 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1494 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1495 default:
1496 error("Unknown visibility type: " + utostr(VisibilityID));
1497 Visibility = GlobalValue::DefaultVisibility;
1498 break;
1499 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001500
Reid Spencer46b002c2004-07-11 17:28:43 +00001501 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001502 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001503 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001504
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001505 // Keep track of how many basic blocks we have read in...
1506 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001507 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001508
Reid Spencer060d25d2004-06-29 23:29:38 +00001509 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001510 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001511 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001512 BufPtr OldAt = At;
1513 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001514
1515 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001516 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001517 if (!InsertedArguments) {
1518 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001519 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001520 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001521 InsertedArguments = true;
1522 }
1523
Reid Spencer04cde2c2004-07-04 11:33:49 +00001524 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001525 break;
1526
Reid Spencerad89bd62004-07-25 18:07:36 +00001527 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001528 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001529 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001530 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001531 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001532 InsertedArguments = true;
1533 }
1534
Misha Brukman8a96c532005-04-21 21:44:41 +00001535 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001536 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001537 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001538 break;
1539 }
1540
Reid Spencer78d033e2007-01-06 07:24:44 +00001541 case BytecodeFormat::ValueSymbolTableBlockID:
1542 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1543 break;
1544
1545 case BytecodeFormat::TypeSymbolTableBlockID:
1546 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001547 break;
1548
1549 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001550 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001551 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001552 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001553 break;
1554 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001555 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001556 }
1557
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001558 // Make sure there were no references to non-existant basic blocks.
1559 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001560 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001561
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001562 ParsedBasicBlocks.clear();
1563
Chris Lattner97330cf2003-10-09 23:10:14 +00001564 // Resolve forward references. Replace any uses of a forward reference value
1565 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001566 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001567 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1568 I = ForwardReferences.begin();
1569 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001570 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001571 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001572 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001573 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001574 }
Chris Lattner00950542001-06-06 20:29:01 +00001575
Misha Brukman12c29d12003-09-22 23:38:23 +00001576 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001577 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001578 freeTable(FunctionValues);
1579
Reid Spencer04cde2c2004-07-04 11:33:49 +00001580 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001581}
1582
Reid Spencer04cde2c2004-07-04 11:33:49 +00001583/// This function parses LLVM functions lazily. It obtains the type of the
1584/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001585/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001586/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001587void BytecodeReader::ParseFunctionLazily() {
1588 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001589 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001590
Reid Spencer060d25d2004-06-29 23:29:38 +00001591 Function *Func = FunctionSignatureList.back();
1592 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001593
Reid Spencer060d25d2004-06-29 23:29:38 +00001594 // Save the information for future reading of the function
1595 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001596
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001597 // This function has a body but it's not loaded so it appears `External'.
1598 // Mark it as a `Ghost' instead to notify the users that it has a body.
1599 Func->setLinkage(GlobalValue::GhostLinkage);
1600
Reid Spencer060d25d2004-06-29 23:29:38 +00001601 // Pretend we've `parsed' this function
1602 At = BlockEnd;
1603}
Chris Lattner89e02532004-01-18 21:08:15 +00001604
Misha Brukman8a96c532005-04-21 21:44:41 +00001605/// The ParserFunction method lazily parses one function. Use this method to
1606/// casue the parser to parse a specific function in the module. Note that
1607/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001608/// ParseAllFunctionBodies.
1609/// @see ParseAllFunctionBodies
1610/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001611bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1612
Reid Spencer9b84ad12006-12-15 19:49:23 +00001613 if (setjmp(context)) {
1614 // Set caller's error message, if requested
1615 if (ErrMsg)
1616 *ErrMsg = ErrorMsg;
1617 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001618 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001619 }
Reid Spencer99655e12006-08-25 19:54:53 +00001620
Reid Spencer060d25d2004-06-29 23:29:38 +00001621 // Find {start, end} pointers and slot in the map. If not there, we're done.
1622 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001623
Reid Spencer060d25d2004-06-29 23:29:38 +00001624 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001625 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001626 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001627 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001628 }
1629
Reid Spencer060d25d2004-06-29 23:29:38 +00001630 BlockStart = At = Fi->second.Buf;
1631 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001632 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001633
1634 LazyFunctionLoadMap.erase(Fi);
1635
Reid Spencer46b002c2004-07-11 17:28:43 +00001636 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001637 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001638}
1639
Reid Spencer04cde2c2004-07-04 11:33:49 +00001640/// The ParseAllFunctionBodies method parses through all the previously
1641/// unparsed functions in the bytecode file. If you want to completely parse
1642/// a bytecode file, this method should be called after Parsebytecode because
1643/// Parsebytecode only records the locations in the bytecode file of where
1644/// the function definitions are located. This function uses that information
1645/// to materialize the functions.
1646/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001647bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001648 if (setjmp(context)) {
1649 // Set caller's error message, if requested
1650 if (ErrMsg)
1651 *ErrMsg = ErrorMsg;
1652 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001653 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001654 }
Reid Spencer99655e12006-08-25 19:54:53 +00001655
Reid Spencer060d25d2004-06-29 23:29:38 +00001656 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1657 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001658
Reid Spencer46b002c2004-07-11 17:28:43 +00001659 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001660 Function* Func = Fi->first;
1661 BlockStart = At = Fi->second.Buf;
1662 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001663 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001664 ++Fi;
1665 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001666 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001667 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001668}
Chris Lattner89e02532004-01-18 21:08:15 +00001669
Reid Spencer04cde2c2004-07-04 11:33:49 +00001670/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001671void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001672 // Read the number of types
1673 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001674 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001675}
1676
Reid Spencer04cde2c2004-07-04 11:33:49 +00001677/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001678void BytecodeReader::ParseModuleGlobalInfo() {
1679
Reid Spencer04cde2c2004-07-04 11:33:49 +00001680 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001681
Chris Lattner404cddf2005-11-12 01:33:40 +00001682 // SectionID - If a global has an explicit section specified, this map
1683 // remembers the ID until we can translate it into a string.
1684 std::map<GlobalValue*, unsigned> SectionID;
1685
Chris Lattner70cc3392001-09-10 07:58:01 +00001686 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001687 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001688 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001689 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1690 // Linkage, bit4+ = slot#
1691 unsigned SlotNo = VarType >> 5;
1692 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001693 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001694 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001695 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001696 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001697 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001698
1699 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1700 if (LinkageID == 3 && !hasInitializer) {
1701 unsigned ExtWord = read_vbr_uint();
1702 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001703 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1704 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001705 hasInitializer = ExtWord & 1;
1706 LinkageID = (ExtWord >> 1) & 7;
1707 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001708 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001709
1710 if (ExtWord & (1 << 9)) // Has a section ID.
1711 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001712 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001713
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001714 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001715 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001716 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1717 case 1: Linkage = GlobalValue::WeakLinkage; break;
1718 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1719 case 3: Linkage = GlobalValue::InternalLinkage; break;
1720 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001721 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1722 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1723 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001724 default:
Reid Spencer24399722004-07-09 22:21:33 +00001725 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001726 Linkage = GlobalValue::InternalLinkage;
1727 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001728 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001729 GlobalValue::VisibilityTypes Visibility;
1730 switch (VisibilityID) {
1731 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1732 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1733 default:
1734 error("Unknown visibility type: " + utostr(VisibilityID));
1735 Visibility = GlobalValue::DefaultVisibility;
1736 break;
1737 }
1738
Chris Lattnere3869c82003-04-16 21:16:05 +00001739 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001740 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001741 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001742
Chris Lattnere73bd452005-11-06 07:43:39 +00001743 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001744 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001745
Chris Lattner52e20b02003-03-19 20:54:26 +00001746 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001747
Chris Lattner70cc3392001-09-10 07:58:01 +00001748 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001749 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001750 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001751 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001752 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001753 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001754
Chris Lattner404cddf2005-11-12 01:33:40 +00001755 if (GlobalSectionID != 0)
1756 SectionID[GV] = GlobalSectionID;
1757
Reid Spencer060d25d2004-06-29 23:29:38 +00001758 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001759 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001760 initSlot = read_vbr_uint();
1761 GlobalInits.push_back(std::make_pair(GV, initSlot));
1762 }
1763
1764 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001765 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001766 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1767 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001768
1769 // Get next item
1770 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001771 }
1772
Chris Lattner52e20b02003-03-19 20:54:26 +00001773 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001774 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001775
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001776 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001777 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1778 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001779 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001780 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001781 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001782 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001783 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001784
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001785 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001786 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001787 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001788
Chris Lattner18549c22004-11-15 21:43:03 +00001789 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001790 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001791 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001792
Chris Lattnere73bd452005-11-06 07:43:39 +00001793 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001794
1795 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001796 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001797
Chris Lattner97fbc502004-11-15 22:38:52 +00001798 // Save this for later so we know type of lazily instantiated functions.
1799 // Note that known-external functions do not have FunctionInfo blocks, so we
1800 // do not add them to the FunctionSignatureList.
1801 if ((Flags & (1 << 4)) == 0)
1802 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001803
Chris Lattnere73bd452005-11-06 07:43:39 +00001804 // Get the calling convention from the low bits.
1805 unsigned CC = Flags & 15;
1806 unsigned Alignment = 0;
1807 if (FnSignature & (1 << 31)) { // Has extension word?
1808 unsigned ExtWord = read_vbr_uint();
1809 Alignment = (1 << (ExtWord & 31)) >> 1;
1810 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001811
1812 if (ExtWord & (1 << 10)) // Has a section ID.
1813 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001814
1815 // Parse external declaration linkage
1816 switch ((ExtWord >> 11) & 3) {
1817 case 0: break;
1818 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1819 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1820 default: assert(0 && "Unsupported external linkage");
1821 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001822 }
1823
Chris Lattner54b369e2005-11-06 07:46:13 +00001824 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001825 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001826
Reid Spencer04cde2c2004-07-04 11:33:49 +00001827 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001828
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001829 // Get the next function signature.
1830 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001831 }
1832
Misha Brukman8a96c532005-04-21 21:44:41 +00001833 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001834 // remove elements efficiently from the back of the vector.
1835 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001836
Chris Lattner404cddf2005-11-12 01:33:40 +00001837 /// SectionNames - This contains the list of section names encoded in the
1838 /// moduleinfoblock. Functions and globals with an explicit section index
1839 /// into this to get their section name.
1840 std::vector<std::string> SectionNames;
1841
Reid Spencerd798a512006-11-14 04:47:22 +00001842 // Read in the dependent library information.
1843 unsigned num_dep_libs = read_vbr_uint();
1844 std::string dep_lib;
1845 while (num_dep_libs--) {
1846 dep_lib = read_str();
1847 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001848 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001849 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001850 }
1851
Reid Spencerd798a512006-11-14 04:47:22 +00001852 // Read target triple and place into the module.
1853 std::string triple = read_str();
1854 TheModule->setTargetTriple(triple);
1855 if (Handler)
1856 Handler->handleTargetTriple(triple);
1857
Reid Spenceraacc35a2007-01-26 08:10:24 +00001858 // Read the data layout string and place into the module.
1859 std::string datalayout = read_str();
1860 TheModule->setDataLayout(datalayout);
1861 // FIXME: Implement
1862 // if (Handler)
1863 // Handler->handleDataLayout(datalayout);
1864
Reid Spencerd798a512006-11-14 04:47:22 +00001865 if (At != BlockEnd) {
1866 // If the file has section info in it, read the section names now.
1867 unsigned NumSections = read_vbr_uint();
1868 while (NumSections--)
1869 SectionNames.push_back(read_str());
1870 }
1871
1872 // If the file has module-level inline asm, read it now.
1873 if (At != BlockEnd)
1874 TheModule->setModuleInlineAsm(read_str());
1875
Chris Lattner404cddf2005-11-12 01:33:40 +00001876 // If any globals are in specified sections, assign them now.
1877 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1878 SectionID.end(); I != E; ++I)
1879 if (I->second) {
1880 if (I->second > SectionID.size())
1881 error("SectionID out of range for global!");
1882 I->first->setSection(SectionNames[I->second-1]);
1883 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001884
Chris Lattner00950542001-06-06 20:29:01 +00001885 // This is for future proofing... in the future extra fields may be added that
1886 // we don't understand, so we transparently ignore them.
1887 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001888 At = BlockEnd;
1889
Reid Spencer04cde2c2004-07-04 11:33:49 +00001890 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001891}
1892
Reid Spencer04cde2c2004-07-04 11:33:49 +00001893/// Parse the version information and decode it by setting flags on the
1894/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001895void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001896 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001897
Reid Spencer3795ad12006-12-03 05:47:10 +00001898 // We don't provide backwards compatibility in the Reader any more. To
1899 // upgrade, the user should use llvm-upgrade.
1900 if (RevisionNum < 7)
1901 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001902
Reid Spenceraacc35a2007-01-26 08:10:24 +00001903 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001904}
1905
Reid Spencer04cde2c2004-07-04 11:33:49 +00001906/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001907void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001908 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001909
Reid Spencer060d25d2004-06-29 23:29:38 +00001910 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001911
1912 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001913 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001914
Reid Spencer060d25d2004-06-29 23:29:38 +00001915 bool SeenModuleGlobalInfo = false;
1916 bool SeenGlobalTypePlane = false;
1917 BufPtr MyEnd = BlockEnd;
1918 while (At < MyEnd) {
1919 BufPtr OldAt = At;
1920 read_block(Type, Size);
1921
Chris Lattner00950542001-06-06 20:29:01 +00001922 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001923
Reid Spencerad89bd62004-07-25 18:07:36 +00001924 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001925 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001926 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001927
Reid Spencer5b472d92004-08-21 20:49:23 +00001928 if (Size > 0)
1929 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001930 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001931 break;
1932
Misha Brukman8a96c532005-04-21 21:44:41 +00001933 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001934 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001935 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001936 ParseModuleGlobalInfo();
1937 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001938 break;
1939
Reid Spencerad89bd62004-07-25 18:07:36 +00001940 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001941 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001942 break;
1943
Reid Spencerad89bd62004-07-25 18:07:36 +00001944 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001945 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001946 break;
Chris Lattner00950542001-06-06 20:29:01 +00001947
Reid Spencer78d033e2007-01-06 07:24:44 +00001948 case BytecodeFormat::ValueSymbolTableBlockID:
1949 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1950 break;
1951
1952 case BytecodeFormat::TypeSymbolTableBlockID:
1953 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001954 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001955
Chris Lattner00950542001-06-06 20:29:01 +00001956 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001957 At += Size;
1958 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001959 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001960 }
Chris Lattner00950542001-06-06 20:29:01 +00001961 break;
1962 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001963 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001964 }
1965
Chris Lattner52e20b02003-03-19 20:54:26 +00001966 // After the module constant pool has been read, we can safely initialize
1967 // global variables...
1968 while (!GlobalInits.empty()) {
1969 GlobalVariable *GV = GlobalInits.back().first;
1970 unsigned Slot = GlobalInits.back().second;
1971 GlobalInits.pop_back();
1972
1973 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001974 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001975
1976 const llvm::PointerType* GVType = GV->getType();
1977 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001978 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001979 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001980 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001981 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001982 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001983 } else
Reid Spencer24399722004-07-09 22:21:33 +00001984 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001985 }
1986
Chris Lattneraba5ff52005-05-05 20:57:00 +00001987 if (!ConstantFwdRefs.empty())
1988 error("Use of undefined constants in a module");
1989
Reid Spencer060d25d2004-06-29 23:29:38 +00001990 /// Make sure we pulled them all out. If we didn't then there's a declaration
1991 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001992 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001993 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001994}
1995
Reid Spencer04cde2c2004-07-04 11:33:49 +00001996/// This function completely parses a bytecode buffer given by the \p Buf
1997/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00001998bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00001999 const std::string &ModuleID,
Chris Lattnerf2e292c2007-02-07 21:41:02 +00002000 BCDecompressor_t *Decompressor,
Reid Spencer233fe722006-08-22 16:09:19 +00002001 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002002
Reid Spencer233fe722006-08-22 16:09:19 +00002003 /// We handle errors by
2004 if (setjmp(context)) {
2005 // Cleanup after error
2006 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002007 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002008 delete TheModule;
2009 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002010 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002011 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002012 decompressedBlock = 0;
2013 }
Reid Spencer233fe722006-08-22 16:09:19 +00002014 // Set caller's error message, if requested
2015 if (ErrMsg)
2016 *ErrMsg = ErrorMsg;
2017 // Indicate an error occurred
2018 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002019 }
Reid Spencer233fe722006-08-22 16:09:19 +00002020
2021 RevisionNum = 0;
2022 At = MemStart = BlockStart = Buf;
2023 MemEnd = BlockEnd = Buf + Length;
2024
2025 // Create the module
2026 TheModule = new Module(ModuleID);
2027
2028 if (Handler) Handler->handleStart(TheModule, Length);
2029
2030 // Read the four bytes of the signature.
2031 unsigned Sig = read_uint();
2032
2033 // If this is a compressed file
2034 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Chris Lattnerf2e292c2007-02-07 21:41:02 +00002035 if (!Decompressor) {
2036 error("Compressed bytecode found, but not decompressor available");
2037 }
Reid Spencer233fe722006-08-22 16:09:19 +00002038
2039 // Invoke the decompression of the bytecode. Note that we have to skip the
2040 // file's magic number which is not part of the compressed block. Hence,
2041 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2042 // member for retention until BytecodeReader is destructed.
Chris Lattner0d3382a2007-02-07 19:49:01 +00002043 unsigned decompressedLength =
2044 Decompressor((char*)Buf+4,Length-4,decompressedBlock, 0);
Reid Spencer233fe722006-08-22 16:09:19 +00002045
2046 // We must adjust the buffer pointers used by the bytecode reader to point
2047 // into the new decompressed block. After decompression, the
2048 // decompressedBlock will point to a contiguous memory area that has
2049 // the decompressed data.
2050 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2051 MemEnd = BlockEnd = Buf + decompressedLength;
2052
2053 // else if this isn't a regular (uncompressed) bytecode file, then its
2054 // and error, generate that now.
2055 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2056 error("Invalid bytecode signature: " + utohexstr(Sig));
2057 }
2058
2059 // Tell the handler we're starting a module
2060 if (Handler) Handler->handleModuleBegin(ModuleID);
2061
2062 // Get the module block and size and verify. This is handled specially
2063 // because the module block/size is always written in long format. Other
2064 // blocks are written in short format so the read_block method is used.
2065 unsigned Type, Size;
2066 Type = read_uint();
2067 Size = read_uint();
2068 if (Type != BytecodeFormat::ModuleBlockID) {
2069 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2070 + utostr(Size));
2071 }
2072
2073 // It looks like the darwin ranlib program is broken, and adds trailing
2074 // garbage to the end of some bytecode files. This hack allows the bc
2075 // reader to ignore trailing garbage on bytecode files.
2076 if (At + Size < MemEnd)
2077 MemEnd = BlockEnd = At+Size;
2078
2079 if (At + Size != MemEnd)
2080 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2081 + ", Size:" + utostr(Size));
2082
2083 // Parse the module contents
2084 this->ParseModule();
2085
2086 // Check for missing functions
2087 if (hasFunctions())
2088 error("Function expected, but bytecode stream ended!");
2089
Reid Spencer233fe722006-08-22 16:09:19 +00002090 // Tell the handler we're done with the module
2091 if (Handler)
2092 Handler->handleModuleEnd(ModuleID);
2093
2094 // Tell the handler we're finished the parse
2095 if (Handler) Handler->handleFinish();
2096
2097 return false;
2098
Chris Lattner00950542001-06-06 20:29:01 +00002099}
Reid Spencer060d25d2004-06-29 23:29:38 +00002100
2101//===----------------------------------------------------------------------===//
2102//=== Default Implementations of Handler Methods
2103//===----------------------------------------------------------------------===//
2104
2105BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002106