blob: d441e7504b7a2f928e60a70d6c1d8ab4047db345 [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"
Reid Spencer0b118202006-01-16 21:12:35 +000020#include "llvm/Assembly/AutoUpgrade.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000021#include "llvm/Bytecode/BytecodeHandler.h"
22#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000023#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000024#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000025#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000026#include "llvm/Instructions.h"
27#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
48 Op(UndefValue::get(Type::IntTy), this) {
49 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
54inline void BytecodeReader::error(std::string err) {
55 err += " (Vers=" ;
56 err += itostr(RevisionNum) ;
57 err += ", Pos=" ;
58 err += itostr(At-MemStart);
59 err += ")";
60 throw err;
61}
62
Reid Spencer060d25d2004-06-29 23:29:38 +000063//===----------------------------------------------------------------------===//
64// Bytecode Reading Methods
65//===----------------------------------------------------------------------===//
66
Reid Spencer04cde2c2004-07-04 11:33:49 +000067/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000068inline bool BytecodeReader::moreInBlock() {
69 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000070}
71
Reid Spencer04cde2c2004-07-04 11:33:49 +000072/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000073inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000074 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000075 error(std::string("Attempt to read past the end of ") + block_name +
76 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000077}
Chris Lattner36392bc2003-10-08 21:18:57 +000078
Reid Spencer04cde2c2004-07-04 11:33:49 +000079/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000080inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000081 if (hasAlignment) {
82 BufPtr Save = At;
Jeff Cohen05ebc8d2006-01-25 17:18:50 +000083 At = (const unsigned char *)((intptr_t)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000084 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000085 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000086 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000087 error("Ran out of data while aligning!");
88 }
Reid Spencer060d25d2004-06-29 23:29:38 +000089}
90
Reid Spencer04cde2c2004-07-04 11:33:49 +000091/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000092inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000093 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000094 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000095 At += 4;
96 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
97}
98
Reid Spencer04cde2c2004-07-04 11:33:49 +000099/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +0000100inline unsigned BytecodeReader::read_vbr_uint() {
101 unsigned Shift = 0;
102 unsigned Result = 0;
103 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000104
Reid Spencer060d25d2004-06-29 23:29:38 +0000105 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000106 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000107 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000108 Result |= (unsigned)((*At++) & 0x7F) << Shift;
109 Shift += 7;
110 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000111 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000112 return Result;
113}
114
Reid Spencer04cde2c2004-07-04 11:33:49 +0000115/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000116inline uint64_t BytecodeReader::read_vbr_uint64() {
117 unsigned Shift = 0;
118 uint64_t Result = 0;
119 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000120
Reid Spencer060d25d2004-06-29 23:29:38 +0000121 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000122 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000123 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000124 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
125 Shift += 7;
126 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000127 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000128 return Result;
129}
130
Reid Spencer04cde2c2004-07-04 11:33:49 +0000131/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000132inline int64_t BytecodeReader::read_vbr_int64() {
133 uint64_t R = read_vbr_uint64();
134 if (R & 1) {
135 if (R != 1)
136 return -(int64_t)(R >> 1);
137 else // There is no such thing as -0 with integers. "-0" really means
138 // 0x8000000000000000.
139 return 1LL << 63;
140 } else
141 return (int64_t)(R >> 1);
142}
143
Reid Spencer04cde2c2004-07-04 11:33:49 +0000144/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000145inline std::string BytecodeReader::read_str() {
146 unsigned Size = read_vbr_uint();
147 const unsigned char *OldAt = At;
148 At += Size;
149 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000150 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000151 return std::string((char*)OldAt, Size);
152}
153
Reid Spencer04cde2c2004-07-04 11:33:49 +0000154/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000155inline void BytecodeReader::read_data(void *Ptr, void *End) {
156 unsigned char *Start = (unsigned char *)Ptr;
157 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000158 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000159 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000160 std::copy(At, At+Amount, Start);
161 At += Amount;
162}
163
Reid Spencer46b002c2004-07-11 17:28:43 +0000164/// Read a float value in little-endian order
165inline void BytecodeReader::read_float(float& FloatVal) {
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 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000169 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000170}
171
172/// Read a double value in little-endian order
173inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000174 /// FIXME: This isn't optimal, it has size problems on some platforms
175 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000176 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
177 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
178 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
179 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000180 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000181}
182
Reid Spencer04cde2c2004-07-04 11:33:49 +0000183/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000184inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000185 if ( hasLongBlockHeaders ) {
186 Type = read_uint();
187 Size = read_uint();
188 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000189 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000190 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000191 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000192 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000193 Type = BytecodeFormat::ModuleBlockID; break;
194 case BytecodeFormat::Function:
195 Type = BytecodeFormat::FunctionBlockID; break;
196 case BytecodeFormat::ConstantPool:
197 Type = BytecodeFormat::ConstantPoolBlockID; break;
198 case BytecodeFormat::SymbolTable:
199 Type = BytecodeFormat::SymbolTableBlockID; break;
200 case BytecodeFormat::ModuleGlobalInfo:
201 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
202 case BytecodeFormat::GlobalTypePlane:
203 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
204 case BytecodeFormat::InstructionList:
205 Type = BytecodeFormat::InstructionListBlockID; break;
206 case BytecodeFormat::CompactionTable:
207 Type = BytecodeFormat::CompactionTableBlockID; break;
208 case BytecodeFormat::BasicBlock:
209 /// This block type isn't used after version 1.1. However, we have to
210 /// still allow the value in case this is an old bc format file.
211 /// We just let its value creep thru.
212 break;
213 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000214 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000215 break;
216 }
217 } else {
218 Size = read_uint();
219 Type = Size & 0x1F; // mask low order five bits
220 Size >>= 5; // get rid of five low order bits, leaving high 27
221 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000222 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000223 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000224 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000225 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000226 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000227}
228
229
230/// In LLVM 1.2 and before, Types were derived from Value and so they were
231/// written as part of the type planes along with any other Value. In LLVM
232/// 1.3 this changed so that Type does not derive from Value. Consequently,
233/// the BytecodeReader's containers for Values can't contain Types because
234/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000235/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
236/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000237/// the types are always read/written first and then the Values. Furthermore
238/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
239/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
240/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
241/// For LLVM 1.2 and before, this function will decrement the type id by
242/// one to account for the missing Type::TypeTyID enumerator if the value is
243/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
244/// function returns true, otherwise false. This helps detect situations
245/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000246/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000247inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
248 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
249 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000250 TypeId = Type::VoidTyID; // sanitize it
251 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000252 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000253 --TypeId; // shift all planes down because type type plane is missing
254 }
255 return false;
256}
257
258/// Reads a vbr uint to read in a type id and does the necessary
259/// conversion on it by calling sanitizeTypeId.
260/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
261/// @see sanitizeTypeId
262inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
263 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000264 if ( !has32BitTypes )
265 if ( TypeId == 0x00FFFFFF )
266 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000267 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000268}
269
270//===----------------------------------------------------------------------===//
271// IR Lookup Methods
272//===----------------------------------------------------------------------===//
273
Reid Spencer04cde2c2004-07-04 11:33:49 +0000274/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000275inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000276 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000277 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000278 return TyID >= Type::FirstDerivedTyID;
279}
280
Reid Spencer04cde2c2004-07-04 11:33:49 +0000281/// Obtain a type given a typeid and account for things like compaction tables,
282/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000283const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000284 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000285 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000286 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000287
288 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000289 ID -= Type::FirstDerivedTyID;
290
Reid Spencer060d25d2004-06-29 23:29:38 +0000291 if (!CompactionTypes.empty()) {
292 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000293 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000294 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000295 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000296
297 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000298 if (ID < ModuleTypes.size())
299 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000300
Reid Spencer46b002c2004-07-11 17:28:43 +0000301 // Nope, is it a function-level type?
302 ID -= ModuleTypes.size();
303 if (ID < FunctionTypes.size())
304 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000305
Reid Spencer46b002c2004-07-11 17:28:43 +0000306 error("Illegal type reference!");
307 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000308}
309
Reid Spencer04cde2c2004-07-04 11:33:49 +0000310/// Get a sanitized type id. This just makes sure that the \p ID
311/// is both sanitized and not the "type type" of pre-1.3 bytecode.
312/// @see sanitizeTypeId
313inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000314 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000315 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000316 return getType(ID);
317}
318
319/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000320/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000321/// then calls getType to return the type value.
322inline const Type* BytecodeReader::readSanitizedType() {
323 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000324 if (read_typeid(ID))
325 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000326 return getType(ID);
327}
328
329/// Get the slot number associated with a type accounting for primitive
330/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000331unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
332 if (Ty->isPrimitiveType())
333 return Ty->getTypeID();
334
335 // Scan the compaction table for the type if needed.
336 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000337 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
338 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000339 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000340
Chris Lattner45b5dd22004-08-03 23:41:28 +0000341 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000342 }
343
344 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000345 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
346 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000347
348 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000349 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000350 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000351
Chris Lattnereebac5f2005-10-03 21:26:53 +0000352 // If we don't have our cache yet, build it now.
353 if (ModuleTypeIDCache.empty()) {
354 unsigned N = 0;
355 ModuleTypeIDCache.reserve(ModuleTypes.size());
356 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
357 I != E; ++I, ++N)
358 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
359
360 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
361 }
362
363 // Binary search the cache for the entry.
364 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
365 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
366 std::make_pair(Ty, 0U));
367 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000368 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000369
370 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000371}
372
Reid Spencer04cde2c2004-07-04 11:33:49 +0000373/// This is just like getType, but when a compaction table is in use, it is
374/// ignored. It also ignores function level types.
375/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000376const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
377 if (Slot < Type::FirstDerivedTyID) {
378 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000379 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000380 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000381 return Ty;
382 }
383 Slot -= Type::FirstDerivedTyID;
384 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000385 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000386 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000387}
388
Reid Spencer04cde2c2004-07-04 11:33:49 +0000389/// This is just like getTypeSlot, but when a compaction table is in use, it
390/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000391unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
392 if (Ty->isPrimitiveType())
393 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000394
395 // If we don't have our cache yet, build it now.
396 if (ModuleTypeIDCache.empty()) {
397 unsigned N = 0;
398 ModuleTypeIDCache.reserve(ModuleTypes.size());
399 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
400 I != E; ++I, ++N)
401 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
402
403 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
404 }
405
406 // Binary search the cache for the entry.
407 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
408 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
409 std::make_pair(Ty, 0U));
410 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000411 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000412
413 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000414}
415
Misha Brukman8a96c532005-04-21 21:44:41 +0000416/// Retrieve a value of a given type and slot number, possibly creating
417/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000418Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000419 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000420 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000421
Chris Lattner89e02532004-01-18 21:08:15 +0000422 // If there is a compaction table active, it defines the low-level numbers.
423 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000424 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
425 if (Num < CompactionValues[type].size())
426 return CompactionValues[type][Num];
427 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000428 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000429 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000430 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000431
Chris Lattner45b5dd22004-08-03 23:41:28 +0000432 // If the type plane was compactified, figure out the global type ID by
433 // adding the derived type ids and the distance.
434 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
435 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000436
Reid Spencer060d25d2004-06-29 23:29:38 +0000437 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000438 const Type *Ty = getType(type);
439 if (!isa<OpaqueType>(Ty)) {
440 if (Num == 0)
441 return Constant::getNullValue(Ty);
442 --Num;
443 }
Chris Lattner89e02532004-01-18 21:08:15 +0000444 }
445
Chris Lattner52f86d62004-01-20 00:54:06 +0000446 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
447 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000448 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000449 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000450 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000451 }
452
Misha Brukman8a96c532005-04-21 21:44:41 +0000453 if (FunctionValues.size() > type &&
454 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000455 Num < FunctionValues[type]->size())
456 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000457
Chris Lattner74734132002-08-17 22:01:27 +0000458 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000459
Reid Spencer551ccae2004-09-01 22:55:40 +0000460 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000461 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000462 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000463 if (I != ForwardReferences.end() && I->first == KeyValue)
464 return I->second; // We have already created this placeholder
465
Reid Spencer551ccae2004-09-01 22:55:40 +0000466 // If the type exists (it should)
467 if (const Type* Ty = getType(type)) {
468 // Create the place holder
469 Value *Val = new Argument(Ty);
470 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
471 return Val;
472 }
473 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000474}
475
Misha Brukman8a96c532005-04-21 21:44:41 +0000476/// This is just like getValue, but when a compaction table is in use, it
477/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000478/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000479Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
480 if (SlotNo == 0)
481 return Constant::getNullValue(getType(TyID));
482
483 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
484 TyID -= Type::FirstDerivedTyID;
485 if (TyID >= CompactionTypes.size())
486 error("Type ID out of range for compaction table!");
487 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000488 }
489
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000490 --SlotNo;
491
Reid Spencer060d25d2004-06-29 23:29:38 +0000492 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
493 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000494 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
495 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000496 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000497 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000498 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000499 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000500 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000501 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000502 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
503 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000504 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000505 }
506 return ModuleValues[TyID]->getOperand(SlotNo);
507}
508
Reid Spencer04cde2c2004-07-04 11:33:49 +0000509/// Just like getValue, except that it returns a null pointer
510/// only on error. It always returns a constant (meaning that if the value is
511/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000512/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000513/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000514Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
515 if (Value *V = getValue(TypeSlot, Slot, false))
516 if (Constant *C = dyn_cast<Constant>(V))
517 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000518 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000519 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000520 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000521
Chris Lattner389bd042004-12-09 06:19:44 +0000522 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000523 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
524
525 if (I != ConstantFwdRefs.end() && I->first == Key) {
526 return I->second;
527 } else {
528 // Create a placeholder for the constant reference and
529 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000530 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000531
Reid Spencer060d25d2004-06-29 23:29:38 +0000532 // Keep track of the fact that we have a forward ref to recycle it
533 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
534 return C;
535 }
536}
537
538//===----------------------------------------------------------------------===//
539// IR Construction Methods
540//===----------------------------------------------------------------------===//
541
Reid Spencer04cde2c2004-07-04 11:33:49 +0000542/// As values are created, they are inserted into the appropriate place
543/// with this method. The ValueTable argument must be one of ModuleValues
544/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000545unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000546 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000547 if (ValueTab.size() <= type)
548 ValueTab.resize(type+1);
549
550 if (!ValueTab[type]) ValueTab[type] = new ValueList();
551
552 ValueTab[type]->push_back(Val);
553
Chris Lattneraba5ff52005-05-05 20:57:00 +0000554 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000555 return ValueTab[type]->size()-1 + HasOffset;
556}
557
Reid Spencer04cde2c2004-07-04 11:33:49 +0000558/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000559void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000560 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000561 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000562 for (FunctionType::param_iterator It = FT->param_begin();
563 It != FT->param_end(); ++It, ++AI)
564 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
565}
566
567//===----------------------------------------------------------------------===//
568// Bytecode Parsing Methods
569//===----------------------------------------------------------------------===//
570
Reid Spencer04cde2c2004-07-04 11:33:49 +0000571/// This method parses a single instruction. The instruction is
572/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000573/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000574void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000575 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000576 BufPtr SaveAt = At;
577
578 // Clear instruction data
579 Oprnds.clear();
580 unsigned iType = 0;
581 unsigned Opcode = 0;
582 unsigned Op = read_uint();
583
584 // bits Instruction format: Common to all formats
585 // --------------------------
586 // 01-00: Opcode type, fixed to 1.
587 // 07-02: Opcode
588 Opcode = (Op >> 2) & 63;
589 Oprnds.resize((Op >> 0) & 03);
590
591 // Extract the operands
592 switch (Oprnds.size()) {
593 case 1:
594 // bits Instruction format:
595 // --------------------------
596 // 19-08: Resulting type plane
597 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
598 //
599 iType = (Op >> 8) & 4095;
600 Oprnds[0] = (Op >> 20) & 4095;
601 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
602 Oprnds.resize(0);
603 break;
604 case 2:
605 // bits Instruction format:
606 // --------------------------
607 // 15-08: Resulting type plane
608 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000609 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000610 //
611 iType = (Op >> 8) & 255;
612 Oprnds[0] = (Op >> 16) & 255;
613 Oprnds[1] = (Op >> 24) & 255;
614 break;
615 case 3:
616 // bits Instruction format:
617 // --------------------------
618 // 13-08: Resulting type plane
619 // 19-14: Operand #1
620 // 25-20: Operand #2
621 // 31-26: Operand #3
622 //
623 iType = (Op >> 8) & 63;
624 Oprnds[0] = (Op >> 14) & 63;
625 Oprnds[1] = (Op >> 20) & 63;
626 Oprnds[2] = (Op >> 26) & 63;
627 break;
628 case 0:
629 At -= 4; // Hrm, try this again...
630 Opcode = read_vbr_uint();
631 Opcode >>= 2;
632 iType = read_vbr_uint();
633
634 unsigned NumOprnds = read_vbr_uint();
635 Oprnds.resize(NumOprnds);
636
637 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000638 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000639
640 for (unsigned i = 0; i != NumOprnds; ++i)
641 Oprnds[i] = read_vbr_uint();
642 align32();
643 break;
644 }
645
Reid Spencer04cde2c2004-07-04 11:33:49 +0000646 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000647
Reid Spencer46b002c2004-07-11 17:28:43 +0000648 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000649 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000650
651 // Declare the resulting instruction we'll build.
652 Instruction *Result = 0;
653
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000654 // If this is a bytecode format that did not include the unreachable
655 // instruction, bump up all opcodes numbers to make space.
656 if (hasNoUnreachableInst) {
657 if (Opcode >= Instruction::Unreachable &&
658 Opcode < 62) {
659 ++Opcode;
660 }
661 }
662
Reid Spencer060d25d2004-06-29 23:29:38 +0000663 // Handle binary operators
664 if (Opcode >= Instruction::BinaryOpsBegin &&
665 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
666 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
667 getValue(iType, Oprnds[0]),
668 getValue(iType, Oprnds[1]));
669
Reid Spencere1e96c02006-01-19 07:02:16 +0000670 bool isCall = false;
Reid Spencer060d25d2004-06-29 23:29:38 +0000671 switch (Opcode) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000672 default:
673 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000674 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000675 break;
676 case Instruction::VAArg:
Misha Brukman8a96c532005-04-21 21:44:41 +0000677 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000678 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000679 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000680 case 32: { //VANext_old
681 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000682 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
683 (Type *)0);
Andrew Lenharth558bc882005-06-18 18:34:52 +0000684
685 //b = vanext a, t ->
686 //foo = alloca 1 of t
687 //bar = vacopy a
688 //store bar -> foo
689 //tmp = vaarg foo, t
690 //b = load foo
691 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
692 BB->getInstList().push_back(foo);
693 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
694 BB->getInstList().push_back(bar);
695 BB->getInstList().push_back(new StoreInst(bar, foo));
696 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
697 BB->getInstList().push_back(tmp);
698 Result = new LoadInst(foo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000699 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000700 }
701 case 33: { //VAArg_old
702 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000703 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
704 (Type *)0);
Andrew Lenharth558bc882005-06-18 18:34:52 +0000705
Jeff Cohen00b168892005-07-27 06:12:32 +0000706 //b = vaarg a, t ->
Andrew Lenharth558bc882005-06-18 18:34:52 +0000707 //foo = alloca 1 of t
Jeff Cohen00b168892005-07-27 06:12:32 +0000708 //bar = vacopy a
Andrew Lenharth558bc882005-06-18 18:34:52 +0000709 //store bar -> foo
710 //b = vaarg foo, t
711 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
712 BB->getInstList().push_back(foo);
713 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
714 BB->getInstList().push_back(bar);
715 BB->getInstList().push_back(new StoreInst(bar, foo));
716 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
717 break;
718 }
Robert Bocchinofee31b32006-01-10 19:04:39 +0000719 case Instruction::ExtractElement: {
720 if (Oprnds.size() != 2)
721 throw std::string("Invalid extractelement instruction!");
Chris Lattner59fecec2006-04-08 04:09:19 +0000722 Value *V1 = getValue(iType, Oprnds[0]);
723 Value *V2 = getValue(Type::UIntTyID, Oprnds[1]);
724
725 if (!ExtractElementInst::isValidOperands(V1, V2))
726 throw std::string("Invalid extractelement instruction!");
727
728 Result = new ExtractElementInst(V1, V2);
Robert Bocchinofee31b32006-01-10 19:04:39 +0000729 break;
730 }
Robert Bocchinob1f240b2006-01-17 20:06:35 +0000731 case Instruction::InsertElement: {
732 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
733 if (!PackedTy || Oprnds.size() != 3)
734 throw std::string("Invalid insertelement instruction!");
Chris Lattner59fecec2006-04-08 04:09:19 +0000735
736 Value *V1 = getValue(iType, Oprnds[0]);
737 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()), Oprnds[1]);
738 Value *V3 = getValue(Type::UIntTyID, Oprnds[2]);
739
740 if (!InsertElementInst::isValidOperands(V1, V2, V3))
741 throw std::string("Invalid insertelement instruction!");
742 Result = new InsertElementInst(V1, V2, V3);
Robert Bocchinob1f240b2006-01-17 20:06:35 +0000743 break;
744 }
Chris Lattner30b44b62006-04-08 01:17:59 +0000745 case Instruction::ShuffleVector: {
746 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
747 if (!PackedTy || Oprnds.size() != 3)
748 throw std::string("Invalid shufflevector instruction!");
749 Value *V1 = getValue(iType, Oprnds[0]);
750 Value *V2 = getValue(iType, Oprnds[1]);
751 const PackedType *EltTy =
752 PackedType::get(Type::UIntTy, PackedTy->getNumElements());
753 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
754 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
755 throw std::string("Invalid shufflevector instruction!");
756 Result = new ShuffleVectorInst(V1, V2, V3);
757 break;
758 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000759 case Instruction::Cast:
Misha Brukman8a96c532005-04-21 21:44:41 +0000760 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000761 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000762 break;
763 case Instruction::Select:
764 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
765 getValue(iType, Oprnds[1]),
766 getValue(iType, Oprnds[2]));
767 break;
768 case Instruction::PHI: {
769 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000770 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000771
772 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000773 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000774 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
775 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
776 Result = PN;
777 break;
778 }
779
780 case Instruction::Shl:
781 case Instruction::Shr:
782 Result = new ShiftInst((Instruction::OtherOps)Opcode,
783 getValue(iType, Oprnds[0]),
784 getValue(Type::UByteTyID, Oprnds[1]));
785 break;
786 case Instruction::Ret:
787 if (Oprnds.size() == 0)
788 Result = new ReturnInst();
789 else if (Oprnds.size() == 1)
790 Result = new ReturnInst(getValue(iType, Oprnds[0]));
791 else
Reid Spencer24399722004-07-09 22:21:33 +0000792 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000793 break;
794
795 case Instruction::Br:
796 if (Oprnds.size() == 1)
797 Result = new BranchInst(getBasicBlock(Oprnds[0]));
798 else if (Oprnds.size() == 3)
Misha Brukman8a96c532005-04-21 21:44:41 +0000799 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000800 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000801 else
Reid Spencer24399722004-07-09 22:21:33 +0000802 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000803 break;
804 case Instruction::Switch: {
805 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000806 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000807
808 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000809 getBasicBlock(Oprnds[1]),
810 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000811 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000812 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000813 getBasicBlock(Oprnds[i+1]));
814 Result = I;
815 break;
816 }
817
Chris Lattnerdee199f2005-05-06 22:34:01 +0000818 case 58: // Call with extra operand for calling conv
819 case 59: // tail call, Fast CC
820 case 60: // normal call, Fast CC
821 case 61: // tail call, C Calling Conv
822 case Instruction::Call: { // Normal Call, C Calling Convention
Reid Spencer060d25d2004-06-29 23:29:38 +0000823 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000824 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000825
826 Value *F = getValue(iType, Oprnds[0]);
827
Chris Lattnerdee199f2005-05-06 22:34:01 +0000828 unsigned CallingConv = CallingConv::C;
829 bool isTailCall = false;
830
831 if (Opcode == 61 || Opcode == 59)
832 isTailCall = true;
Chris Lattnera65371e2006-05-26 18:42:34 +0000833
834 if (Opcode == 58) {
835 isTailCall = Oprnds.back() & 1;
836 CallingConv = Oprnds.back() >> 1;
837 Oprnds.pop_back();
838 } else if (Opcode == 59 || Opcode == 60) {
839 CallingConv = CallingConv::Fast;
840 }
841
Reid Spencer060d25d2004-06-29 23:29:38 +0000842 // Check to make sure we have a pointer to function type
843 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000844 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000845 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000846 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000847
848 std::vector<Value *> Params;
849 if (!FTy->isVarArg()) {
850 FunctionType::param_iterator It = FTy->param_begin();
851
852 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
853 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000854 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000855 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
856 }
857 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000858 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000859 } else {
860 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
861
862 unsigned FirstVariableOperand;
863 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000864 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000865
866 // Read all of the fixed arguments
867 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
868 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000869
Reid Spencer060d25d2004-06-29 23:29:38 +0000870 FirstVariableOperand = FTy->getNumParams();
871
Misha Brukman8a96c532005-04-21 21:44:41 +0000872 if ((Oprnds.size()-FirstVariableOperand) & 1)
Chris Lattner4a242b32004-10-14 01:39:18 +0000873 error("Invalid call instruction!"); // Must be pairs of type/value
Misha Brukman8a96c532005-04-21 21:44:41 +0000874
875 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000876 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000877 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
878 }
879
880 Result = new CallInst(F, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000881 if (isTailCall) cast<CallInst>(Result)->setTailCall();
882 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000883 break;
884 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000885 case 56: // Invoke with encoded CC
886 case 57: // Invoke Fast CC
887 case Instruction::Invoke: { // Invoke C CC
Misha Brukman8a96c532005-04-21 21:44:41 +0000888 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000889 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000890 Value *F = getValue(iType, Oprnds[0]);
891
892 // Check to make sure we have a pointer to function type
893 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000894 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000895 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000896 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000897 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000898 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000899
900 std::vector<Value *> Params;
901 BasicBlock *Normal, *Except;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000902 unsigned CallingConv = CallingConv::C;
903
904 if (Opcode == 57)
905 CallingConv = CallingConv::Fast;
906 else if (Opcode == 56) {
907 CallingConv = Oprnds.back();
908 Oprnds.pop_back();
909 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000910
911 if (!FTy->isVarArg()) {
912 Normal = getBasicBlock(Oprnds[1]);
913 Except = getBasicBlock(Oprnds[2]);
914
915 FunctionType::param_iterator It = FTy->param_begin();
916 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
917 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000918 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000919 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
920 }
921 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000922 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000923 } else {
924 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
925
926 Normal = getBasicBlock(Oprnds[0]);
927 Except = getBasicBlock(Oprnds[1]);
Misha Brukman8a96c532005-04-21 21:44:41 +0000928
Reid Spencer060d25d2004-06-29 23:29:38 +0000929 unsigned FirstVariableArgument = FTy->getNumParams()+2;
930 for (unsigned i = 2; i != FirstVariableArgument; ++i)
931 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
932 Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000933
Reid Spencer060d25d2004-06-29 23:29:38 +0000934 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000935 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000936
937 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
938 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
939 }
940
941 Result = new InvokeInst(F, Normal, Except, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000942 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000943 break;
944 }
Chris Lattner42ba6b42005-11-05 22:08:14 +0000945 case Instruction::Malloc: {
946 unsigned Align = 0;
947 if (Oprnds.size() == 2)
948 Align = (1 << Oprnds[1]) >> 1;
949 else if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000950 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000951 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000952 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000953
954 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Chris Lattner42ba6b42005-11-05 22:08:14 +0000955 getValue(Type::UIntTyID, Oprnds[0]), Align);
Reid Spencer060d25d2004-06-29 23:29:38 +0000956 break;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000957 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000958
Chris Lattner42ba6b42005-11-05 22:08:14 +0000959 case Instruction::Alloca: {
960 unsigned Align = 0;
961 if (Oprnds.size() == 2)
962 Align = (1 << Oprnds[1]) >> 1;
963 else if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000964 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000965 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000966 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000967
968 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Chris Lattner42ba6b42005-11-05 22:08:14 +0000969 getValue(Type::UIntTyID, Oprnds[0]), Align);
Reid Spencer060d25d2004-06-29 23:29:38 +0000970 break;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000971 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000972 case Instruction::Free:
973 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000974 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000975 Result = new FreeInst(getValue(iType, Oprnds[0]));
976 break;
977 case Instruction::GetElementPtr: {
978 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000979 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000980
981 std::vector<Value*> Idx;
982
983 const Type *NextTy = InstTy;
984 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
985 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Misha Brukman8a96c532005-04-21 21:44:41 +0000986 if (!TopTy)
987 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000988
989 unsigned ValIdx = Oprnds[i];
990 unsigned IdxTy = 0;
991 if (!hasRestrictedGEPTypes) {
992 // Struct indices are always uints, sequential type indices can be any
993 // of the 32 or 64-bit integer types. The actual choice of type is
994 // encoded in the low two bits of the slot number.
995 if (isa<StructType>(TopTy))
996 IdxTy = Type::UIntTyID;
997 else {
998 switch (ValIdx & 3) {
999 default:
1000 case 0: IdxTy = Type::UIntTyID; break;
1001 case 1: IdxTy = Type::IntTyID; break;
1002 case 2: IdxTy = Type::ULongTyID; break;
1003 case 3: IdxTy = Type::LongTyID; break;
1004 }
1005 ValIdx >>= 2;
1006 }
1007 } else {
1008 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
1009 }
1010
1011 Idx.push_back(getValue(IdxTy, ValIdx));
1012
1013 // Convert ubyte struct indices into uint struct indices.
1014 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
1015 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
1016 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
1017
1018 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
1019 }
1020
1021 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
1022 break;
1023 }
1024
1025 case 62: // volatile load
1026 case Instruction::Load:
1027 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +00001028 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001029 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
1030 break;
1031
Misha Brukman8a96c532005-04-21 21:44:41 +00001032 case 63: // volatile store
Reid Spencer060d25d2004-06-29 23:29:38 +00001033 case Instruction::Store: {
1034 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +00001035 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001036
1037 Value *Ptr = getValue(iType, Oprnds[1]);
1038 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
1039 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1040 Opcode == 63);
1041 break;
1042 }
1043 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001044 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001045 Result = new UnwindInst();
1046 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001047 case Instruction::Unreachable:
1048 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1049 Result = new UnreachableInst();
1050 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001051 } // end switch(Opcode)
Reid Spencer060d25d2004-06-29 23:29:38 +00001052
Reid Spencere1e96c02006-01-19 07:02:16 +00001053 BB->getInstList().push_back(Result);
1054
Reid Spencer060d25d2004-06-29 23:29:38 +00001055 unsigned TypeSlot;
1056 if (Result->getType() == InstTy)
1057 TypeSlot = iType;
1058 else
1059 TypeSlot = getTypeSlot(Result->getType());
1060
1061 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +00001062}
1063
Reid Spencer04cde2c2004-07-04 11:33:49 +00001064/// Get a particular numbered basic block, which might be a forward reference.
1065/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +00001066/// in a clean manner. This function is used when constructing phi, br, switch,
1067/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +00001068/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001069BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001070 // Make sure there is room in the table...
1071 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1072
1073 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1074 // has already created this block, or if the forward reference has already
1075 // been created.
1076 if (ParsedBasicBlocks[ID])
1077 return ParsedBasicBlocks[ID];
1078
1079 // Otherwise, the basic block has not yet been created. Do so and add it to
1080 // the ParsedBasicBlocks list.
1081 return ParsedBasicBlocks[ID] = new BasicBlock();
1082}
1083
Misha Brukman8a96c532005-04-21 21:44:41 +00001084/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001085/// This method reads in one of the basicblock packets. This method is not used
1086/// for bytecode files after LLVM 1.0
1087/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001088BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1089 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001090
1091 BasicBlock *BB = 0;
1092
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001093 if (ParsedBasicBlocks.size() == BlockNo)
1094 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1095 else if (ParsedBasicBlocks[BlockNo] == 0)
1096 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1097 else
1098 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001099
Reid Spencer060d25d2004-06-29 23:29:38 +00001100 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001101 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001102 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001103
Reid Spencer46b002c2004-07-11 17:28:43 +00001104 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001105 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001106}
1107
Reid Spencer04cde2c2004-07-04 11:33:49 +00001108/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001109/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001110/// in order to avoid per-basic-block overhead.
1111/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001112unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001113 unsigned BlockNo = 0;
1114 std::vector<unsigned> Args;
1115
Reid Spencer46b002c2004-07-11 17:28:43 +00001116 while (moreInBlock()) {
1117 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001118 BasicBlock *BB;
1119 if (ParsedBasicBlocks.size() == BlockNo)
1120 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1121 else if (ParsedBasicBlocks[BlockNo] == 0)
1122 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1123 else
1124 BB = ParsedBasicBlocks[BlockNo];
1125 ++BlockNo;
1126 F->getBasicBlockList().push_back(BB);
1127
1128 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001129 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001130 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001131
1132 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001133 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001134
Reid Spencer46b002c2004-07-11 17:28:43 +00001135 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001136 }
1137
1138 return BlockNo;
1139}
1140
Reid Spencer04cde2c2004-07-04 11:33:49 +00001141/// Parse a symbol table. This works for both module level and function
1142/// level symbol tables. For function level symbol tables, the CurrentFunction
1143/// parameter must be non-zero and the ST parameter must correspond to
1144/// CurrentFunction's symbol table. For Module level symbol tables, the
1145/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001146void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001147 SymbolTable *ST) {
1148 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001149
Chris Lattner39cacce2003-10-10 05:43:47 +00001150 // Allow efficient basic block lookup by number.
1151 std::vector<BasicBlock*> BBMap;
1152 if (CurrentFunction)
1153 for (Function::iterator I = CurrentFunction->begin(),
1154 E = CurrentFunction->end(); I != E; ++I)
1155 BBMap.push_back(I);
1156
Reid Spencer04cde2c2004-07-04 11:33:49 +00001157 /// In LLVM 1.3 we write types separately from values so
1158 /// The types are always first in the symbol table. This is
1159 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001160 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001161 // Symtab block header: [num entries]
1162 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001163 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001164 // Symtab entry: [def slot #][name]
1165 unsigned slot = read_vbr_uint();
1166 std::string Name = read_str();
1167 const Type* T = getType(slot);
1168 ST->insert(Name, T);
1169 }
1170 }
1171
Reid Spencer46b002c2004-07-11 17:28:43 +00001172 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001173 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001174 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001175 unsigned Typ = 0;
1176 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001177 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001178
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001179 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001180 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001181 unsigned slot = read_vbr_uint();
1182 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001183
Reid Spencer04cde2c2004-07-04 11:33:49 +00001184 // if we're reading a pre 1.3 bytecode file and the type plane
1185 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001186 if (isTypeType) {
1187 const Type* T = getType(slot);
1188 if (T == 0)
1189 error("Failed type look-up for name '" + Name + "'");
1190 ST->insert(Name, T);
1191 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001192 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001193 Value *V = 0;
1194 if (Typ == Type::LabelTyID) {
1195 if (slot < BBMap.size())
1196 V = BBMap[slot];
1197 } else {
1198 V = getValue(Typ, slot, false); // Find mapping...
1199 }
1200 if (V == 0)
1201 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001202 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001203 }
Chris Lattner00950542001-06-06 20:29:01 +00001204 }
1205 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001206 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001207 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001208}
1209
Misha Brukman8a96c532005-04-21 21:44:41 +00001210/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001211void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001212 for (unsigned i = 0; i != NumEntries; ++i) {
1213 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001214 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001215 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001216 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001217 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001218 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001219 }
1220}
1221
1222/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001223void BytecodeReader::ParseCompactionTable() {
1224
Reid Spencer46b002c2004-07-11 17:28:43 +00001225 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001226 if (Handler) Handler->handleCompactionTableBegin();
1227
Misha Brukman8a96c532005-04-21 21:44:41 +00001228 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001229 // we always write them first in the compaction table
1230 // because they can't occupy a "type plane" where the
1231 // Values reside.
1232 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001233 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001234 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001235 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001236
Reid Spencer46b002c2004-07-11 17:28:43 +00001237 // Compaction tables live in separate blocks so we have to loop
1238 // until we've read the whole thing.
1239 while (moreInBlock()) {
1240 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001241 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001242 unsigned Ty = 0;
1243 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001244
Reid Spencer46b002c2004-07-11 17:28:43 +00001245 // Decode the type from value read in. Most compaction table
1246 // planes will have one or two entries in them. If that's the
1247 // case then the length is encoded in the bottom two bits and
1248 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001249 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001250 // In this case, both low-order bits are set (value 3). This
1251 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001252 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001253 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001254 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001255 // In this case, the low-order bits specify the number of entries
1256 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001257 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001258 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001259 NumEntries &= 3;
1260 }
1261
Reid Spencer04cde2c2004-07-04 11:33:49 +00001262 // if we're reading a pre 1.3 bytecode file and the type plane
1263 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001264 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001265 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001266 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001267 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001268 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001269 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001270
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001271 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001272 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001273 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001274
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001275 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001276 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001277
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001278 // Push the implicit zero.
1279 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001280
1281 // Read in each of the entries, put them in the compaction table
1282 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001283 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001284 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001285 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001286 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001287 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001288 }
1289 }
1290 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001291 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001292 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001293}
Misha Brukman8a96c532005-04-21 21:44:41 +00001294
Reid Spencer46b002c2004-07-11 17:28:43 +00001295// Parse a single type. The typeid is read in first. If its a primitive type
1296// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001297// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001298// definition.
1299const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001300 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001301 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001302 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001303
1304 const Type *Result = 0;
1305 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1306 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001307
Reid Spencer060d25d2004-06-29 23:29:38 +00001308 switch (PrimType) {
1309 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001310 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001311
1312 unsigned NumParams = read_vbr_uint();
1313
1314 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001315 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001316 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001317
1318 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1319 if (isVarArg) Params.pop_back();
1320
1321 Result = FunctionType::get(RetType, Params, isVarArg);
1322 break;
1323 }
1324 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001325 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001326 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001327 Result = ArrayType::get(ElementType, NumElements);
1328 break;
1329 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001330 case Type::PackedTyID: {
1331 const Type *ElementType = readSanitizedType();
1332 unsigned NumElements = read_vbr_uint();
1333 Result = PackedType::get(ElementType, NumElements);
1334 break;
1335 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001336 case Type::StructTyID: {
1337 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001338 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001339 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001340 error("Invalid element type (type type) for structure!");
1341
Reid Spencer060d25d2004-06-29 23:29:38 +00001342 while (Typ) { // List is terminated by void/0 typeid
1343 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001344 if (read_typeid(Typ))
1345 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001346 }
1347
1348 Result = StructType::get(Elements);
1349 break;
1350 }
1351 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001352 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001353 break;
1354 }
1355
1356 case Type::OpaqueTyID: {
1357 Result = OpaqueType::get();
1358 break;
1359 }
1360
1361 default:
Reid Spencer24399722004-07-09 22:21:33 +00001362 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001363 break;
1364 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001365 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001366 return Result;
1367}
1368
Reid Spencer5b472d92004-08-21 20:49:23 +00001369// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001370// types. We know that recursive types will only reference the current slab of
1371// values in the type plane, but they can forward reference types before they
1372// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1373// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1374// this ugly problem, we pessimistically insert an opaque type for each type we
1375// are about to read. This means that forward references will resolve to
1376// something and when we reread the type later, we can replace the opaque type
1377// with a new resolved concrete type.
1378//
Reid Spencer46b002c2004-07-11 17:28:43 +00001379void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001380 assert(Tab.size() == 0 && "should not have read type constants in before!");
1381
1382 // Insert a bunch of opaque types to be resolved later...
1383 Tab.reserve(NumEntries);
1384 for (unsigned i = 0; i != NumEntries; ++i)
1385 Tab.push_back(OpaqueType::get());
1386
Misha Brukman8a96c532005-04-21 21:44:41 +00001387 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001388 Handler->handleTypeList(NumEntries);
1389
Chris Lattnereebac5f2005-10-03 21:26:53 +00001390 // If we are about to resolve types, make sure the type cache is clear.
1391 if (NumEntries)
1392 ModuleTypeIDCache.clear();
1393
Reid Spencer060d25d2004-06-29 23:29:38 +00001394 // Loop through reading all of the types. Forward types will make use of the
1395 // opaque types just inserted.
1396 //
1397 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001398 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001399 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001400 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001401 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001402
Misha Brukman8a96c532005-04-21 21:44:41 +00001403 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001404 // the opaque type we previously inserted with the new concrete value. This
1405 // approach helps with forward references to types. The refinement from the
1406 // abstract (opaque) type to the new type causes all uses of the abstract
1407 // type to use the concrete type (NewTy). This will also cause the opaque
1408 // type to be deleted.
1409 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1410
1411 // This should have replaced the old opaque type with the new type in the
1412 // value table... or with a preexisting type that was already in the system.
1413 // Let's just make sure it did.
1414 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1415 }
1416}
1417
Reid Spencer04cde2c2004-07-04 11:33:49 +00001418/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001419Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001420 // We must check for a ConstantExpr before switching by type because
1421 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001422 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001423 // 0 if not expr; numArgs if is expr
1424 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001425
Reid Spencer060d25d2004-06-29 23:29:38 +00001426 if (isExprNumArgs) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001427 if (!hasNoUndefValue) {
1428 // 'undef' is encoded with 'exprnumargs' == 1.
1429 if (isExprNumArgs == 1)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001430 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001431
Chris Lattner3bc5a602006-01-25 23:08:15 +00001432 // Inline asm is encoded with exprnumargs == ~0U.
1433 if (isExprNumArgs == ~0U) {
1434 std::string AsmStr = read_str();
1435 std::string ConstraintStr = read_str();
1436 unsigned Flags = read_vbr_uint();
1437
1438 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1439 const FunctionType *FTy =
1440 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1441
1442 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1443 error("Invalid constraints for inline asm");
1444 if (Flags & ~1U)
1445 error("Invalid flags for inline asm");
1446 bool HasSideEffects = Flags & 1;
1447 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
1448 }
1449
1450 --isExprNumArgs;
1451 }
1452
Reid Spencer060d25d2004-06-29 23:29:38 +00001453 // FIXME: Encoding of constant exprs could be much more compact!
1454 std::vector<Constant*> ArgVec;
1455 ArgVec.reserve(isExprNumArgs);
1456 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001457
1458 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1459 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001460
Reid Spencer060d25d2004-06-29 23:29:38 +00001461 // Read the slot number and types of each of the arguments
1462 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1463 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001464 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001465 if (read_typeid(ArgTypeSlot))
1466 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001467
Reid Spencer060d25d2004-06-29 23:29:38 +00001468 // Get the arg value from its slot if it exists, otherwise a placeholder
1469 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1470 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001471
Reid Spencer060d25d2004-06-29 23:29:38 +00001472 // Construct a ConstantExpr of the appropriate kind
1473 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001474 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001475 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001476
Reid Spencer060d25d2004-06-29 23:29:38 +00001477 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001478 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001479 return Result;
1480 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1481 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1482
1483 if (hasRestrictedGEPTypes) {
1484 const Type *BaseTy = ArgVec[0]->getType();
1485 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1486 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1487 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1488 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1489 if (isa<StructType>(*GTI)) {
1490 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001491 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001492 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1493 }
1494 }
1495
1496 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001497 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001498 return Result;
1499 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001500 if (ArgVec.size() != 3)
1501 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001502 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001503 ArgVec[2]);
1504 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001505 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001506 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001507 if (ArgVec.size() != 2 ||
1508 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1509 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001510 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1511 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1512 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001513 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001514 if (ArgVec.size() != 3 ||
1515 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1516 error("Invalid insertelement constand expr arguments");
1517
1518 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001519 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1520 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1521 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001522 } else if (Opcode == Instruction::ShuffleVector) {
1523 if (ArgVec.size() != 3 ||
1524 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001525 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001526 Constant *Result =
1527 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1528 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1529 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001530 } else { // All other 2-operand expressions
1531 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001532 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001533 return Result;
1534 }
1535 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001536
Reid Spencer060d25d2004-06-29 23:29:38 +00001537 // Ok, not an ConstantExpr. We now know how to read the given type...
1538 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001539 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001540 switch (Ty->getTypeID()) {
1541 case Type::BoolTyID: {
1542 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001543 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001544 error("Invalid boolean value read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001545 Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001546 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001547 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001548 }
1549
1550 case Type::UByteTyID: // Unsigned integer types...
1551 case Type::UShortTyID:
1552 case Type::UIntTyID: {
1553 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001554 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001555 error("Invalid unsigned byte/short/int read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001556 Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001557 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001558 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001559 }
1560
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001561 case Type::ULongTyID:
1562 Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001563 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001564 break;
1565
Reid Spencer060d25d2004-06-29 23:29:38 +00001566 case Type::SByteTyID: // Signed integer types...
1567 case Type::ShortTyID:
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001568 case Type::IntTyID:
1569 case Type::LongTyID: {
Reid Spencer060d25d2004-06-29 23:29:38 +00001570 int64_t Val = read_vbr_int64();
Misha Brukman8a96c532005-04-21 21:44:41 +00001571 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001572 error("Invalid signed byte/short/int/long read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001573 Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001574 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001575 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001576 }
1577
1578 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001579 float Val;
1580 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001581 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001582 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001583 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001584 }
1585
1586 case Type::DoubleTyID: {
1587 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001588 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001589 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001590 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001591 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001592 }
1593
Reid Spencer060d25d2004-06-29 23:29:38 +00001594 case Type::ArrayTyID: {
1595 const ArrayType *AT = cast<ArrayType>(Ty);
1596 unsigned NumElements = AT->getNumElements();
1597 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1598 std::vector<Constant*> Elements;
1599 Elements.reserve(NumElements);
1600 while (NumElements--) // Read all of the elements of the constant.
1601 Elements.push_back(getConstantValue(TypeSlot,
1602 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001603 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001604 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001605 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001606 }
1607
1608 case Type::StructTyID: {
1609 const StructType *ST = cast<StructType>(Ty);
1610
1611 std::vector<Constant *> Elements;
1612 Elements.reserve(ST->getNumElements());
1613 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1614 Elements.push_back(getConstantValue(ST->getElementType(i),
1615 read_vbr_uint()));
1616
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001617 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001618 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001619 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001620 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001621
Brian Gaeke715c90b2004-08-20 06:00:58 +00001622 case Type::PackedTyID: {
1623 const PackedType *PT = cast<PackedType>(Ty);
1624 unsigned NumElements = PT->getNumElements();
1625 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1626 std::vector<Constant*> Elements;
1627 Elements.reserve(NumElements);
1628 while (NumElements--) // Read all of the elements of the constant.
1629 Elements.push_back(getConstantValue(TypeSlot,
1630 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001631 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001632 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001633 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001634 }
1635
Chris Lattner638c3812004-11-19 16:24:05 +00001636 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001637 const PointerType *PT = cast<PointerType>(Ty);
1638 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001639
Reid Spencer060d25d2004-06-29 23:29:38 +00001640 // Check to see if we have already read this global variable...
1641 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001642 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001643 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1644 if (!GV) error("GlobalValue not in ValueTable!");
1645 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1646 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001647 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001648 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001649 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001650 }
1651
1652 default:
Reid Spencer24399722004-07-09 22:21:33 +00001653 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001654 Ty->getDescription());
1655 break;
1656 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001657
1658 // Check that we didn't read a null constant if they are implicit for this
1659 // type plane. Do not do this check for constantexprs, as they may be folded
1660 // to a null value in a way that isn't predicted when a .bc file is initially
1661 // produced.
1662 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1663 !hasImplicitNull(TypeID) &&
1664 "Cannot read null values from bytecode!");
1665 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001666}
1667
Misha Brukman8a96c532005-04-21 21:44:41 +00001668/// Resolve references for constants. This function resolves the forward
1669/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001670/// replaceAllUsesWith method of Value class to substitute the placeholder
1671/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001672void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1673 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001674 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001675 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001676 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001677
Chris Lattner29b789b2003-11-19 17:27:18 +00001678 Value *PH = I->second; // Get the placeholder...
1679 PH->replaceAllUsesWith(NewV);
1680 delete PH; // Delete the old placeholder
1681 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001682}
1683
Reid Spencer04cde2c2004-07-04 11:33:49 +00001684/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001685void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1686 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001687 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001688 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001689 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001690 const Type *Ty = getType(Typ);
1691 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001692 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001693
Reid Spencer060d25d2004-06-29 23:29:38 +00001694 const ArrayType *ATy = cast<ArrayType>(Ty);
1695 if (ATy->getElementType() != Type::SByteTy &&
1696 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001697 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001698
Reid Spencer060d25d2004-06-29 23:29:38 +00001699 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001700 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001701 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001702
Reid Spencer060d25d2004-06-29 23:29:38 +00001703 std::vector<Constant*> Elements(ATy->getNumElements());
1704 if (ATy->getElementType() == Type::SByteTy)
1705 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1706 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1707 else
1708 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1709 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001710
Reid Spencer060d25d2004-06-29 23:29:38 +00001711 // Create the constant, inserting it as needed.
1712 Constant *C = ConstantArray::get(ATy, Elements);
1713 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001714 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001715 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001716 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001717}
1718
Reid Spencer04cde2c2004-07-04 11:33:49 +00001719/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001720void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001721 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001722 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001723 if (Handler) Handler->handleGlobalConstantsBegin();
1724
1725 /// In LLVM 1.3 Type does not derive from Value so the types
1726 /// do not occupy a plane. Consequently, we read the types
1727 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001728 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001729 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001730 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001731 }
1732
Reid Spencer46b002c2004-07-11 17:28:43 +00001733 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001734 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001735 unsigned Typ = 0;
1736 bool isTypeType = read_typeid(Typ);
1737
1738 /// In LLVM 1.2 and before, Types were written to the
1739 /// bytecode file in the "Type Type" plane (#12).
1740 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001741 if (isTypeType) {
1742 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001743 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001744 /// Use of Type::VoidTyID is a misnomer. It actually means
1745 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001746 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1747 ParseStringConstants(NumEntries, Tab);
1748 } else {
1749 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001750 Value *V = ParseConstantPoolValue(Typ);
1751 assert(V && "ParseConstantPoolValue returned NULL!");
1752 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001753
Reid Spencer060d25d2004-06-29 23:29:38 +00001754 // If we are reading a function constant table, make sure that we adjust
1755 // the slot number to be the real global constant number.
1756 //
1757 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1758 ModuleValues[Typ])
1759 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001760 if (Constant *C = dyn_cast<Constant>(V))
1761 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001762 }
1763 }
1764 }
Chris Lattner02dce162004-12-04 05:28:27 +00001765
1766 // After we have finished parsing the constant pool, we had better not have
1767 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001768 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001769 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001770 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001771 error(utostr(ConstantFwdRefs.size()) +
1772 " unresolved constant reference exist. First one is '" +
1773 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001774 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001775 }
Chris Lattner02dce162004-12-04 05:28:27 +00001776
Reid Spencer060d25d2004-06-29 23:29:38 +00001777 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001778 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001779}
Chris Lattner00950542001-06-06 20:29:01 +00001780
Reid Spencer04cde2c2004-07-04 11:33:49 +00001781/// Parse the contents of a function. Note that this function can be
1782/// called lazily by materializeFunction
1783/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001784void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001785
1786 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001787 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1788
Reid Spencer060d25d2004-06-29 23:29:38 +00001789 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001790 switch (LinkageType) {
1791 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1792 case 1: Linkage = GlobalValue::WeakLinkage; break;
1793 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1794 case 3: Linkage = GlobalValue::InternalLinkage; break;
1795 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001796 default:
Reid Spencer24399722004-07-09 22:21:33 +00001797 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001798 Linkage = GlobalValue::InternalLinkage;
1799 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001800 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001801
Reid Spencer46b002c2004-07-11 17:28:43 +00001802 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001803 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001804
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001805 // Keep track of how many basic blocks we have read in...
1806 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001807 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001808
Reid Spencer060d25d2004-06-29 23:29:38 +00001809 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001810 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001811 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001812 BufPtr OldAt = At;
1813 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001814
1815 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001816 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001817 if (!InsertedArguments) {
1818 // Insert arguments into the value table before we parse the first basic
1819 // block in the function, but after we potentially read in the
1820 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001821 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001822 InsertedArguments = true;
1823 }
1824
Reid Spencer04cde2c2004-07-04 11:33:49 +00001825 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001826 break;
1827
Reid Spencerad89bd62004-07-25 18:07:36 +00001828 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001829 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001830 break;
1831
Chris Lattner00950542001-06-06 20:29:01 +00001832 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001833 if (!InsertedArguments) {
1834 // Insert arguments into the value table before we parse the first basic
1835 // block in the function, but after we potentially read in the
1836 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001837 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001838 InsertedArguments = true;
1839 }
1840
Reid Spencer060d25d2004-06-29 23:29:38 +00001841 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001842 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001843 break;
1844 }
1845
Reid Spencerad89bd62004-07-25 18:07:36 +00001846 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001847 // Insert arguments into the value table before we parse the instruction
1848 // list for the function, but after we potentially read in the compaction
1849 // table.
1850 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001851 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001852 InsertedArguments = true;
1853 }
1854
Misha Brukman8a96c532005-04-21 21:44:41 +00001855 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001856 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001857 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001858 break;
1859 }
1860
Reid Spencerad89bd62004-07-25 18:07:36 +00001861 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001862 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001863 break;
1864
1865 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001866 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001867 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001868 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001869 break;
1870 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001871 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001872
Misha Brukman12c29d12003-09-22 23:38:23 +00001873 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001874 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001875 }
1876
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001877 // Make sure there were no references to non-existant basic blocks.
1878 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001879 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001880
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001881 ParsedBasicBlocks.clear();
1882
Chris Lattner97330cf2003-10-09 23:10:14 +00001883 // Resolve forward references. Replace any uses of a forward reference value
1884 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001885 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001886 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1887 I = ForwardReferences.begin();
1888 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001889 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001890 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001891 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001892 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001893 }
Chris Lattner00950542001-06-06 20:29:01 +00001894
Reid Spencere2a5fb02006-01-27 11:49:27 +00001895 // If upgraded intrinsic functions were detected during reading of the
1896 // module information, then we need to look for instructions that need to
1897 // be upgraded. This can't be done while the instructions are read in because
1898 // additional instructions inserted mess up the slot numbering.
1899 if (!upgradedFunctions.empty()) {
1900 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
1901 for (BasicBlock::iterator II = BI->begin(), IE = BI->end();
Jim Laskeyf4321a32006-03-13 13:07:37 +00001902 II != IE;)
1903 if (CallInst* CI = dyn_cast<CallInst>(II++)) {
Reid Spencere2a5fb02006-01-27 11:49:27 +00001904 std::map<Function*,Function*>::iterator FI =
1905 upgradedFunctions.find(CI->getCalledFunction());
Chris Lattnerbad08002006-03-02 23:59:12 +00001906 if (FI != upgradedFunctions.end())
1907 UpgradeIntrinsicCall(CI, FI->second);
Reid Spencere2a5fb02006-01-27 11:49:27 +00001908 }
1909 }
1910
Misha Brukman12c29d12003-09-22 23:38:23 +00001911 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001912 FunctionTypes.clear();
1913 CompactionTypes.clear();
1914 CompactionValues.clear();
1915 freeTable(FunctionValues);
1916
Reid Spencer04cde2c2004-07-04 11:33:49 +00001917 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001918}
1919
Reid Spencer04cde2c2004-07-04 11:33:49 +00001920/// This function parses LLVM functions lazily. It obtains the type of the
1921/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001922/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001923/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001924void BytecodeReader::ParseFunctionLazily() {
1925 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001926 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001927
Reid Spencer060d25d2004-06-29 23:29:38 +00001928 Function *Func = FunctionSignatureList.back();
1929 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001930
Reid Spencer060d25d2004-06-29 23:29:38 +00001931 // Save the information for future reading of the function
1932 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001933
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001934 // This function has a body but it's not loaded so it appears `External'.
1935 // Mark it as a `Ghost' instead to notify the users that it has a body.
1936 Func->setLinkage(GlobalValue::GhostLinkage);
1937
Reid Spencer060d25d2004-06-29 23:29:38 +00001938 // Pretend we've `parsed' this function
1939 At = BlockEnd;
1940}
Chris Lattner89e02532004-01-18 21:08:15 +00001941
Misha Brukman8a96c532005-04-21 21:44:41 +00001942/// The ParserFunction method lazily parses one function. Use this method to
1943/// casue the parser to parse a specific function in the module. Note that
1944/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001945/// ParseAllFunctionBodies.
1946/// @see ParseAllFunctionBodies
1947/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001948void BytecodeReader::ParseFunction(Function* Func) {
1949 // Find {start, end} pointers and slot in the map. If not there, we're done.
1950 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001951
Reid Spencer060d25d2004-06-29 23:29:38 +00001952 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001953 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001954 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001955 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001956 }
1957
Reid Spencer060d25d2004-06-29 23:29:38 +00001958 BlockStart = At = Fi->second.Buf;
1959 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001960 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001961
1962 LazyFunctionLoadMap.erase(Fi);
1963
Reid Spencer46b002c2004-07-11 17:28:43 +00001964 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001965}
1966
Reid Spencer04cde2c2004-07-04 11:33:49 +00001967/// The ParseAllFunctionBodies method parses through all the previously
1968/// unparsed functions in the bytecode file. If you want to completely parse
1969/// a bytecode file, this method should be called after Parsebytecode because
1970/// Parsebytecode only records the locations in the bytecode file of where
1971/// the function definitions are located. This function uses that information
1972/// to materialize the functions.
1973/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001974void BytecodeReader::ParseAllFunctionBodies() {
1975 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1976 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001977
Reid Spencer46b002c2004-07-11 17:28:43 +00001978 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001979 Function* Func = Fi->first;
1980 BlockStart = At = Fi->second.Buf;
1981 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001982 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001983 ++Fi;
1984 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001985 LazyFunctionLoadMap.clear();
Reid Spencere2a5fb02006-01-27 11:49:27 +00001986
Reid Spencer060d25d2004-06-29 23:29:38 +00001987}
Chris Lattner89e02532004-01-18 21:08:15 +00001988
Reid Spencer04cde2c2004-07-04 11:33:49 +00001989/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001990void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001991 // Read the number of types
1992 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001993
1994 // Ignore the type plane identifier for types if the bc file is pre 1.3
1995 if (hasTypeDerivedFromValue)
1996 read_vbr_uint();
1997
Reid Spencer46b002c2004-07-11 17:28:43 +00001998 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001999}
2000
Reid Spencer04cde2c2004-07-04 11:33:49 +00002001/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00002002void BytecodeReader::ParseModuleGlobalInfo() {
2003
Reid Spencer04cde2c2004-07-04 11:33:49 +00002004 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00002005
Chris Lattner404cddf2005-11-12 01:33:40 +00002006 // SectionID - If a global has an explicit section specified, this map
2007 // remembers the ID until we can translate it into a string.
2008 std::map<GlobalValue*, unsigned> SectionID;
2009
Chris Lattner70cc3392001-09-10 07:58:01 +00002010 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002011 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002012 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00002013 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
2014 // Linkage, bit4+ = slot#
2015 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00002016 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00002017 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00002018 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00002019 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002020 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002021 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00002022 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002023
2024 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
2025 if (LinkageID == 3 && !hasInitializer) {
2026 unsigned ExtWord = read_vbr_uint();
2027 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
2028 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
2029 hasInitializer = ExtWord & 1;
2030 LinkageID = (ExtWord >> 1) & 7;
2031 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00002032
2033 if (ExtWord & (1 << 9)) // Has a section ID.
2034 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002035 }
Chris Lattnere3869c82003-04-16 21:16:05 +00002036
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002037 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002038 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00002039 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2040 case 1: Linkage = GlobalValue::WeakLinkage; break;
2041 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2042 case 3: Linkage = GlobalValue::InternalLinkage; break;
2043 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00002044 default:
Reid Spencer24399722004-07-09 22:21:33 +00002045 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00002046 Linkage = GlobalValue::InternalLinkage;
2047 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002048 }
2049
2050 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00002051 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00002052 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00002053
Chris Lattnere73bd452005-11-06 07:43:39 +00002054 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002055 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00002056
Chris Lattner52e20b02003-03-19 20:54:26 +00002057 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00002058
Chris Lattner70cc3392001-09-10 07:58:01 +00002059 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00002060 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00002061 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002062 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00002063 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00002064
Chris Lattner404cddf2005-11-12 01:33:40 +00002065 if (GlobalSectionID != 0)
2066 SectionID[GV] = GlobalSectionID;
2067
Reid Spencer060d25d2004-06-29 23:29:38 +00002068 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00002069 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002070 initSlot = read_vbr_uint();
2071 GlobalInits.push_back(std::make_pair(GV, initSlot));
2072 }
2073
2074 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00002075 if (Handler)
2076 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002077
2078 // Get next item
2079 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002080 }
2081
Chris Lattner52e20b02003-03-19 20:54:26 +00002082 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002083 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00002084
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002085 if (hasNoFlagsForFunctions)
2086 FnSignature = (FnSignature << 5) + 1;
2087
2088 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00002089 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
2090 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00002091 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00002092 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002093 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00002094 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00002095 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00002096
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002097 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00002098 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00002099 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00002100
Chris Lattner18549c22004-11-15 21:43:03 +00002101 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00002102 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002103 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00002104
Chris Lattnere73bd452005-11-06 07:43:39 +00002105 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002106
2107 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00002108 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00002109
Chris Lattner97fbc502004-11-15 22:38:52 +00002110 // Save this for later so we know type of lazily instantiated functions.
2111 // Note that known-external functions do not have FunctionInfo blocks, so we
2112 // do not add them to the FunctionSignatureList.
2113 if ((Flags & (1 << 4)) == 0)
2114 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00002115
Chris Lattnere73bd452005-11-06 07:43:39 +00002116 // Get the calling convention from the low bits.
2117 unsigned CC = Flags & 15;
2118 unsigned Alignment = 0;
2119 if (FnSignature & (1 << 31)) { // Has extension word?
2120 unsigned ExtWord = read_vbr_uint();
2121 Alignment = (1 << (ExtWord & 31)) >> 1;
2122 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00002123
2124 if (ExtWord & (1 << 10)) // Has a section ID.
2125 SectionID[Func] = read_vbr_uint();
Chris Lattnere73bd452005-11-06 07:43:39 +00002126 }
2127
Chris Lattner54b369e2005-11-06 07:46:13 +00002128 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00002129 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00002130
Reid Spencer04cde2c2004-07-04 11:33:49 +00002131 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002132
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002133 // Get the next function signature.
2134 FnSignature = read_vbr_uint();
2135 if (hasNoFlagsForFunctions)
2136 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00002137 }
2138
Misha Brukman8a96c532005-04-21 21:44:41 +00002139 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002140 // remove elements efficiently from the back of the vector.
2141 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002142
Chris Lattner404cddf2005-11-12 01:33:40 +00002143 /// SectionNames - This contains the list of section names encoded in the
2144 /// moduleinfoblock. Functions and globals with an explicit section index
2145 /// into this to get their section name.
2146 std::vector<std::string> SectionNames;
2147
2148 if (hasInconsistentModuleGlobalInfo) {
2149 align32();
2150 } else if (!hasNoDependentLibraries) {
2151 // If this bytecode format has dependent library information in it, read in
2152 // the number of dependent library items that follow.
Reid Spencerad89bd62004-07-25 18:07:36 +00002153 unsigned num_dep_libs = read_vbr_uint();
2154 std::string dep_lib;
Chris Lattner404cddf2005-11-12 01:33:40 +00002155 while (num_dep_libs--) {
Reid Spencerad89bd62004-07-25 18:07:36 +00002156 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00002157 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002158 if (Handler)
2159 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002160 }
2161
Chris Lattner404cddf2005-11-12 01:33:40 +00002162 // Read target triple and place into the module.
Reid Spencerad89bd62004-07-25 18:07:36 +00002163 std::string triple = read_str();
2164 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00002165 if (Handler)
2166 Handler->handleTargetTriple(triple);
Chris Lattner404cddf2005-11-12 01:33:40 +00002167
Chris Lattner7e6db762006-01-23 23:43:17 +00002168 if (!hasAlignment && At != BlockEnd) {
Chris Lattner404cddf2005-11-12 01:33:40 +00002169 // If the file has section info in it, read the section names now.
2170 unsigned NumSections = read_vbr_uint();
2171 while (NumSections--)
2172 SectionNames.push_back(read_str());
2173 }
Chris Lattner7e6db762006-01-23 23:43:17 +00002174
2175 // If the file has module-level inline asm, read it now.
2176 if (!hasAlignment && At != BlockEnd)
Chris Lattner66316012006-01-24 04:14:29 +00002177 TheModule->setModuleInlineAsm(read_str());
Reid Spencerad89bd62004-07-25 18:07:36 +00002178 }
2179
Chris Lattner404cddf2005-11-12 01:33:40 +00002180 // If any globals are in specified sections, assign them now.
2181 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2182 SectionID.end(); I != E; ++I)
2183 if (I->second) {
2184 if (I->second > SectionID.size())
2185 error("SectionID out of range for global!");
2186 I->first->setSection(SectionNames[I->second-1]);
2187 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002188
Chris Lattner00950542001-06-06 20:29:01 +00002189 // This is for future proofing... in the future extra fields may be added that
2190 // we don't understand, so we transparently ignore them.
2191 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002192 At = BlockEnd;
2193
Reid Spencer04cde2c2004-07-04 11:33:49 +00002194 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002195}
2196
Reid Spencer04cde2c2004-07-04 11:33:49 +00002197/// Parse the version information and decode it by setting flags on the
2198/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002199void BytecodeReader::ParseVersionInfo() {
2200 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002201
2202 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002203 Module::Endianness Endianness;
2204 Module::PointerSize PointerSize;
2205 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2206 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2207
2208 bool hasNoEndianness = Version & 4;
2209 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002210
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002211 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002212
2213 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002214 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002215 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002216 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002217 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002218 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002219 has32BitTypes = false;
2220 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002221 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002222 hasNoUndefValue = false;
2223 hasNoFlagsForFunctions = false;
2224 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002225
2226 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002227 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002228 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002229 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002230 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002231
Chris Lattner80b97342004-01-17 23:25:43 +00002232 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002233
2234 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002235 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002236
2237 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2238 // included the size for the alignment at the end, where the rest of the
2239 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002240
2241 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2242 // structures and longs for sequential types.
2243 hasRestrictedGEPTypes = true;
2244
Reid Spencer04cde2c2004-07-04 11:33:49 +00002245 // LLVM 1.2 and before had the Type class derive from Value class. This
2246 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002247 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002248 // type planes for Values.
2249 hasTypeDerivedFromValue = true;
2250
Chris Lattner5fa428f2004-04-05 01:27:26 +00002251 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002252
Reid Spencer5b472d92004-08-21 20:49:23 +00002253 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002254
Reid Spencer5b472d92004-08-21 20:49:23 +00002255 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002256 // especially for small files where the 8 bytes per block is a large
2257 // fraction of the total block size. In LLVM 1.3, the block type and length
2258 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2259 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002260 hasLongBlockHeaders = true;
2261
Reid Spencer5b472d92004-08-21 20:49:23 +00002262 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002263 // this has been reduced to vbr_uint24. It shouldn't make much difference
2264 // since we haven't run into a module with > 24 million types, but for
2265 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2266 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002267 has32BitTypes = true;
2268
Misha Brukman8a96c532005-04-21 21:44:41 +00002269 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002270 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2271 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002272 hasNoDependentLibraries = true;
2273
2274 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002275
2276 case 3: // LLVM 1.3 (Released)
2277 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002278 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002279 // of GEP references to a constant array), this can increase the file size
2280 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002281 hasAlignment = true;
2282
2283 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002284
Reid Spencer5b472d92004-08-21 20:49:23 +00002285 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002286 // In version 4, we did not support the 'undef' constant.
2287 hasNoUndefValue = true;
2288
2289 // In version 4 and above, we did not include space for flags for functions
2290 // in the module info block.
2291 hasNoFlagsForFunctions = true;
2292
2293 // In version 4 and above, we did not include the 'unreachable' instruction
2294 // in the opcode numbering in the bytecode file.
2295 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002296 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002297
2298 // FALL THROUGH
2299
Chris Lattnerdee199f2005-05-06 22:34:01 +00002300 case 5: // 1.4 (Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002301 break;
2302
Chris Lattner036b8aa2003-03-06 17:55:45 +00002303 default:
Reid Spencer24399722004-07-09 22:21:33 +00002304 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002305 }
2306
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002307 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2308 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002309
Brian Gaekefe2102b2004-07-14 20:33:13 +00002310 TheModule->setEndianness(Endianness);
2311 TheModule->setPointerSize(PointerSize);
2312
Reid Spencer46b002c2004-07-11 17:28:43 +00002313 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002314}
2315
Reid Spencer04cde2c2004-07-04 11:33:49 +00002316/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002317void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002318 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002319
Reid Spencer060d25d2004-06-29 23:29:38 +00002320 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002321
2322 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002323 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002324 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002325
Reid Spencer060d25d2004-06-29 23:29:38 +00002326 bool SeenModuleGlobalInfo = false;
2327 bool SeenGlobalTypePlane = false;
2328 BufPtr MyEnd = BlockEnd;
2329 while (At < MyEnd) {
2330 BufPtr OldAt = At;
2331 read_block(Type, Size);
2332
Chris Lattner00950542001-06-06 20:29:01 +00002333 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002334
Reid Spencerad89bd62004-07-25 18:07:36 +00002335 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002336 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002337 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002338
Reid Spencer5b472d92004-08-21 20:49:23 +00002339 if (Size > 0)
2340 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002341 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002342 break;
2343
Misha Brukman8a96c532005-04-21 21:44:41 +00002344 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002345 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002346 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002347 ParseModuleGlobalInfo();
2348 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002349 break;
2350
Reid Spencerad89bd62004-07-25 18:07:36 +00002351 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002352 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002353 break;
2354
Reid Spencerad89bd62004-07-25 18:07:36 +00002355 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002356 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002357 break;
Chris Lattner00950542001-06-06 20:29:01 +00002358
Reid Spencerad89bd62004-07-25 18:07:36 +00002359 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002360 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002361 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002362
Chris Lattner00950542001-06-06 20:29:01 +00002363 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002364 At += Size;
2365 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002366 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002367 }
Chris Lattner00950542001-06-06 20:29:01 +00002368 break;
2369 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002370 BlockEnd = MyEnd;
2371 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002372 }
2373
Chris Lattner52e20b02003-03-19 20:54:26 +00002374 // After the module constant pool has been read, we can safely initialize
2375 // global variables...
2376 while (!GlobalInits.empty()) {
2377 GlobalVariable *GV = GlobalInits.back().first;
2378 unsigned Slot = GlobalInits.back().second;
2379 GlobalInits.pop_back();
2380
2381 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002382 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002383
2384 const llvm::PointerType* GVType = GV->getType();
2385 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002386 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002387 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002388 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002389 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002390 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002391 } else
Reid Spencer24399722004-07-09 22:21:33 +00002392 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002393 }
2394
Chris Lattneraba5ff52005-05-05 20:57:00 +00002395 if (!ConstantFwdRefs.empty())
2396 error("Use of undefined constants in a module");
2397
Reid Spencer060d25d2004-06-29 23:29:38 +00002398 /// Make sure we pulled them all out. If we didn't then there's a declaration
2399 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002400 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002401 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002402}
2403
Reid Spencer04cde2c2004-07-04 11:33:49 +00002404/// This function completely parses a bytecode buffer given by the \p Buf
2405/// and \p Length parameters.
Misha Brukman8a96c532005-04-21 21:44:41 +00002406void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002407 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002408
Reid Spencer060d25d2004-06-29 23:29:38 +00002409 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002410 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002411 At = MemStart = BlockStart = Buf;
2412 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002413
Reid Spencer060d25d2004-06-29 23:29:38 +00002414 // Create the module
2415 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002416
Reid Spencer04cde2c2004-07-04 11:33:49 +00002417 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002418
Reid Spencerf0c977c2004-11-07 18:20:55 +00002419 // Read the four bytes of the signature.
2420 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002421
Reid Spencerf0c977c2004-11-07 18:20:55 +00002422 // If this is a compressed file
2423 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002424
Reid Spencerf0c977c2004-11-07 18:20:55 +00002425 // Invoke the decompression of the bytecode. Note that we have to skip the
2426 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002427 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2428 // member for retention until BytecodeReader is destructed.
2429 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2430 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002431
2432 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002433 // into the new decompressed block. After decompression, the
2434 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002435 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002436 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002437 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002438
Reid Spencerf0c977c2004-11-07 18:20:55 +00002439 // else if this isn't a regular (uncompressed) bytecode file, then its
2440 // and error, generate that now.
2441 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2442 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002443 }
2444
Reid Spencer060d25d2004-06-29 23:29:38 +00002445 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002446 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002447
Reid Spencerad89bd62004-07-25 18:07:36 +00002448 // Get the module block and size and verify. This is handled specially
2449 // because the module block/size is always written in long format. Other
2450 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002451 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002452 Type = read_uint();
2453 Size = read_uint();
2454 if (Type != BytecodeFormat::ModuleBlockID) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002455 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002456 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002457 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002458
2459 // It looks like the darwin ranlib program is broken, and adds trailing
2460 // garbage to the end of some bytecode files. This hack allows the bc
2461 // reader to ignore trailing garbage on bytecode files.
2462 if (At + Size < MemEnd)
2463 MemEnd = BlockEnd = At+Size;
2464
2465 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002466 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002467 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002468
2469 // Parse the module contents
2470 this->ParseModule();
2471
Reid Spencer060d25d2004-06-29 23:29:38 +00002472 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002473 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002474 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002475
Reid Spencere2a5fb02006-01-27 11:49:27 +00002476 // Look for intrinsic functions to upgrade, upgrade them, and save the
2477 // mapping from old function to new for use later when instructions are
2478 // converted.
2479 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2480 FI != FE; ++FI)
2481 if (Function* newF = UpgradeIntrinsicFunction(FI)) {
Chris Lattnerbad08002006-03-02 23:59:12 +00002482 upgradedFunctions.insert(std::make_pair(FI, newF));
Reid Spencere2a5fb02006-01-27 11:49:27 +00002483 FI->setName("");
2484 }
2485
Reid Spencer5c15fe52004-07-05 00:57:50 +00002486 // Tell the handler we're done with the module
Misha Brukman8a96c532005-04-21 21:44:41 +00002487 if (Handler)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002488 Handler->handleModuleEnd(ModuleID);
2489
2490 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002491 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002492
Reid Spencer46b002c2004-07-11 17:28:43 +00002493 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002494 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002495 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002496 delete TheModule;
2497 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002498 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002499 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002500 decompressedBlock = 0;
2501 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002502 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002503 } catch (...) {
2504 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002505 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002506 freeState();
2507 delete TheModule;
2508 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002509 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002510 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002511 decompressedBlock = 0;
2512 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002513 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002514 }
Chris Lattner00950542001-06-06 20:29:01 +00002515}
Reid Spencer060d25d2004-06-29 23:29:38 +00002516
2517//===----------------------------------------------------------------------===//
2518//=== Default Implementations of Handler Methods
2519//===----------------------------------------------------------------------===//
2520
2521BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002522