blob: c7e99d0c94dd81ddc76fd9b6f32319f7e9a348a3 [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
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
57 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000078 if (hasAlignment) {
79 BufPtr Save = At;
Jeff Cohen05ebc8d2006-01-25 17:18:50 +000080 At = (const unsigned char *)((intptr_t)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000081 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000082 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000083 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000084 error("Ran out of data while aligning!");
85 }
Reid Spencer060d25d2004-06-29 23:29:38 +000086}
87
Reid Spencer04cde2c2004-07-04 11:33:49 +000088/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000089inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000090 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000091 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000092 At += 4;
93 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
94}
95
Reid Spencer04cde2c2004-07-04 11:33:49 +000096/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000097inline unsigned BytecodeReader::read_vbr_uint() {
98 unsigned Shift = 0;
99 unsigned Result = 0;
100 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000101
Reid Spencer060d25d2004-06-29 23:29:38 +0000102 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000103 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000104 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000105 Result |= (unsigned)((*At++) & 0x7F) << Shift;
106 Shift += 7;
107 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000108 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 return Result;
110}
111
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000113inline uint64_t BytecodeReader::read_vbr_uint64() {
114 unsigned Shift = 0;
115 uint64_t Result = 0;
116 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000117
Reid Spencer060d25d2004-06-29 23:29:38 +0000118 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000119 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000120 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000121 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
122 Shift += 7;
123 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000124 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000125 return Result;
126}
127
Reid Spencer04cde2c2004-07-04 11:33:49 +0000128/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000129inline int64_t BytecodeReader::read_vbr_int64() {
130 uint64_t R = read_vbr_uint64();
131 if (R & 1) {
132 if (R != 1)
133 return -(int64_t)(R >> 1);
134 else // There is no such thing as -0 with integers. "-0" really means
135 // 0x8000000000000000.
136 return 1LL << 63;
137 } else
138 return (int64_t)(R >> 1);
139}
140
Reid Spencer04cde2c2004-07-04 11:33:49 +0000141/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000142inline std::string BytecodeReader::read_str() {
143 unsigned Size = read_vbr_uint();
144 const unsigned char *OldAt = At;
145 At += Size;
146 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000147 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000148 return std::string((char*)OldAt, Size);
149}
150
Reid Spencer04cde2c2004-07-04 11:33:49 +0000151/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000152inline void BytecodeReader::read_data(void *Ptr, void *End) {
153 unsigned char *Start = (unsigned char *)Ptr;
154 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000155 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000156 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000157 std::copy(At, At+Amount, Start);
158 At += Amount;
159}
160
Reid Spencer46b002c2004-07-11 17:28:43 +0000161/// Read a float value in little-endian order
162inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000163 /// FIXME: This isn't optimal, it has size problems on some platforms
164 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000165 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000166 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000167}
168
169/// Read a double value in little-endian order
170inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000171 /// FIXME: This isn't optimal, it has size problems on some platforms
172 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000173 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
174 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
175 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
176 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000177 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000178}
179
Reid Spencer04cde2c2004-07-04 11:33:49 +0000180/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000181inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000182 if ( hasLongBlockHeaders ) {
183 Type = read_uint();
184 Size = read_uint();
185 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000186 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000187 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000188 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000189 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000190 Type = BytecodeFormat::ModuleBlockID; break;
191 case BytecodeFormat::Function:
192 Type = BytecodeFormat::FunctionBlockID; break;
193 case BytecodeFormat::ConstantPool:
194 Type = BytecodeFormat::ConstantPoolBlockID; break;
195 case BytecodeFormat::SymbolTable:
196 Type = BytecodeFormat::SymbolTableBlockID; break;
197 case BytecodeFormat::ModuleGlobalInfo:
198 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
199 case BytecodeFormat::GlobalTypePlane:
200 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
201 case BytecodeFormat::InstructionList:
202 Type = BytecodeFormat::InstructionListBlockID; break;
203 case BytecodeFormat::CompactionTable:
204 Type = BytecodeFormat::CompactionTableBlockID; break;
205 case BytecodeFormat::BasicBlock:
206 /// This block type isn't used after version 1.1. However, we have to
207 /// still allow the value in case this is an old bc format file.
208 /// We just let its value creep thru.
209 break;
210 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000211 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000212 break;
213 }
214 } else {
215 Size = read_uint();
216 Type = Size & 0x1F; // mask low order five bits
217 Size >>= 5; // get rid of five low order bits, leaving high 27
218 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000219 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000220 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000221 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000222 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000223 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000224}
225
226
227/// In LLVM 1.2 and before, Types were derived from Value and so they were
228/// written as part of the type planes along with any other Value. In LLVM
229/// 1.3 this changed so that Type does not derive from Value. Consequently,
230/// the BytecodeReader's containers for Values can't contain Types because
231/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000232/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
233/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000234/// the types are always read/written first and then the Values. Furthermore
235/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
236/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
237/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
238/// For LLVM 1.2 and before, this function will decrement the type id by
239/// one to account for the missing Type::TypeTyID enumerator if the value is
240/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
241/// function returns true, otherwise false. This helps detect situations
242/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000243/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000244inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
245 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
246 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000247 TypeId = Type::VoidTyID; // sanitize it
248 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000249 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000250 --TypeId; // shift all planes down because type type plane is missing
251 }
252 return false;
253}
254
255/// Reads a vbr uint to read in a type id and does the necessary
256/// conversion on it by calling sanitizeTypeId.
257/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
258/// @see sanitizeTypeId
259inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
260 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000261 if ( !has32BitTypes )
262 if ( TypeId == 0x00FFFFFF )
263 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000264 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000265}
266
267//===----------------------------------------------------------------------===//
268// IR Lookup Methods
269//===----------------------------------------------------------------------===//
270
Reid Spencer04cde2c2004-07-04 11:33:49 +0000271/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000272inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000273 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000274 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000275 return TyID >= Type::FirstDerivedTyID;
276}
277
Reid Spencer04cde2c2004-07-04 11:33:49 +0000278/// Obtain a type given a typeid and account for things like compaction tables,
279/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000280const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000281 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000282 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000283 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000284
285 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000286 ID -= Type::FirstDerivedTyID;
287
Reid Spencer060d25d2004-06-29 23:29:38 +0000288 if (!CompactionTypes.empty()) {
289 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000290 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000291 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000292 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000293
294 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000295 if (ID < ModuleTypes.size())
296 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000297
Reid Spencer46b002c2004-07-11 17:28:43 +0000298 // Nope, is it a function-level type?
299 ID -= ModuleTypes.size();
300 if (ID < FunctionTypes.size())
301 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000302
Reid Spencer46b002c2004-07-11 17:28:43 +0000303 error("Illegal type reference!");
304 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000305}
306
Reid Spencer04cde2c2004-07-04 11:33:49 +0000307/// Get a sanitized type id. This just makes sure that the \p ID
308/// is both sanitized and not the "type type" of pre-1.3 bytecode.
309/// @see sanitizeTypeId
310inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000311 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000312 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000313 return getType(ID);
314}
315
316/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000317/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000318/// then calls getType to return the type value.
319inline const Type* BytecodeReader::readSanitizedType() {
320 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000321 if (read_typeid(ID))
322 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000323 return getType(ID);
324}
325
326/// Get the slot number associated with a type accounting for primitive
327/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000328unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
329 if (Ty->isPrimitiveType())
330 return Ty->getTypeID();
331
332 // Scan the compaction table for the type if needed.
333 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000334 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
335 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000336 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000337
Chris Lattner45b5dd22004-08-03 23:41:28 +0000338 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000339 }
340
341 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000342 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
343 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000344
345 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000346 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000347 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000348
Chris Lattnereebac5f2005-10-03 21:26:53 +0000349 // If we don't have our cache yet, build it now.
350 if (ModuleTypeIDCache.empty()) {
351 unsigned N = 0;
352 ModuleTypeIDCache.reserve(ModuleTypes.size());
353 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
354 I != E; ++I, ++N)
355 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
356
357 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
358 }
359
360 // Binary search the cache for the entry.
361 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
362 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
363 std::make_pair(Ty, 0U));
364 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000365 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000366
367 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000368}
369
Reid Spencer04cde2c2004-07-04 11:33:49 +0000370/// This is just like getType, but when a compaction table is in use, it is
371/// ignored. It also ignores function level types.
372/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000373const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
374 if (Slot < Type::FirstDerivedTyID) {
375 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000376 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000377 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000378 return Ty;
379 }
380 Slot -= Type::FirstDerivedTyID;
381 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000382 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000383 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000384}
385
Reid Spencer04cde2c2004-07-04 11:33:49 +0000386/// This is just like getTypeSlot, but when a compaction table is in use, it
387/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000388unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
389 if (Ty->isPrimitiveType())
390 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000391
392 // If we don't have our cache yet, build it now.
393 if (ModuleTypeIDCache.empty()) {
394 unsigned N = 0;
395 ModuleTypeIDCache.reserve(ModuleTypes.size());
396 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
397 I != E; ++I, ++N)
398 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
399
400 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
401 }
402
403 // Binary search the cache for the entry.
404 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
405 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
406 std::make_pair(Ty, 0U));
407 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000408 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000409
410 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000411}
412
Misha Brukman8a96c532005-04-21 21:44:41 +0000413/// Retrieve a value of a given type and slot number, possibly creating
414/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000415Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000416 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000417 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000418
Chris Lattner89e02532004-01-18 21:08:15 +0000419 // If there is a compaction table active, it defines the low-level numbers.
420 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000421 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
422 if (Num < CompactionValues[type].size())
423 return CompactionValues[type][Num];
424 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000425 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000426 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000427 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000428
Chris Lattner45b5dd22004-08-03 23:41:28 +0000429 // If the type plane was compactified, figure out the global type ID by
430 // adding the derived type ids and the distance.
431 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
432 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000433
Reid Spencer060d25d2004-06-29 23:29:38 +0000434 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000435 const Type *Ty = getType(type);
436 if (!isa<OpaqueType>(Ty)) {
437 if (Num == 0)
438 return Constant::getNullValue(Ty);
439 --Num;
440 }
Chris Lattner89e02532004-01-18 21:08:15 +0000441 }
442
Chris Lattner52f86d62004-01-20 00:54:06 +0000443 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
444 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000445 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000446 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000447 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000448 }
449
Misha Brukman8a96c532005-04-21 21:44:41 +0000450 if (FunctionValues.size() > type &&
451 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000452 Num < FunctionValues[type]->size())
453 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000454
Chris Lattner74734132002-08-17 22:01:27 +0000455 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000456
Reid Spencer551ccae2004-09-01 22:55:40 +0000457 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000458 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000459 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000460 if (I != ForwardReferences.end() && I->first == KeyValue)
461 return I->second; // We have already created this placeholder
462
Reid Spencer551ccae2004-09-01 22:55:40 +0000463 // If the type exists (it should)
464 if (const Type* Ty = getType(type)) {
465 // Create the place holder
466 Value *Val = new Argument(Ty);
467 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
468 return Val;
469 }
Reid Spencer233fe722006-08-22 16:09:19 +0000470 error("Can't create placeholder for value of type slot #" + utostr(type));
471 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000472}
473
Misha Brukman8a96c532005-04-21 21:44:41 +0000474/// This is just like getValue, but when a compaction table is in use, it
475/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000476/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000477Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
478 if (SlotNo == 0)
479 return Constant::getNullValue(getType(TyID));
480
481 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
482 TyID -= Type::FirstDerivedTyID;
483 if (TyID >= CompactionTypes.size())
484 error("Type ID out of range for compaction table!");
485 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000486 }
487
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000488 --SlotNo;
489
Reid Spencer060d25d2004-06-29 23:29:38 +0000490 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
491 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000492 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
493 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000494 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000495 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000496 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000497 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000498 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000499 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000500 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
501 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000502 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000503 }
504 return ModuleValues[TyID]->getOperand(SlotNo);
505}
506
Reid Spencer04cde2c2004-07-04 11:33:49 +0000507/// Just like getValue, except that it returns a null pointer
508/// only on error. It always returns a constant (meaning that if the value is
509/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000510/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000511/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000512Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
513 if (Value *V = getValue(TypeSlot, Slot, false))
514 if (Constant *C = dyn_cast<Constant>(V))
515 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000516 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000517 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000518 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000519
Chris Lattner389bd042004-12-09 06:19:44 +0000520 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000521 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
522
523 if (I != ConstantFwdRefs.end() && I->first == Key) {
524 return I->second;
525 } else {
526 // Create a placeholder for the constant reference and
527 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000528 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000529
Reid Spencer060d25d2004-06-29 23:29:38 +0000530 // Keep track of the fact that we have a forward ref to recycle it
531 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
532 return C;
533 }
534}
535
536//===----------------------------------------------------------------------===//
537// IR Construction Methods
538//===----------------------------------------------------------------------===//
539
Reid Spencer04cde2c2004-07-04 11:33:49 +0000540/// As values are created, they are inserted into the appropriate place
541/// with this method. The ValueTable argument must be one of ModuleValues
542/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000543unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000544 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000545 if (ValueTab.size() <= type)
546 ValueTab.resize(type+1);
547
548 if (!ValueTab[type]) ValueTab[type] = new ValueList();
549
550 ValueTab[type]->push_back(Val);
551
Chris Lattneraba5ff52005-05-05 20:57:00 +0000552 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000553 return ValueTab[type]->size()-1 + HasOffset;
554}
555
Reid Spencer04cde2c2004-07-04 11:33:49 +0000556/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000557void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000558 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000559 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000560 for (FunctionType::param_iterator It = FT->param_begin();
561 It != FT->param_end(); ++It, ++AI)
562 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
563}
564
565//===----------------------------------------------------------------------===//
566// Bytecode Parsing Methods
567//===----------------------------------------------------------------------===//
568
Reid Spencer04cde2c2004-07-04 11:33:49 +0000569/// This method parses a single instruction. The instruction is
570/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000571/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000572void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000573 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000574 BufPtr SaveAt = At;
575
576 // Clear instruction data
577 Oprnds.clear();
578 unsigned iType = 0;
579 unsigned Opcode = 0;
580 unsigned Op = read_uint();
581
582 // bits Instruction format: Common to all formats
583 // --------------------------
584 // 01-00: Opcode type, fixed to 1.
585 // 07-02: Opcode
586 Opcode = (Op >> 2) & 63;
587 Oprnds.resize((Op >> 0) & 03);
588
589 // Extract the operands
590 switch (Oprnds.size()) {
591 case 1:
592 // bits Instruction format:
593 // --------------------------
594 // 19-08: Resulting type plane
595 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
596 //
597 iType = (Op >> 8) & 4095;
598 Oprnds[0] = (Op >> 20) & 4095;
599 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
600 Oprnds.resize(0);
601 break;
602 case 2:
603 // bits Instruction format:
604 // --------------------------
605 // 15-08: Resulting type plane
606 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000607 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000608 //
609 iType = (Op >> 8) & 255;
610 Oprnds[0] = (Op >> 16) & 255;
611 Oprnds[1] = (Op >> 24) & 255;
612 break;
613 case 3:
614 // bits Instruction format:
615 // --------------------------
616 // 13-08: Resulting type plane
617 // 19-14: Operand #1
618 // 25-20: Operand #2
619 // 31-26: Operand #3
620 //
621 iType = (Op >> 8) & 63;
622 Oprnds[0] = (Op >> 14) & 63;
623 Oprnds[1] = (Op >> 20) & 63;
624 Oprnds[2] = (Op >> 26) & 63;
625 break;
626 case 0:
627 At -= 4; // Hrm, try this again...
628 Opcode = read_vbr_uint();
629 Opcode >>= 2;
630 iType = read_vbr_uint();
631
632 unsigned NumOprnds = read_vbr_uint();
633 Oprnds.resize(NumOprnds);
634
635 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000636 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000637
638 for (unsigned i = 0; i != NumOprnds; ++i)
639 Oprnds[i] = read_vbr_uint();
640 align32();
641 break;
642 }
643
Reid Spencer04cde2c2004-07-04 11:33:49 +0000644 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000645
Reid Spencer46b002c2004-07-11 17:28:43 +0000646 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000647 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000648
649 // Declare the resulting instruction we'll build.
650 Instruction *Result = 0;
651
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000652 // If this is a bytecode format that did not include the unreachable
653 // instruction, bump up all opcodes numbers to make space.
654 if (hasNoUnreachableInst) {
655 if (Opcode >= Instruction::Unreachable &&
656 Opcode < 62) {
657 ++Opcode;
658 }
659 }
660
Reid Spencer060d25d2004-06-29 23:29:38 +0000661 // Handle binary operators
662 if (Opcode >= Instruction::BinaryOpsBegin &&
663 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
664 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
665 getValue(iType, Oprnds[0]),
666 getValue(iType, Oprnds[1]));
667
Reid Spencere1e96c02006-01-19 07:02:16 +0000668 bool isCall = false;
Reid Spencer060d25d2004-06-29 23:29:38 +0000669 switch (Opcode) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000670 default:
671 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000672 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000673 break;
674 case Instruction::VAArg:
Misha Brukman8a96c532005-04-21 21:44:41 +0000675 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000676 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000677 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000678 case 32: { //VANext_old
679 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000680 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
681 (Type *)0);
Andrew Lenharth558bc882005-06-18 18:34:52 +0000682
683 //b = vanext a, t ->
684 //foo = alloca 1 of t
685 //bar = vacopy a
686 //store bar -> foo
687 //tmp = vaarg foo, t
688 //b = load foo
689 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
690 BB->getInstList().push_back(foo);
691 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
692 BB->getInstList().push_back(bar);
693 BB->getInstList().push_back(new StoreInst(bar, foo));
694 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
695 BB->getInstList().push_back(tmp);
696 Result = new LoadInst(foo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000697 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000698 }
699 case 33: { //VAArg_old
700 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000701 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
702 (Type *)0);
Andrew Lenharth558bc882005-06-18 18:34:52 +0000703
Jeff Cohen00b168892005-07-27 06:12:32 +0000704 //b = vaarg a, t ->
Andrew Lenharth558bc882005-06-18 18:34:52 +0000705 //foo = alloca 1 of t
Jeff Cohen00b168892005-07-27 06:12:32 +0000706 //bar = vacopy a
Andrew Lenharth558bc882005-06-18 18:34:52 +0000707 //store bar -> foo
708 //b = vaarg foo, t
709 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
710 BB->getInstList().push_back(foo);
711 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
712 BB->getInstList().push_back(bar);
713 BB->getInstList().push_back(new StoreInst(bar, foo));
714 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
715 break;
716 }
Robert Bocchinofee31b32006-01-10 19:04:39 +0000717 case Instruction::ExtractElement: {
718 if (Oprnds.size() != 2)
Reid Spencer233fe722006-08-22 16:09:19 +0000719 error("Invalid extractelement instruction!");
Chris Lattner59fecec2006-04-08 04:09:19 +0000720 Value *V1 = getValue(iType, Oprnds[0]);
721 Value *V2 = getValue(Type::UIntTyID, Oprnds[1]);
722
723 if (!ExtractElementInst::isValidOperands(V1, V2))
Reid Spencer233fe722006-08-22 16:09:19 +0000724 error("Invalid extractelement instruction!");
Chris Lattner59fecec2006-04-08 04:09:19 +0000725
726 Result = new ExtractElementInst(V1, V2);
Robert Bocchinofee31b32006-01-10 19:04:39 +0000727 break;
728 }
Robert Bocchinob1f240b2006-01-17 20:06:35 +0000729 case Instruction::InsertElement: {
730 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
731 if (!PackedTy || Oprnds.size() != 3)
Reid Spencer233fe722006-08-22 16:09:19 +0000732 error("Invalid insertelement instruction!");
Chris Lattner59fecec2006-04-08 04:09:19 +0000733
734 Value *V1 = getValue(iType, Oprnds[0]);
735 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()), Oprnds[1]);
736 Value *V3 = getValue(Type::UIntTyID, Oprnds[2]);
737
738 if (!InsertElementInst::isValidOperands(V1, V2, V3))
Reid Spencer233fe722006-08-22 16:09:19 +0000739 error("Invalid insertelement instruction!");
Chris Lattner59fecec2006-04-08 04:09:19 +0000740 Result = new InsertElementInst(V1, V2, V3);
Robert Bocchinob1f240b2006-01-17 20:06:35 +0000741 break;
742 }
Chris Lattner30b44b62006-04-08 01:17:59 +0000743 case Instruction::ShuffleVector: {
744 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
745 if (!PackedTy || Oprnds.size() != 3)
Reid Spencer233fe722006-08-22 16:09:19 +0000746 error("Invalid shufflevector instruction!");
Chris Lattner30b44b62006-04-08 01:17:59 +0000747 Value *V1 = getValue(iType, Oprnds[0]);
748 Value *V2 = getValue(iType, Oprnds[1]);
749 const PackedType *EltTy =
750 PackedType::get(Type::UIntTy, PackedTy->getNumElements());
751 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
752 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
Reid Spencer233fe722006-08-22 16:09:19 +0000753 error("Invalid shufflevector instruction!");
Chris Lattner30b44b62006-04-08 01:17:59 +0000754 Result = new ShuffleVectorInst(V1, V2, V3);
755 break;
756 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000757 case Instruction::Cast:
Misha Brukman8a96c532005-04-21 21:44:41 +0000758 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000759 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000760 break;
761 case Instruction::Select:
762 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
763 getValue(iType, Oprnds[1]),
764 getValue(iType, Oprnds[2]));
765 break;
766 case Instruction::PHI: {
767 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000768 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000769
770 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000771 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000772 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
773 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
774 Result = PN;
775 break;
776 }
777
778 case Instruction::Shl:
779 case Instruction::Shr:
780 Result = new ShiftInst((Instruction::OtherOps)Opcode,
781 getValue(iType, Oprnds[0]),
782 getValue(Type::UByteTyID, Oprnds[1]));
783 break;
784 case Instruction::Ret:
785 if (Oprnds.size() == 0)
786 Result = new ReturnInst();
787 else if (Oprnds.size() == 1)
788 Result = new ReturnInst(getValue(iType, Oprnds[0]));
789 else
Reid Spencer24399722004-07-09 22:21:33 +0000790 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000791 break;
792
793 case Instruction::Br:
794 if (Oprnds.size() == 1)
795 Result = new BranchInst(getBasicBlock(Oprnds[0]));
796 else if (Oprnds.size() == 3)
Misha Brukman8a96c532005-04-21 21:44:41 +0000797 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000798 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000799 else
Reid Spencer24399722004-07-09 22:21:33 +0000800 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000801 break;
802 case Instruction::Switch: {
803 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000804 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000805
806 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000807 getBasicBlock(Oprnds[1]),
808 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000809 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000810 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000811 getBasicBlock(Oprnds[i+1]));
812 Result = I;
813 break;
814 }
815
Chris Lattnerdee199f2005-05-06 22:34:01 +0000816 case 58: // Call with extra operand for calling conv
817 case 59: // tail call, Fast CC
818 case 60: // normal call, Fast CC
819 case 61: // tail call, C Calling Conv
820 case Instruction::Call: { // Normal Call, C Calling Convention
Reid Spencer060d25d2004-06-29 23:29:38 +0000821 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000822 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000823
824 Value *F = getValue(iType, Oprnds[0]);
825
Chris Lattnerdee199f2005-05-06 22:34:01 +0000826 unsigned CallingConv = CallingConv::C;
827 bool isTailCall = false;
828
829 if (Opcode == 61 || Opcode == 59)
830 isTailCall = true;
Chris Lattnera65371e2006-05-26 18:42:34 +0000831
832 if (Opcode == 58) {
833 isTailCall = Oprnds.back() & 1;
834 CallingConv = Oprnds.back() >> 1;
835 Oprnds.pop_back();
836 } else if (Opcode == 59 || Opcode == 60) {
837 CallingConv = CallingConv::Fast;
838 }
839
Reid Spencer060d25d2004-06-29 23:29:38 +0000840 // Check to make sure we have a pointer to function type
841 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000842 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000843 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000844 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000845
846 std::vector<Value *> Params;
847 if (!FTy->isVarArg()) {
848 FunctionType::param_iterator It = FTy->param_begin();
849
850 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
851 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000852 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000853 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
854 }
855 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000856 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000857 } else {
858 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
859
860 unsigned FirstVariableOperand;
861 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000862 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000863
864 // Read all of the fixed arguments
865 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
866 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000867
Reid Spencer060d25d2004-06-29 23:29:38 +0000868 FirstVariableOperand = FTy->getNumParams();
869
Misha Brukman8a96c532005-04-21 21:44:41 +0000870 if ((Oprnds.size()-FirstVariableOperand) & 1)
Chris Lattner4a242b32004-10-14 01:39:18 +0000871 error("Invalid call instruction!"); // Must be pairs of type/value
Misha Brukman8a96c532005-04-21 21:44:41 +0000872
873 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000874 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000875 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
876 }
877
878 Result = new CallInst(F, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000879 if (isTailCall) cast<CallInst>(Result)->setTailCall();
880 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000881 break;
882 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000883 case 56: // Invoke with encoded CC
884 case 57: // Invoke Fast CC
885 case Instruction::Invoke: { // Invoke C CC
Misha Brukman8a96c532005-04-21 21:44:41 +0000886 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000887 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000888 Value *F = getValue(iType, Oprnds[0]);
889
890 // Check to make sure we have a pointer to function type
891 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000892 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000893 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000894 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000895 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000896 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000897
898 std::vector<Value *> Params;
899 BasicBlock *Normal, *Except;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000900 unsigned CallingConv = CallingConv::C;
901
902 if (Opcode == 57)
903 CallingConv = CallingConv::Fast;
904 else if (Opcode == 56) {
905 CallingConv = Oprnds.back();
906 Oprnds.pop_back();
907 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000908
909 if (!FTy->isVarArg()) {
910 Normal = getBasicBlock(Oprnds[1]);
911 Except = getBasicBlock(Oprnds[2]);
912
913 FunctionType::param_iterator It = FTy->param_begin();
914 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
915 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000916 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000917 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
918 }
919 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000920 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000921 } else {
922 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
923
924 Normal = getBasicBlock(Oprnds[0]);
925 Except = getBasicBlock(Oprnds[1]);
Misha Brukman8a96c532005-04-21 21:44:41 +0000926
Reid Spencer060d25d2004-06-29 23:29:38 +0000927 unsigned FirstVariableArgument = FTy->getNumParams()+2;
928 for (unsigned i = 2; i != FirstVariableArgument; ++i)
929 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
930 Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000931
Reid Spencer060d25d2004-06-29 23:29:38 +0000932 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000933 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000934
935 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
936 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
937 }
938
939 Result = new InvokeInst(F, Normal, Except, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000940 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000941 break;
942 }
Chris Lattner42ba6b42005-11-05 22:08:14 +0000943 case Instruction::Malloc: {
944 unsigned Align = 0;
945 if (Oprnds.size() == 2)
946 Align = (1 << Oprnds[1]) >> 1;
947 else if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000948 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000949 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000950 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000951
952 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Chris Lattner42ba6b42005-11-05 22:08:14 +0000953 getValue(Type::UIntTyID, Oprnds[0]), Align);
Reid Spencer060d25d2004-06-29 23:29:38 +0000954 break;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000955 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000956
Chris Lattner42ba6b42005-11-05 22:08:14 +0000957 case Instruction::Alloca: {
958 unsigned Align = 0;
959 if (Oprnds.size() == 2)
960 Align = (1 << Oprnds[1]) >> 1;
961 else if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000962 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000963 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000964 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000965
966 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Chris Lattner42ba6b42005-11-05 22:08:14 +0000967 getValue(Type::UIntTyID, Oprnds[0]), Align);
Reid Spencer060d25d2004-06-29 23:29:38 +0000968 break;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000969 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000970 case Instruction::Free:
971 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000972 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000973 Result = new FreeInst(getValue(iType, Oprnds[0]));
974 break;
975 case Instruction::GetElementPtr: {
976 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000977 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000978
979 std::vector<Value*> Idx;
980
981 const Type *NextTy = InstTy;
982 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
983 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Misha Brukman8a96c532005-04-21 21:44:41 +0000984 if (!TopTy)
985 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000986
987 unsigned ValIdx = Oprnds[i];
988 unsigned IdxTy = 0;
989 if (!hasRestrictedGEPTypes) {
990 // Struct indices are always uints, sequential type indices can be any
991 // of the 32 or 64-bit integer types. The actual choice of type is
992 // encoded in the low two bits of the slot number.
993 if (isa<StructType>(TopTy))
994 IdxTy = Type::UIntTyID;
995 else {
996 switch (ValIdx & 3) {
997 default:
998 case 0: IdxTy = Type::UIntTyID; break;
999 case 1: IdxTy = Type::IntTyID; break;
1000 case 2: IdxTy = Type::ULongTyID; break;
1001 case 3: IdxTy = Type::LongTyID; break;
1002 }
1003 ValIdx >>= 2;
1004 }
1005 } else {
1006 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
1007 }
1008
1009 Idx.push_back(getValue(IdxTy, ValIdx));
1010
1011 // Convert ubyte struct indices into uint struct indices.
1012 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
Reid Spencerb83eb642006-10-20 07:07:24 +00001013 if (ConstantInt *C = dyn_cast<ConstantInt>(Idx.back()))
1014 if (C->getType() == Type::UByteTy)
1015 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
Reid Spencer060d25d2004-06-29 23:29:38 +00001016
1017 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
1018 }
1019
1020 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
1021 break;
1022 }
1023
1024 case 62: // volatile load
1025 case Instruction::Load:
1026 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +00001027 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001028 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
1029 break;
1030
Misha Brukman8a96c532005-04-21 21:44:41 +00001031 case 63: // volatile store
Reid Spencer060d25d2004-06-29 23:29:38 +00001032 case Instruction::Store: {
1033 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +00001034 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001035
1036 Value *Ptr = getValue(iType, Oprnds[1]);
1037 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
1038 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1039 Opcode == 63);
1040 break;
1041 }
1042 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001043 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001044 Result = new UnwindInst();
1045 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001046 case Instruction::Unreachable:
1047 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1048 Result = new UnreachableInst();
1049 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001050 } // end switch(Opcode)
Reid Spencer060d25d2004-06-29 23:29:38 +00001051
Reid Spencere1e96c02006-01-19 07:02:16 +00001052 BB->getInstList().push_back(Result);
1053
Reid Spencer060d25d2004-06-29 23:29:38 +00001054 unsigned TypeSlot;
1055 if (Result->getType() == InstTy)
1056 TypeSlot = iType;
1057 else
1058 TypeSlot = getTypeSlot(Result->getType());
1059
1060 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +00001061}
1062
Reid Spencer04cde2c2004-07-04 11:33:49 +00001063/// Get a particular numbered basic block, which might be a forward reference.
1064/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +00001065/// in a clean manner. This function is used when constructing phi, br, switch,
1066/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +00001067/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001068BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001069 // Make sure there is room in the table...
1070 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1071
1072 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1073 // has already created this block, or if the forward reference has already
1074 // been created.
1075 if (ParsedBasicBlocks[ID])
1076 return ParsedBasicBlocks[ID];
1077
1078 // Otherwise, the basic block has not yet been created. Do so and add it to
1079 // the ParsedBasicBlocks list.
1080 return ParsedBasicBlocks[ID] = new BasicBlock();
1081}
1082
Misha Brukman8a96c532005-04-21 21:44:41 +00001083/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001084/// This method reads in one of the basicblock packets. This method is not used
1085/// for bytecode files after LLVM 1.0
1086/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001087BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1088 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001089
1090 BasicBlock *BB = 0;
1091
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001092 if (ParsedBasicBlocks.size() == BlockNo)
1093 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1094 else if (ParsedBasicBlocks[BlockNo] == 0)
1095 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1096 else
1097 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001098
Reid Spencer060d25d2004-06-29 23:29:38 +00001099 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001100 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001101 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001102
Reid Spencer46b002c2004-07-11 17:28:43 +00001103 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001104 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001105}
1106
Reid Spencer04cde2c2004-07-04 11:33:49 +00001107/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001108/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001109/// in order to avoid per-basic-block overhead.
1110/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001111unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001112 unsigned BlockNo = 0;
1113 std::vector<unsigned> Args;
1114
Reid Spencer46b002c2004-07-11 17:28:43 +00001115 while (moreInBlock()) {
1116 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001117 BasicBlock *BB;
1118 if (ParsedBasicBlocks.size() == BlockNo)
1119 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1120 else if (ParsedBasicBlocks[BlockNo] == 0)
1121 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1122 else
1123 BB = ParsedBasicBlocks[BlockNo];
1124 ++BlockNo;
1125 F->getBasicBlockList().push_back(BB);
1126
1127 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001128 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001129 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001130
1131 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001132 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001133
Reid Spencer46b002c2004-07-11 17:28:43 +00001134 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001135 }
1136
1137 return BlockNo;
1138}
1139
Reid Spencer04cde2c2004-07-04 11:33:49 +00001140/// Parse a symbol table. This works for both module level and function
1141/// level symbol tables. For function level symbol tables, the CurrentFunction
1142/// parameter must be non-zero and the ST parameter must correspond to
1143/// CurrentFunction's symbol table. For Module level symbol tables, the
1144/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001145void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001146 SymbolTable *ST) {
1147 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001148
Chris Lattner39cacce2003-10-10 05:43:47 +00001149 // Allow efficient basic block lookup by number.
1150 std::vector<BasicBlock*> BBMap;
1151 if (CurrentFunction)
1152 for (Function::iterator I = CurrentFunction->begin(),
1153 E = CurrentFunction->end(); I != E; ++I)
1154 BBMap.push_back(I);
1155
Reid Spencer04cde2c2004-07-04 11:33:49 +00001156 /// In LLVM 1.3 we write types separately from values so
1157 /// The types are always first in the symbol table. This is
1158 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001159 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001160 // Symtab block header: [num entries]
1161 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001162 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001163 // Symtab entry: [def slot #][name]
1164 unsigned slot = read_vbr_uint();
1165 std::string Name = read_str();
1166 const Type* T = getType(slot);
1167 ST->insert(Name, T);
1168 }
1169 }
1170
Reid Spencer46b002c2004-07-11 17:28:43 +00001171 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001172 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001173 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001174 unsigned Typ = 0;
1175 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001176 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001177
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001178 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001179 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001180 unsigned slot = read_vbr_uint();
1181 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001182
Reid Spencer04cde2c2004-07-04 11:33:49 +00001183 // if we're reading a pre 1.3 bytecode file and the type plane
1184 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001185 if (isTypeType) {
1186 const Type* T = getType(slot);
1187 if (T == 0)
1188 error("Failed type look-up for name '" + Name + "'");
1189 ST->insert(Name, T);
1190 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001191 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001192 Value *V = 0;
1193 if (Typ == Type::LabelTyID) {
1194 if (slot < BBMap.size())
1195 V = BBMap[slot];
1196 } else {
1197 V = getValue(Typ, slot, false); // Find mapping...
1198 }
1199 if (V == 0)
1200 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001201 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001202 }
Chris Lattner00950542001-06-06 20:29:01 +00001203 }
1204 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001205 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001206 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001207}
1208
Misha Brukman8a96c532005-04-21 21:44:41 +00001209/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001210void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001211 for (unsigned i = 0; i != NumEntries; ++i) {
1212 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001213 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001214 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001215 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001216 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001217 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001218 }
1219}
1220
1221/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001222void BytecodeReader::ParseCompactionTable() {
1223
Reid Spencer46b002c2004-07-11 17:28:43 +00001224 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001225 if (Handler) Handler->handleCompactionTableBegin();
1226
Misha Brukman8a96c532005-04-21 21:44:41 +00001227 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001228 // we always write them first in the compaction table
1229 // because they can't occupy a "type plane" where the
1230 // Values reside.
1231 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001232 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001233 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001234 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001235
Reid Spencer46b002c2004-07-11 17:28:43 +00001236 // Compaction tables live in separate blocks so we have to loop
1237 // until we've read the whole thing.
1238 while (moreInBlock()) {
1239 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001240 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001241 unsigned Ty = 0;
1242 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001243
Reid Spencer46b002c2004-07-11 17:28:43 +00001244 // Decode the type from value read in. Most compaction table
1245 // planes will have one or two entries in them. If that's the
1246 // case then the length is encoded in the bottom two bits and
1247 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001248 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001249 // In this case, both low-order bits are set (value 3). This
1250 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001251 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001252 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001253 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001254 // In this case, the low-order bits specify the number of entries
1255 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001256 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001257 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001258 NumEntries &= 3;
1259 }
1260
Reid Spencer04cde2c2004-07-04 11:33:49 +00001261 // if we're reading a pre 1.3 bytecode file and the type plane
1262 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001263 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001264 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001265 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001266 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001267 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001268 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001269
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001270 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001271 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001272 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001273
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001274 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001275 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001276
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001277 // Push the implicit zero.
1278 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001279
1280 // Read in each of the entries, put them in the compaction table
1281 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001282 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001283 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001284 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001285 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001286 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001287 }
1288 }
1289 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001290 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001291 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001292}
Misha Brukman8a96c532005-04-21 21:44:41 +00001293
Reid Spencer46b002c2004-07-11 17:28:43 +00001294// Parse a single type. The typeid is read in first. If its a primitive type
1295// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001296// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001297// definition.
1298const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001299 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001300 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001301 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001302
1303 const Type *Result = 0;
1304 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1305 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001306
Reid Spencer060d25d2004-06-29 23:29:38 +00001307 switch (PrimType) {
1308 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001309 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001310
1311 unsigned NumParams = read_vbr_uint();
1312
1313 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001314 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001315 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001316
1317 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1318 if (isVarArg) Params.pop_back();
1319
1320 Result = FunctionType::get(RetType, Params, isVarArg);
1321 break;
1322 }
1323 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001324 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001325 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001326 Result = ArrayType::get(ElementType, NumElements);
1327 break;
1328 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001329 case Type::PackedTyID: {
1330 const Type *ElementType = readSanitizedType();
1331 unsigned NumElements = read_vbr_uint();
1332 Result = PackedType::get(ElementType, NumElements);
1333 break;
1334 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001335 case Type::StructTyID: {
1336 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001337 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001338 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001339 error("Invalid element type (type type) for structure!");
1340
Reid Spencer060d25d2004-06-29 23:29:38 +00001341 while (Typ) { // List is terminated by void/0 typeid
1342 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001343 if (read_typeid(Typ))
1344 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 }
1346
1347 Result = StructType::get(Elements);
1348 break;
1349 }
1350 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001351 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001352 break;
1353 }
1354
1355 case Type::OpaqueTyID: {
1356 Result = OpaqueType::get();
1357 break;
1358 }
1359
1360 default:
Reid Spencer24399722004-07-09 22:21:33 +00001361 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001362 break;
1363 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001364 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001365 return Result;
1366}
1367
Reid Spencer5b472d92004-08-21 20:49:23 +00001368// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001369// types. We know that recursive types will only reference the current slab of
1370// values in the type plane, but they can forward reference types before they
1371// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1372// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1373// this ugly problem, we pessimistically insert an opaque type for each type we
1374// are about to read. This means that forward references will resolve to
1375// something and when we reread the type later, we can replace the opaque type
1376// with a new resolved concrete type.
1377//
Reid Spencer46b002c2004-07-11 17:28:43 +00001378void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001379 assert(Tab.size() == 0 && "should not have read type constants in before!");
1380
1381 // Insert a bunch of opaque types to be resolved later...
1382 Tab.reserve(NumEntries);
1383 for (unsigned i = 0; i != NumEntries; ++i)
1384 Tab.push_back(OpaqueType::get());
1385
Misha Brukman8a96c532005-04-21 21:44:41 +00001386 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001387 Handler->handleTypeList(NumEntries);
1388
Chris Lattnereebac5f2005-10-03 21:26:53 +00001389 // If we are about to resolve types, make sure the type cache is clear.
1390 if (NumEntries)
1391 ModuleTypeIDCache.clear();
1392
Reid Spencer060d25d2004-06-29 23:29:38 +00001393 // Loop through reading all of the types. Forward types will make use of the
1394 // opaque types just inserted.
1395 //
1396 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001397 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001398 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001399 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001400 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001401
Misha Brukman8a96c532005-04-21 21:44:41 +00001402 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 // the opaque type we previously inserted with the new concrete value. This
1404 // approach helps with forward references to types. The refinement from the
1405 // abstract (opaque) type to the new type causes all uses of the abstract
1406 // type to use the concrete type (NewTy). This will also cause the opaque
1407 // type to be deleted.
1408 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1409
1410 // This should have replaced the old opaque type with the new type in the
1411 // value table... or with a preexisting type that was already in the system.
1412 // Let's just make sure it did.
1413 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1414 }
1415}
1416
Reid Spencer04cde2c2004-07-04 11:33:49 +00001417/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001418Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001419 // We must check for a ConstantExpr before switching by type because
1420 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001421 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001422 // 0 if not expr; numArgs if is expr
1423 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001424
Reid Spencer060d25d2004-06-29 23:29:38 +00001425 if (isExprNumArgs) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001426 if (!hasNoUndefValue) {
1427 // 'undef' is encoded with 'exprnumargs' == 1.
1428 if (isExprNumArgs == 1)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001429 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001430
Chris Lattner3bc5a602006-01-25 23:08:15 +00001431 // Inline asm is encoded with exprnumargs == ~0U.
1432 if (isExprNumArgs == ~0U) {
1433 std::string AsmStr = read_str();
1434 std::string ConstraintStr = read_str();
1435 unsigned Flags = read_vbr_uint();
1436
1437 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1438 const FunctionType *FTy =
1439 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1440
1441 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1442 error("Invalid constraints for inline asm");
1443 if (Flags & ~1U)
1444 error("Invalid flags for inline asm");
1445 bool HasSideEffects = Flags & 1;
1446 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
1447 }
1448
1449 --isExprNumArgs;
1450 }
1451
Reid Spencer060d25d2004-06-29 23:29:38 +00001452 // FIXME: Encoding of constant exprs could be much more compact!
1453 std::vector<Constant*> ArgVec;
1454 ArgVec.reserve(isExprNumArgs);
1455 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001456
1457 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1458 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001459
Reid Spencer060d25d2004-06-29 23:29:38 +00001460 // Read the slot number and types of each of the arguments
1461 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1462 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001463 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001464 if (read_typeid(ArgTypeSlot))
1465 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001466
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 // Get the arg value from its slot if it exists, otherwise a placeholder
1468 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1469 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001470
Reid Spencer060d25d2004-06-29 23:29:38 +00001471 // Construct a ConstantExpr of the appropriate kind
1472 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001473 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001474 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001475
Reid Spencer060d25d2004-06-29 23:29:38 +00001476 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001477 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001478 return Result;
1479 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1480 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1481
1482 if (hasRestrictedGEPTypes) {
1483 const Type *BaseTy = ArgVec[0]->getType();
1484 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1485 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1486 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1487 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1488 if (isa<StructType>(*GTI)) {
1489 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001490 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001491 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1492 }
1493 }
1494
1495 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001496 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001497 return Result;
1498 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001499 if (ArgVec.size() != 3)
1500 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001501 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001502 ArgVec[2]);
1503 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001504 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001505 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001506 if (ArgVec.size() != 2 ||
1507 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1508 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001509 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1510 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1511 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001512 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001513 if (ArgVec.size() != 3 ||
1514 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1515 error("Invalid insertelement constand expr arguments");
1516
1517 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001518 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1519 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1520 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001521 } else if (Opcode == Instruction::ShuffleVector) {
1522 if (ArgVec.size() != 3 ||
1523 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001524 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001525 Constant *Result =
1526 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1527 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1528 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001529 } else { // All other 2-operand expressions
1530 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001531 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001532 return Result;
1533 }
1534 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001535
Reid Spencer060d25d2004-06-29 23:29:38 +00001536 // Ok, not an ConstantExpr. We now know how to read the given type...
1537 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001538 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001539 switch (Ty->getTypeID()) {
1540 case Type::BoolTyID: {
1541 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001542 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001543 error("Invalid boolean value read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001544 Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001545 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001546 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001547 }
1548
1549 case Type::UByteTyID: // Unsigned integer types...
1550 case Type::UShortTyID:
1551 case Type::UIntTyID: {
1552 unsigned Val = read_vbr_uint();
Reid Spencerb83eb642006-10-20 07:07:24 +00001553 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
Reid Spencer24399722004-07-09 22:21:33 +00001554 error("Invalid unsigned byte/short/int read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001555 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001556 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001557 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001558 }
1559
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001560 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +00001561 Result = ConstantInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001562 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001563 break;
1564
Reid Spencer060d25d2004-06-29 23:29:38 +00001565 case Type::SByteTyID: // Signed integer types...
1566 case Type::ShortTyID:
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001567 case Type::IntTyID:
1568 case Type::LongTyID: {
Reid Spencer060d25d2004-06-29 23:29:38 +00001569 int64_t Val = read_vbr_int64();
Reid Spencerb83eb642006-10-20 07:07:24 +00001570 if (!ConstantInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001571 error("Invalid signed byte/short/int/long read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001572 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001573 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001574 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001575 }
1576
1577 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001578 float Val;
1579 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001580 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001581 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001582 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001583 }
1584
1585 case Type::DoubleTyID: {
1586 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001587 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001588 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001589 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001590 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001591 }
1592
Reid Spencer060d25d2004-06-29 23:29:38 +00001593 case Type::ArrayTyID: {
1594 const ArrayType *AT = cast<ArrayType>(Ty);
1595 unsigned NumElements = AT->getNumElements();
1596 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1597 std::vector<Constant*> Elements;
1598 Elements.reserve(NumElements);
1599 while (NumElements--) // Read all of the elements of the constant.
1600 Elements.push_back(getConstantValue(TypeSlot,
1601 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001602 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001603 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001604 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001605 }
1606
1607 case Type::StructTyID: {
1608 const StructType *ST = cast<StructType>(Ty);
1609
1610 std::vector<Constant *> Elements;
1611 Elements.reserve(ST->getNumElements());
1612 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1613 Elements.push_back(getConstantValue(ST->getElementType(i),
1614 read_vbr_uint()));
1615
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001616 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001617 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001618 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001619 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001620
Brian Gaeke715c90b2004-08-20 06:00:58 +00001621 case Type::PackedTyID: {
1622 const PackedType *PT = cast<PackedType>(Ty);
1623 unsigned NumElements = PT->getNumElements();
1624 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1625 std::vector<Constant*> Elements;
1626 Elements.reserve(NumElements);
1627 while (NumElements--) // Read all of the elements of the constant.
1628 Elements.push_back(getConstantValue(TypeSlot,
1629 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001630 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001631 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001632 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001633 }
1634
Chris Lattner638c3812004-11-19 16:24:05 +00001635 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001636 const PointerType *PT = cast<PointerType>(Ty);
1637 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001638
Reid Spencer060d25d2004-06-29 23:29:38 +00001639 // Check to see if we have already read this global variable...
1640 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001641 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001642 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1643 if (!GV) error("GlobalValue not in ValueTable!");
1644 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1645 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001646 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001647 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001648 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001649 }
1650
1651 default:
Reid Spencer24399722004-07-09 22:21:33 +00001652 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001653 Ty->getDescription());
1654 break;
1655 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001656
1657 // Check that we didn't read a null constant if they are implicit for this
1658 // type plane. Do not do this check for constantexprs, as they may be folded
1659 // to a null value in a way that isn't predicted when a .bc file is initially
1660 // produced.
1661 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1662 !hasImplicitNull(TypeID) &&
1663 "Cannot read null values from bytecode!");
1664 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001665}
1666
Misha Brukman8a96c532005-04-21 21:44:41 +00001667/// Resolve references for constants. This function resolves the forward
1668/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001669/// replaceAllUsesWith method of Value class to substitute the placeholder
1670/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001671void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1672 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001673 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001674 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001675 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001676
Chris Lattner29b789b2003-11-19 17:27:18 +00001677 Value *PH = I->second; // Get the placeholder...
1678 PH->replaceAllUsesWith(NewV);
1679 delete PH; // Delete the old placeholder
1680 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001681}
1682
Reid Spencer04cde2c2004-07-04 11:33:49 +00001683/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001684void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1685 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001686 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001687 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001688 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001689 const Type *Ty = getType(Typ);
1690 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001691 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001692
Reid Spencer060d25d2004-06-29 23:29:38 +00001693 const ArrayType *ATy = cast<ArrayType>(Ty);
1694 if (ATy->getElementType() != Type::SByteTy &&
1695 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001696 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001697
Reid Spencer060d25d2004-06-29 23:29:38 +00001698 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001699 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001700 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001701
Reid Spencer060d25d2004-06-29 23:29:38 +00001702 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001703 const Type* ElemType = ATy->getElementType();
1704 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1705 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001706
Reid Spencer060d25d2004-06-29 23:29:38 +00001707 // Create the constant, inserting it as needed.
1708 Constant *C = ConstantArray::get(ATy, Elements);
1709 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001710 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001711 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001712 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001713}
1714
Reid Spencer04cde2c2004-07-04 11:33:49 +00001715/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001716void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001717 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001718 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001719 if (Handler) Handler->handleGlobalConstantsBegin();
1720
1721 /// In LLVM 1.3 Type does not derive from Value so the types
1722 /// do not occupy a plane. Consequently, we read the types
1723 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001724 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001725 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001726 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001727 }
1728
Reid Spencer46b002c2004-07-11 17:28:43 +00001729 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001730 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001731 unsigned Typ = 0;
1732 bool isTypeType = read_typeid(Typ);
1733
1734 /// In LLVM 1.2 and before, Types were written to the
1735 /// bytecode file in the "Type Type" plane (#12).
1736 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001737 if (isTypeType) {
1738 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001739 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001740 /// Use of Type::VoidTyID is a misnomer. It actually means
1741 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001742 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1743 ParseStringConstants(NumEntries, Tab);
1744 } else {
1745 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001746 Value *V = ParseConstantPoolValue(Typ);
1747 assert(V && "ParseConstantPoolValue returned NULL!");
1748 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001749
Reid Spencer060d25d2004-06-29 23:29:38 +00001750 // If we are reading a function constant table, make sure that we adjust
1751 // the slot number to be the real global constant number.
1752 //
1753 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1754 ModuleValues[Typ])
1755 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001756 if (Constant *C = dyn_cast<Constant>(V))
1757 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001758 }
1759 }
1760 }
Chris Lattner02dce162004-12-04 05:28:27 +00001761
1762 // After we have finished parsing the constant pool, we had better not have
1763 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001764 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001765 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001766 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001767 error(utostr(ConstantFwdRefs.size()) +
1768 " unresolved constant reference exist. First one is '" +
1769 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001770 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001771 }
Chris Lattner02dce162004-12-04 05:28:27 +00001772
Reid Spencer060d25d2004-06-29 23:29:38 +00001773 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001774 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001775}
Chris Lattner00950542001-06-06 20:29:01 +00001776
Reid Spencer04cde2c2004-07-04 11:33:49 +00001777/// Parse the contents of a function. Note that this function can be
1778/// called lazily by materializeFunction
1779/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001780void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001781
1782 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001783 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1784
Reid Spencer060d25d2004-06-29 23:29:38 +00001785 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001786 switch (LinkageType) {
1787 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1788 case 1: Linkage = GlobalValue::WeakLinkage; break;
1789 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1790 case 3: Linkage = GlobalValue::InternalLinkage; break;
1791 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001792 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1793 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1794 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001795 default:
Reid Spencer24399722004-07-09 22:21:33 +00001796 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001797 Linkage = GlobalValue::InternalLinkage;
1798 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001799 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001800
Reid Spencer46b002c2004-07-11 17:28:43 +00001801 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001802 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001803
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001804 // Keep track of how many basic blocks we have read in...
1805 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001806 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001807
Reid Spencer060d25d2004-06-29 23:29:38 +00001808 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001809 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001810 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001811 BufPtr OldAt = At;
1812 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001813
1814 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001815 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001816 if (!InsertedArguments) {
1817 // Insert arguments into the value table before we parse the first basic
1818 // block in the function, but after we potentially read in the
1819 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001820 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001821 InsertedArguments = true;
1822 }
1823
Reid Spencer04cde2c2004-07-04 11:33:49 +00001824 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001825 break;
1826
Reid Spencerad89bd62004-07-25 18:07:36 +00001827 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001828 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001829 break;
1830
Chris Lattner00950542001-06-06 20:29:01 +00001831 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001832 if (!InsertedArguments) {
1833 // Insert arguments into the value table before we parse the first basic
1834 // block in the function, but after we potentially read in the
1835 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001836 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001837 InsertedArguments = true;
1838 }
1839
Reid Spencer060d25d2004-06-29 23:29:38 +00001840 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001841 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001842 break;
1843 }
1844
Reid Spencerad89bd62004-07-25 18:07:36 +00001845 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001846 // Insert arguments into the value table before we parse the instruction
1847 // list for the function, but after we potentially read in the compaction
1848 // table.
1849 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001850 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001851 InsertedArguments = true;
1852 }
1853
Misha Brukman8a96c532005-04-21 21:44:41 +00001854 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001855 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001856 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001857 break;
1858 }
1859
Reid Spencerad89bd62004-07-25 18:07:36 +00001860 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001861 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001862 break;
1863
1864 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001865 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001866 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001867 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001868 break;
1869 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001870 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001871
Misha Brukman12c29d12003-09-22 23:38:23 +00001872 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001873 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001874 }
1875
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001876 // Make sure there were no references to non-existant basic blocks.
1877 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001878 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001879
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001880 ParsedBasicBlocks.clear();
1881
Chris Lattner97330cf2003-10-09 23:10:14 +00001882 // Resolve forward references. Replace any uses of a forward reference value
1883 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001884 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001885 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1886 I = ForwardReferences.begin();
1887 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001888 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001889 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001890 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001891 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001892 }
Chris Lattner00950542001-06-06 20:29:01 +00001893
Reid Spencere2a5fb02006-01-27 11:49:27 +00001894 // If upgraded intrinsic functions were detected during reading of the
1895 // module information, then we need to look for instructions that need to
1896 // be upgraded. This can't be done while the instructions are read in because
1897 // additional instructions inserted mess up the slot numbering.
1898 if (!upgradedFunctions.empty()) {
1899 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
1900 for (BasicBlock::iterator II = BI->begin(), IE = BI->end();
Jim Laskeyf4321a32006-03-13 13:07:37 +00001901 II != IE;)
1902 if (CallInst* CI = dyn_cast<CallInst>(II++)) {
Reid Spencere2a5fb02006-01-27 11:49:27 +00001903 std::map<Function*,Function*>::iterator FI =
1904 upgradedFunctions.find(CI->getCalledFunction());
Chris Lattnerbad08002006-03-02 23:59:12 +00001905 if (FI != upgradedFunctions.end())
1906 UpgradeIntrinsicCall(CI, FI->second);
Reid Spencere2a5fb02006-01-27 11:49:27 +00001907 }
1908 }
1909
Misha Brukman12c29d12003-09-22 23:38:23 +00001910 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001911 FunctionTypes.clear();
1912 CompactionTypes.clear();
1913 CompactionValues.clear();
1914 freeTable(FunctionValues);
1915
Reid Spencer04cde2c2004-07-04 11:33:49 +00001916 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001917}
1918
Reid Spencer04cde2c2004-07-04 11:33:49 +00001919/// This function parses LLVM functions lazily. It obtains the type of the
1920/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001921/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001922/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001923void BytecodeReader::ParseFunctionLazily() {
1924 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001925 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001926
Reid Spencer060d25d2004-06-29 23:29:38 +00001927 Function *Func = FunctionSignatureList.back();
1928 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001929
Reid Spencer060d25d2004-06-29 23:29:38 +00001930 // Save the information for future reading of the function
1931 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001932
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001933 // This function has a body but it's not loaded so it appears `External'.
1934 // Mark it as a `Ghost' instead to notify the users that it has a body.
1935 Func->setLinkage(GlobalValue::GhostLinkage);
1936
Reid Spencer060d25d2004-06-29 23:29:38 +00001937 // Pretend we've `parsed' this function
1938 At = BlockEnd;
1939}
Chris Lattner89e02532004-01-18 21:08:15 +00001940
Misha Brukman8a96c532005-04-21 21:44:41 +00001941/// The ParserFunction method lazily parses one function. Use this method to
1942/// casue the parser to parse a specific function in the module. Note that
1943/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001944/// ParseAllFunctionBodies.
1945/// @see ParseAllFunctionBodies
1946/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001947bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1948
1949 if (setjmp(context))
1950 return true;
1951
Reid Spencer060d25d2004-06-29 23:29:38 +00001952 // Find {start, end} pointers and slot in the map. If not there, we're done.
1953 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001954
Reid Spencer060d25d2004-06-29 23:29:38 +00001955 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001956 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001957 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001958 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001959 }
1960
Reid Spencer060d25d2004-06-29 23:29:38 +00001961 BlockStart = At = Fi->second.Buf;
1962 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001963 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001964
1965 LazyFunctionLoadMap.erase(Fi);
1966
Reid Spencer46b002c2004-07-11 17:28:43 +00001967 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001968 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001969}
1970
Reid Spencer04cde2c2004-07-04 11:33:49 +00001971/// The ParseAllFunctionBodies method parses through all the previously
1972/// unparsed functions in the bytecode file. If you want to completely parse
1973/// a bytecode file, this method should be called after Parsebytecode because
1974/// Parsebytecode only records the locations in the bytecode file of where
1975/// the function definitions are located. This function uses that information
1976/// to materialize the functions.
1977/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001978bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
1979 if (setjmp(context))
1980 return true;
1981
Reid Spencer060d25d2004-06-29 23:29:38 +00001982 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1983 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001984
Reid Spencer46b002c2004-07-11 17:28:43 +00001985 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001986 Function* Func = Fi->first;
1987 BlockStart = At = Fi->second.Buf;
1988 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001989 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001990 ++Fi;
1991 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001992 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001993 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001994}
Chris Lattner89e02532004-01-18 21:08:15 +00001995
Reid Spencer04cde2c2004-07-04 11:33:49 +00001996/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001997void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001998 // Read the number of types
1999 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00002000
2001 // Ignore the type plane identifier for types if the bc file is pre 1.3
2002 if (hasTypeDerivedFromValue)
2003 read_vbr_uint();
2004
Reid Spencer46b002c2004-07-11 17:28:43 +00002005 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00002006}
2007
Reid Spencer04cde2c2004-07-04 11:33:49 +00002008/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00002009void BytecodeReader::ParseModuleGlobalInfo() {
2010
Reid Spencer04cde2c2004-07-04 11:33:49 +00002011 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00002012
Chris Lattner404cddf2005-11-12 01:33:40 +00002013 // SectionID - If a global has an explicit section specified, this map
2014 // remembers the ID until we can translate it into a string.
2015 std::map<GlobalValue*, unsigned> SectionID;
2016
Chris Lattner70cc3392001-09-10 07:58:01 +00002017 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002018 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002019 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00002020 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
2021 // Linkage, bit4+ = slot#
2022 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00002023 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00002024 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00002025 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00002026 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002027 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002028 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00002029 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002030
2031 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
2032 if (LinkageID == 3 && !hasInitializer) {
2033 unsigned ExtWord = read_vbr_uint();
2034 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
2035 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
2036 hasInitializer = ExtWord & 1;
2037 LinkageID = (ExtWord >> 1) & 7;
2038 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00002039
2040 if (ExtWord & (1 << 9)) // Has a section ID.
2041 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002042 }
Chris Lattnere3869c82003-04-16 21:16:05 +00002043
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002044 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002045 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00002046 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2047 case 1: Linkage = GlobalValue::WeakLinkage; break;
2048 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2049 case 3: Linkage = GlobalValue::InternalLinkage; break;
2050 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002051 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
2052 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
2053 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00002054 default:
Reid Spencer24399722004-07-09 22:21:33 +00002055 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00002056 Linkage = GlobalValue::InternalLinkage;
2057 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002058 }
2059
2060 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00002061 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00002062 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00002063
Chris Lattnere73bd452005-11-06 07:43:39 +00002064 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002065 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00002066
Chris Lattner52e20b02003-03-19 20:54:26 +00002067 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00002068
Chris Lattner70cc3392001-09-10 07:58:01 +00002069 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00002070 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00002071 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002072 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00002073 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00002074
Chris Lattner404cddf2005-11-12 01:33:40 +00002075 if (GlobalSectionID != 0)
2076 SectionID[GV] = GlobalSectionID;
2077
Reid Spencer060d25d2004-06-29 23:29:38 +00002078 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00002079 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002080 initSlot = read_vbr_uint();
2081 GlobalInits.push_back(std::make_pair(GV, initSlot));
2082 }
2083
2084 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00002085 if (Handler)
2086 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002087
2088 // Get next item
2089 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002090 }
2091
Chris Lattner52e20b02003-03-19 20:54:26 +00002092 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002093 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00002094
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002095 if (hasNoFlagsForFunctions)
2096 FnSignature = (FnSignature << 5) + 1;
2097
2098 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00002099 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
2100 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00002101 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00002102 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002103 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00002104 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00002105 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00002106
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002107 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00002108 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00002109 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00002110
Chris Lattner18549c22004-11-15 21:43:03 +00002111 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00002112 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002113 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00002114
Chris Lattnere73bd452005-11-06 07:43:39 +00002115 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002116
2117 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00002118 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00002119
Chris Lattner97fbc502004-11-15 22:38:52 +00002120 // Save this for later so we know type of lazily instantiated functions.
2121 // Note that known-external functions do not have FunctionInfo blocks, so we
2122 // do not add them to the FunctionSignatureList.
2123 if ((Flags & (1 << 4)) == 0)
2124 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00002125
Chris Lattnere73bd452005-11-06 07:43:39 +00002126 // Get the calling convention from the low bits.
2127 unsigned CC = Flags & 15;
2128 unsigned Alignment = 0;
2129 if (FnSignature & (1 << 31)) { // Has extension word?
2130 unsigned ExtWord = read_vbr_uint();
2131 Alignment = (1 << (ExtWord & 31)) >> 1;
2132 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00002133
2134 if (ExtWord & (1 << 10)) // Has a section ID.
2135 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002136
2137 // Parse external declaration linkage
2138 switch ((ExtWord >> 11) & 3) {
2139 case 0: break;
2140 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
2141 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
2142 default: assert(0 && "Unsupported external linkage");
2143 }
Chris Lattnere73bd452005-11-06 07:43:39 +00002144 }
2145
Chris Lattner54b369e2005-11-06 07:46:13 +00002146 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00002147 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00002148
Reid Spencer04cde2c2004-07-04 11:33:49 +00002149 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002150
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002151 // Get the next function signature.
2152 FnSignature = read_vbr_uint();
2153 if (hasNoFlagsForFunctions)
2154 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00002155 }
2156
Misha Brukman8a96c532005-04-21 21:44:41 +00002157 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002158 // remove elements efficiently from the back of the vector.
2159 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002160
Chris Lattner404cddf2005-11-12 01:33:40 +00002161 /// SectionNames - This contains the list of section names encoded in the
2162 /// moduleinfoblock. Functions and globals with an explicit section index
2163 /// into this to get their section name.
2164 std::vector<std::string> SectionNames;
2165
2166 if (hasInconsistentModuleGlobalInfo) {
2167 align32();
2168 } else if (!hasNoDependentLibraries) {
2169 // If this bytecode format has dependent library information in it, read in
2170 // the number of dependent library items that follow.
Reid Spencerad89bd62004-07-25 18:07:36 +00002171 unsigned num_dep_libs = read_vbr_uint();
2172 std::string dep_lib;
Chris Lattner404cddf2005-11-12 01:33:40 +00002173 while (num_dep_libs--) {
Reid Spencerad89bd62004-07-25 18:07:36 +00002174 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00002175 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002176 if (Handler)
2177 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002178 }
2179
Chris Lattner404cddf2005-11-12 01:33:40 +00002180 // Read target triple and place into the module.
Reid Spencerad89bd62004-07-25 18:07:36 +00002181 std::string triple = read_str();
2182 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00002183 if (Handler)
2184 Handler->handleTargetTriple(triple);
Chris Lattner404cddf2005-11-12 01:33:40 +00002185
Chris Lattner7e6db762006-01-23 23:43:17 +00002186 if (!hasAlignment && At != BlockEnd) {
Chris Lattner404cddf2005-11-12 01:33:40 +00002187 // If the file has section info in it, read the section names now.
2188 unsigned NumSections = read_vbr_uint();
2189 while (NumSections--)
2190 SectionNames.push_back(read_str());
2191 }
Chris Lattner7e6db762006-01-23 23:43:17 +00002192
2193 // If the file has module-level inline asm, read it now.
2194 if (!hasAlignment && At != BlockEnd)
Chris Lattner66316012006-01-24 04:14:29 +00002195 TheModule->setModuleInlineAsm(read_str());
Reid Spencerad89bd62004-07-25 18:07:36 +00002196 }
2197
Chris Lattner404cddf2005-11-12 01:33:40 +00002198 // If any globals are in specified sections, assign them now.
2199 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2200 SectionID.end(); I != E; ++I)
2201 if (I->second) {
2202 if (I->second > SectionID.size())
2203 error("SectionID out of range for global!");
2204 I->first->setSection(SectionNames[I->second-1]);
2205 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002206
Chris Lattner00950542001-06-06 20:29:01 +00002207 // This is for future proofing... in the future extra fields may be added that
2208 // we don't understand, so we transparently ignore them.
2209 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002210 At = BlockEnd;
2211
Reid Spencer04cde2c2004-07-04 11:33:49 +00002212 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002213}
2214
Reid Spencer04cde2c2004-07-04 11:33:49 +00002215/// Parse the version information and decode it by setting flags on the
2216/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002217void BytecodeReader::ParseVersionInfo() {
2218 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002219
2220 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002221 Module::Endianness Endianness;
2222 Module::PointerSize PointerSize;
2223 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2224 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2225
2226 bool hasNoEndianness = Version & 4;
2227 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002228
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002229 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002230
2231 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002232 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002233 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002234 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002235 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002236 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002237 has32BitTypes = false;
2238 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002239 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002240 hasNoUndefValue = false;
2241 hasNoFlagsForFunctions = false;
2242 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002243
2244 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002245 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002246 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002247 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002248 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002249
Chris Lattner80b97342004-01-17 23:25:43 +00002250 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002251
2252 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002253 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002254
2255 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2256 // included the size for the alignment at the end, where the rest of the
2257 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002258
2259 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2260 // structures and longs for sequential types.
2261 hasRestrictedGEPTypes = true;
2262
Reid Spencer04cde2c2004-07-04 11:33:49 +00002263 // LLVM 1.2 and before had the Type class derive from Value class. This
2264 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002265 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002266 // type planes for Values.
2267 hasTypeDerivedFromValue = true;
2268
Chris Lattner5fa428f2004-04-05 01:27:26 +00002269 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002270
Reid Spencer5b472d92004-08-21 20:49:23 +00002271 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002272
Reid Spencer5b472d92004-08-21 20:49:23 +00002273 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002274 // especially for small files where the 8 bytes per block is a large
2275 // fraction of the total block size. In LLVM 1.3, the block type and length
2276 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2277 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002278 hasLongBlockHeaders = true;
2279
Reid Spencer5b472d92004-08-21 20:49:23 +00002280 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002281 // this has been reduced to vbr_uint24. It shouldn't make much difference
2282 // since we haven't run into a module with > 24 million types, but for
2283 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2284 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002285 has32BitTypes = true;
2286
Misha Brukman8a96c532005-04-21 21:44:41 +00002287 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002288 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2289 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002290 hasNoDependentLibraries = true;
2291
2292 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002293
2294 case 3: // LLVM 1.3 (Released)
2295 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002296 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002297 // of GEP references to a constant array), this can increase the file size
2298 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002299 hasAlignment = true;
2300
2301 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002302
Reid Spencer5b472d92004-08-21 20:49:23 +00002303 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002304 // In version 4, we did not support the 'undef' constant.
2305 hasNoUndefValue = true;
2306
2307 // In version 4 and above, we did not include space for flags for functions
2308 // in the module info block.
2309 hasNoFlagsForFunctions = true;
2310
2311 // In version 4 and above, we did not include the 'unreachable' instruction
2312 // in the opcode numbering in the bytecode file.
2313 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002314 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002315
2316 // FALL THROUGH
2317
Chris Lattnerdee199f2005-05-06 22:34:01 +00002318 case 5: // 1.4 (Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002319 break;
2320
Chris Lattner036b8aa2003-03-06 17:55:45 +00002321 default:
Reid Spencer24399722004-07-09 22:21:33 +00002322 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002323 }
2324
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002325 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2326 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002327
Brian Gaekefe2102b2004-07-14 20:33:13 +00002328 TheModule->setEndianness(Endianness);
2329 TheModule->setPointerSize(PointerSize);
2330
Reid Spencer46b002c2004-07-11 17:28:43 +00002331 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002332}
2333
Reid Spencer04cde2c2004-07-04 11:33:49 +00002334/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002335void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002336 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002337
Reid Spencer060d25d2004-06-29 23:29:38 +00002338 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002339
2340 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002341 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002342 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002343
Reid Spencer060d25d2004-06-29 23:29:38 +00002344 bool SeenModuleGlobalInfo = false;
2345 bool SeenGlobalTypePlane = false;
2346 BufPtr MyEnd = BlockEnd;
2347 while (At < MyEnd) {
2348 BufPtr OldAt = At;
2349 read_block(Type, Size);
2350
Chris Lattner00950542001-06-06 20:29:01 +00002351 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002352
Reid Spencerad89bd62004-07-25 18:07:36 +00002353 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002354 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002355 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002356
Reid Spencer5b472d92004-08-21 20:49:23 +00002357 if (Size > 0)
2358 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002359 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002360 break;
2361
Misha Brukman8a96c532005-04-21 21:44:41 +00002362 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002363 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002364 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002365 ParseModuleGlobalInfo();
2366 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002367 break;
2368
Reid Spencerad89bd62004-07-25 18:07:36 +00002369 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002370 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002371 break;
2372
Reid Spencerad89bd62004-07-25 18:07:36 +00002373 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002374 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002375 break;
Chris Lattner00950542001-06-06 20:29:01 +00002376
Reid Spencerad89bd62004-07-25 18:07:36 +00002377 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002378 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002379 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002380
Chris Lattner00950542001-06-06 20:29:01 +00002381 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002382 At += Size;
2383 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002384 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002385 }
Chris Lattner00950542001-06-06 20:29:01 +00002386 break;
2387 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002388 BlockEnd = MyEnd;
2389 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002390 }
2391
Chris Lattner52e20b02003-03-19 20:54:26 +00002392 // After the module constant pool has been read, we can safely initialize
2393 // global variables...
2394 while (!GlobalInits.empty()) {
2395 GlobalVariable *GV = GlobalInits.back().first;
2396 unsigned Slot = GlobalInits.back().second;
2397 GlobalInits.pop_back();
2398
2399 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002400 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002401
2402 const llvm::PointerType* GVType = GV->getType();
2403 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002404 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002405 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002406 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002407 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002408 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002409 } else
Reid Spencer24399722004-07-09 22:21:33 +00002410 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002411 }
2412
Chris Lattneraba5ff52005-05-05 20:57:00 +00002413 if (!ConstantFwdRefs.empty())
2414 error("Use of undefined constants in a module");
2415
Reid Spencer060d25d2004-06-29 23:29:38 +00002416 /// Make sure we pulled them all out. If we didn't then there's a declaration
2417 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002418 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002419 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002420}
2421
Reid Spencer04cde2c2004-07-04 11:33:49 +00002422/// This function completely parses a bytecode buffer given by the \p Buf
2423/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002424bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002425 const std::string &ModuleID,
2426 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002427
Reid Spencer233fe722006-08-22 16:09:19 +00002428 /// We handle errors by
2429 if (setjmp(context)) {
2430 // Cleanup after error
2431 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002432 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002433 delete TheModule;
2434 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002435 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002436 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002437 decompressedBlock = 0;
2438 }
Reid Spencer233fe722006-08-22 16:09:19 +00002439 // Set caller's error message, if requested
2440 if (ErrMsg)
2441 *ErrMsg = ErrorMsg;
2442 // Indicate an error occurred
2443 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002444 }
Reid Spencer233fe722006-08-22 16:09:19 +00002445
2446 RevisionNum = 0;
2447 At = MemStart = BlockStart = Buf;
2448 MemEnd = BlockEnd = Buf + Length;
2449
2450 // Create the module
2451 TheModule = new Module(ModuleID);
2452
2453 if (Handler) Handler->handleStart(TheModule, Length);
2454
2455 // Read the four bytes of the signature.
2456 unsigned Sig = read_uint();
2457
2458 // If this is a compressed file
2459 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2460
2461 // Invoke the decompression of the bytecode. Note that we have to skip the
2462 // file's magic number which is not part of the compressed block. Hence,
2463 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2464 // member for retention until BytecodeReader is destructed.
2465 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2466 (char*)Buf+4,Length-4,decompressedBlock);
2467
2468 // We must adjust the buffer pointers used by the bytecode reader to point
2469 // into the new decompressed block. After decompression, the
2470 // decompressedBlock will point to a contiguous memory area that has
2471 // the decompressed data.
2472 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2473 MemEnd = BlockEnd = Buf + decompressedLength;
2474
2475 // else if this isn't a regular (uncompressed) bytecode file, then its
2476 // and error, generate that now.
2477 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2478 error("Invalid bytecode signature: " + utohexstr(Sig));
2479 }
2480
2481 // Tell the handler we're starting a module
2482 if (Handler) Handler->handleModuleBegin(ModuleID);
2483
2484 // Get the module block and size and verify. This is handled specially
2485 // because the module block/size is always written in long format. Other
2486 // blocks are written in short format so the read_block method is used.
2487 unsigned Type, Size;
2488 Type = read_uint();
2489 Size = read_uint();
2490 if (Type != BytecodeFormat::ModuleBlockID) {
2491 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2492 + utostr(Size));
2493 }
2494
2495 // It looks like the darwin ranlib program is broken, and adds trailing
2496 // garbage to the end of some bytecode files. This hack allows the bc
2497 // reader to ignore trailing garbage on bytecode files.
2498 if (At + Size < MemEnd)
2499 MemEnd = BlockEnd = At+Size;
2500
2501 if (At + Size != MemEnd)
2502 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2503 + ", Size:" + utostr(Size));
2504
2505 // Parse the module contents
2506 this->ParseModule();
2507
2508 // Check for missing functions
2509 if (hasFunctions())
2510 error("Function expected, but bytecode stream ended!");
2511
2512 // Look for intrinsic functions to upgrade, upgrade them, and save the
2513 // mapping from old function to new for use later when instructions are
2514 // converted.
2515 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2516 FI != FE; ++FI)
2517 if (Function* newF = UpgradeIntrinsicFunction(FI)) {
2518 upgradedFunctions.insert(std::make_pair(FI, newF));
2519 FI->setName("");
2520 }
2521
2522 // Tell the handler we're done with the module
2523 if (Handler)
2524 Handler->handleModuleEnd(ModuleID);
2525
2526 // Tell the handler we're finished the parse
2527 if (Handler) Handler->handleFinish();
2528
2529 return false;
2530
Chris Lattner00950542001-06-06 20:29:01 +00002531}
Reid Spencer060d25d2004-06-29 23:29:38 +00002532
2533//===----------------------------------------------------------------------===//
2534//=== Default Implementations of Handler Methods
2535//===----------------------------------------------------------------------===//
2536
2537BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002538