blob: f56c59ad18f36aea7b3c5ae33dfd747b09b415c6 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000024#include "llvm/Instructions.h"
25#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000027#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000029#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000031#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000032#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Reid Spencer46b002c2004-07-11 17:28:43 +000035namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000036 /// @brief A class for maintaining the slot number definition
37 /// as a placeholder for the actual definition for forward constants defs.
38 class ConstantPlaceHolder : public ConstantExpr {
39 ConstantPlaceHolder(); // DO NOT IMPLEMENT
40 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
41 public:
Chris Lattner61323322005-01-31 01:11:13 +000042 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000043 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000044 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
45 Op(UndefValue::get(Type::IntTy), this) {
46 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000047 };
Reid Spencer46b002c2004-07-11 17:28:43 +000048}
Reid Spencer060d25d2004-06-29 23:29:38 +000049
Reid Spencer24399722004-07-09 22:21:33 +000050// Provide some details on error
51inline void BytecodeReader::error(std::string err) {
52 err += " (Vers=" ;
53 err += itostr(RevisionNum) ;
54 err += ", Pos=" ;
55 err += itostr(At-MemStart);
56 err += ")";
57 throw err;
58}
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;
80 At = (const unsigned char *)((unsigned long)(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.
165 union {
166 float f;
167 uint32_t i;
168 } FloatUnion;
169 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
170 At+=sizeof(uint32_t);
171 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000172}
173
174/// Read a double value in little-endian order
175inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000176 /// FIXME: This isn't optimal, it has size problems on some platforms
177 /// where FP is not IEEE.
178 union {
179 double d;
180 uint64_t i;
181 } DoubleUnion;
Misha Brukman8a96c532005-04-21 21:44:41 +0000182 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
Chris Lattner1d785162004-07-25 23:15:44 +0000183 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Misha Brukman8a96c532005-04-21 21:44:41 +0000184 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
Reid Spencerada16182004-07-25 21:36:26 +0000185 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
186 At+=sizeof(uint64_t);
187 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000188}
189
Reid Spencer04cde2c2004-07-04 11:33:49 +0000190/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000191inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000192 if ( hasLongBlockHeaders ) {
193 Type = read_uint();
194 Size = read_uint();
195 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000196 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000197 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000198 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000199 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000200 Type = BytecodeFormat::ModuleBlockID; break;
201 case BytecodeFormat::Function:
202 Type = BytecodeFormat::FunctionBlockID; break;
203 case BytecodeFormat::ConstantPool:
204 Type = BytecodeFormat::ConstantPoolBlockID; break;
205 case BytecodeFormat::SymbolTable:
206 Type = BytecodeFormat::SymbolTableBlockID; break;
207 case BytecodeFormat::ModuleGlobalInfo:
208 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
209 case BytecodeFormat::GlobalTypePlane:
210 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
211 case BytecodeFormat::InstructionList:
212 Type = BytecodeFormat::InstructionListBlockID; break;
213 case BytecodeFormat::CompactionTable:
214 Type = BytecodeFormat::CompactionTableBlockID; break;
215 case BytecodeFormat::BasicBlock:
216 /// This block type isn't used after version 1.1. However, we have to
217 /// still allow the value in case this is an old bc format file.
218 /// We just let its value creep thru.
219 break;
220 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000221 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000222 break;
223 }
224 } else {
225 Size = read_uint();
226 Type = Size & 0x1F; // mask low order five bits
227 Size >>= 5; // get rid of five low order bits, leaving high 27
228 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000229 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000230 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000231 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000232 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000233 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000234}
235
236
237/// In LLVM 1.2 and before, Types were derived from Value and so they were
238/// written as part of the type planes along with any other Value. In LLVM
239/// 1.3 this changed so that Type does not derive from Value. Consequently,
240/// the BytecodeReader's containers for Values can't contain Types because
241/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000242/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
243/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000244/// the types are always read/written first and then the Values. Furthermore
245/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
246/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
247/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
248/// For LLVM 1.2 and before, this function will decrement the type id by
249/// one to account for the missing Type::TypeTyID enumerator if the value is
250/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
251/// function returns true, otherwise false. This helps detect situations
252/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000253/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000254inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
255 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
256 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000257 TypeId = Type::VoidTyID; // sanitize it
258 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000259 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000260 --TypeId; // shift all planes down because type type plane is missing
261 }
262 return false;
263}
264
265/// Reads a vbr uint to read in a type id and does the necessary
266/// conversion on it by calling sanitizeTypeId.
267/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
268/// @see sanitizeTypeId
269inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
270 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000271 if ( !has32BitTypes )
272 if ( TypeId == 0x00FFFFFF )
273 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000274 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000275}
276
277//===----------------------------------------------------------------------===//
278// IR Lookup Methods
279//===----------------------------------------------------------------------===//
280
Reid Spencer04cde2c2004-07-04 11:33:49 +0000281/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000282inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000283 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000284 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000285 return TyID >= Type::FirstDerivedTyID;
286}
287
Reid Spencer04cde2c2004-07-04 11:33:49 +0000288/// Obtain a type given a typeid and account for things like compaction tables,
289/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000290const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000291 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000292 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000293 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000294
295 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000296 ID -= Type::FirstDerivedTyID;
297
Reid Spencer060d25d2004-06-29 23:29:38 +0000298 if (!CompactionTypes.empty()) {
299 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000300 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000301 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000302 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000303
304 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000305 if (ID < ModuleTypes.size())
306 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000307
Reid Spencer46b002c2004-07-11 17:28:43 +0000308 // Nope, is it a function-level type?
309 ID -= ModuleTypes.size();
310 if (ID < FunctionTypes.size())
311 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000312
Reid Spencer46b002c2004-07-11 17:28:43 +0000313 error("Illegal type reference!");
314 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000315}
316
Reid Spencer04cde2c2004-07-04 11:33:49 +0000317/// Get a sanitized type id. This just makes sure that the \p ID
318/// is both sanitized and not the "type type" of pre-1.3 bytecode.
319/// @see sanitizeTypeId
320inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000321 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000322 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000323 return getType(ID);
324}
325
326/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000327/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000328/// then calls getType to return the type value.
329inline const Type* BytecodeReader::readSanitizedType() {
330 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000331 if (read_typeid(ID))
332 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000333 return getType(ID);
334}
335
336/// Get the slot number associated with a type accounting for primitive
337/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000338unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
339 if (Ty->isPrimitiveType())
340 return Ty->getTypeID();
341
342 // Scan the compaction table for the type if needed.
343 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000344 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
345 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000346 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000347
Chris Lattner45b5dd22004-08-03 23:41:28 +0000348 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000349 }
350
351 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000352 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
353 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000354
355 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000356 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000357 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000358
359 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000360 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000361 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000362 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000363 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000364}
365
Reid Spencer04cde2c2004-07-04 11:33:49 +0000366/// This is just like getType, but when a compaction table is in use, it is
367/// ignored. It also ignores function level types.
368/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000369const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
370 if (Slot < Type::FirstDerivedTyID) {
371 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000372 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000373 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000374 return Ty;
375 }
376 Slot -= Type::FirstDerivedTyID;
377 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000378 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000379 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000380}
381
Reid Spencer04cde2c2004-07-04 11:33:49 +0000382/// This is just like getTypeSlot, but when a compaction table is in use, it
383/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000384unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
385 if (Ty->isPrimitiveType())
386 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000387 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000388 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000389 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000390 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000391 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
392}
393
Misha Brukman8a96c532005-04-21 21:44:41 +0000394/// Retrieve a value of a given type and slot number, possibly creating
395/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000396Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000397 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000398 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000399
Chris Lattner89e02532004-01-18 21:08:15 +0000400 // If there is a compaction table active, it defines the low-level numbers.
401 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000402 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
403 if (Num < CompactionValues[type].size())
404 return CompactionValues[type][Num];
405 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000406 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000407 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000408 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000409
Chris Lattner45b5dd22004-08-03 23:41:28 +0000410 // If the type plane was compactified, figure out the global type ID by
411 // adding the derived type ids and the distance.
412 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
413 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000414
Reid Spencer060d25d2004-06-29 23:29:38 +0000415 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000416 const Type *Ty = getType(type);
417 if (!isa<OpaqueType>(Ty)) {
418 if (Num == 0)
419 return Constant::getNullValue(Ty);
420 --Num;
421 }
Chris Lattner89e02532004-01-18 21:08:15 +0000422 }
423
Chris Lattner52f86d62004-01-20 00:54:06 +0000424 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
425 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000426 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000427 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000428 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000429 }
430
Misha Brukman8a96c532005-04-21 21:44:41 +0000431 if (FunctionValues.size() > type &&
432 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000433 Num < FunctionValues[type]->size())
434 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000435
Chris Lattner74734132002-08-17 22:01:27 +0000436 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000437
Reid Spencer551ccae2004-09-01 22:55:40 +0000438 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000439 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000440 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000441 if (I != ForwardReferences.end() && I->first == KeyValue)
442 return I->second; // We have already created this placeholder
443
Reid Spencer551ccae2004-09-01 22:55:40 +0000444 // If the type exists (it should)
445 if (const Type* Ty = getType(type)) {
446 // Create the place holder
447 Value *Val = new Argument(Ty);
448 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
449 return Val;
450 }
451 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000452}
453
Misha Brukman8a96c532005-04-21 21:44:41 +0000454/// This is just like getValue, but when a compaction table is in use, it
455/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000456/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000457Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
458 if (SlotNo == 0)
459 return Constant::getNullValue(getType(TyID));
460
461 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
462 TyID -= Type::FirstDerivedTyID;
463 if (TyID >= CompactionTypes.size())
464 error("Type ID out of range for compaction table!");
465 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000466 }
467
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000468 --SlotNo;
469
Reid Spencer060d25d2004-06-29 23:29:38 +0000470 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
471 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000472 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
473 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000474 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000475 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000476 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000477 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000478 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000479 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000480 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
481 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000482 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000483 }
484 return ModuleValues[TyID]->getOperand(SlotNo);
485}
486
Reid Spencer04cde2c2004-07-04 11:33:49 +0000487/// Just like getValue, except that it returns a null pointer
488/// only on error. It always returns a constant (meaning that if the value is
489/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000490/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000491/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000492Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
493 if (Value *V = getValue(TypeSlot, Slot, false))
494 if (Constant *C = dyn_cast<Constant>(V))
495 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000496 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000497 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000498 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000499
Chris Lattner389bd042004-12-09 06:19:44 +0000500 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000501 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
502
503 if (I != ConstantFwdRefs.end() && I->first == Key) {
504 return I->second;
505 } else {
506 // Create a placeholder for the constant reference and
507 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000508 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000509
Reid Spencer060d25d2004-06-29 23:29:38 +0000510 // Keep track of the fact that we have a forward ref to recycle it
511 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
512 return C;
513 }
514}
515
516//===----------------------------------------------------------------------===//
517// IR Construction Methods
518//===----------------------------------------------------------------------===//
519
Reid Spencer04cde2c2004-07-04 11:33:49 +0000520/// As values are created, they are inserted into the appropriate place
521/// with this method. The ValueTable argument must be one of ModuleValues
522/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000523unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000524 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000525 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000526 !hasImplicitNull(type) &&
527 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000528
529 if (ValueTab.size() <= type)
530 ValueTab.resize(type+1);
531
532 if (!ValueTab[type]) ValueTab[type] = new ValueList();
533
534 ValueTab[type]->push_back(Val);
535
Chris Lattneraba5ff52005-05-05 20:57:00 +0000536 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000537 return ValueTab[type]->size()-1 + HasOffset;
538}
539
Reid Spencer04cde2c2004-07-04 11:33:49 +0000540/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000541void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000542 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000543 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000544 for (FunctionType::param_iterator It = FT->param_begin();
545 It != FT->param_end(); ++It, ++AI)
546 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
547}
548
549//===----------------------------------------------------------------------===//
550// Bytecode Parsing Methods
551//===----------------------------------------------------------------------===//
552
Reid Spencer04cde2c2004-07-04 11:33:49 +0000553/// This method parses a single instruction. The instruction is
554/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000555/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000556void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000557 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000558 BufPtr SaveAt = At;
559
560 // Clear instruction data
561 Oprnds.clear();
562 unsigned iType = 0;
563 unsigned Opcode = 0;
564 unsigned Op = read_uint();
565
566 // bits Instruction format: Common to all formats
567 // --------------------------
568 // 01-00: Opcode type, fixed to 1.
569 // 07-02: Opcode
570 Opcode = (Op >> 2) & 63;
571 Oprnds.resize((Op >> 0) & 03);
572
573 // Extract the operands
574 switch (Oprnds.size()) {
575 case 1:
576 // bits Instruction format:
577 // --------------------------
578 // 19-08: Resulting type plane
579 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
580 //
581 iType = (Op >> 8) & 4095;
582 Oprnds[0] = (Op >> 20) & 4095;
583 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
584 Oprnds.resize(0);
585 break;
586 case 2:
587 // bits Instruction format:
588 // --------------------------
589 // 15-08: Resulting type plane
590 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000591 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000592 //
593 iType = (Op >> 8) & 255;
594 Oprnds[0] = (Op >> 16) & 255;
595 Oprnds[1] = (Op >> 24) & 255;
596 break;
597 case 3:
598 // bits Instruction format:
599 // --------------------------
600 // 13-08: Resulting type plane
601 // 19-14: Operand #1
602 // 25-20: Operand #2
603 // 31-26: Operand #3
604 //
605 iType = (Op >> 8) & 63;
606 Oprnds[0] = (Op >> 14) & 63;
607 Oprnds[1] = (Op >> 20) & 63;
608 Oprnds[2] = (Op >> 26) & 63;
609 break;
610 case 0:
611 At -= 4; // Hrm, try this again...
612 Opcode = read_vbr_uint();
613 Opcode >>= 2;
614 iType = read_vbr_uint();
615
616 unsigned NumOprnds = read_vbr_uint();
617 Oprnds.resize(NumOprnds);
618
619 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000620 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000621
622 for (unsigned i = 0; i != NumOprnds; ++i)
623 Oprnds[i] = read_vbr_uint();
624 align32();
625 break;
626 }
627
Reid Spencer04cde2c2004-07-04 11:33:49 +0000628 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000629
Reid Spencer46b002c2004-07-11 17:28:43 +0000630 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000631 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000632
633 // Declare the resulting instruction we'll build.
634 Instruction *Result = 0;
635
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000636 // If this is a bytecode format that did not include the unreachable
637 // instruction, bump up all opcodes numbers to make space.
638 if (hasNoUnreachableInst) {
639 if (Opcode >= Instruction::Unreachable &&
640 Opcode < 62) {
641 ++Opcode;
642 }
643 }
644
Reid Spencer060d25d2004-06-29 23:29:38 +0000645 // Handle binary operators
646 if (Opcode >= Instruction::BinaryOpsBegin &&
647 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
648 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
649 getValue(iType, Oprnds[0]),
650 getValue(iType, Oprnds[1]));
651
652 switch (Opcode) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000653 default:
654 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000655 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000656 break;
657 case Instruction::VAArg:
Misha Brukman8a96c532005-04-21 21:44:41 +0000658 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000659 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000660 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000661 case 32: { //VANext_old
662 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
663 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
664
665 //b = vanext a, t ->
666 //foo = alloca 1 of t
667 //bar = vacopy a
668 //store bar -> foo
669 //tmp = vaarg foo, t
670 //b = load foo
671 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
672 BB->getInstList().push_back(foo);
673 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
674 BB->getInstList().push_back(bar);
675 BB->getInstList().push_back(new StoreInst(bar, foo));
676 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
677 BB->getInstList().push_back(tmp);
678 Result = new LoadInst(foo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000679 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000680 }
681 case 33: { //VAArg_old
682 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
683 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
684
Jeff Cohen00b168892005-07-27 06:12:32 +0000685 //b = vaarg a, t ->
Andrew Lenharth558bc882005-06-18 18:34:52 +0000686 //foo = alloca 1 of t
Jeff Cohen00b168892005-07-27 06:12:32 +0000687 //bar = vacopy a
Andrew Lenharth558bc882005-06-18 18:34:52 +0000688 //store bar -> foo
689 //b = vaarg foo, t
690 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
691 BB->getInstList().push_back(foo);
692 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
693 BB->getInstList().push_back(bar);
694 BB->getInstList().push_back(new StoreInst(bar, foo));
695 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
696 break;
697 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000698 case Instruction::Cast:
Misha Brukman8a96c532005-04-21 21:44:41 +0000699 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000700 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000701 break;
702 case Instruction::Select:
703 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
704 getValue(iType, Oprnds[1]),
705 getValue(iType, Oprnds[2]));
706 break;
707 case Instruction::PHI: {
708 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000709 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000710
711 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000712 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000713 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
714 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
715 Result = PN;
716 break;
717 }
718
719 case Instruction::Shl:
720 case Instruction::Shr:
721 Result = new ShiftInst((Instruction::OtherOps)Opcode,
722 getValue(iType, Oprnds[0]),
723 getValue(Type::UByteTyID, Oprnds[1]));
724 break;
725 case Instruction::Ret:
726 if (Oprnds.size() == 0)
727 Result = new ReturnInst();
728 else if (Oprnds.size() == 1)
729 Result = new ReturnInst(getValue(iType, Oprnds[0]));
730 else
Reid Spencer24399722004-07-09 22:21:33 +0000731 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000732 break;
733
734 case Instruction::Br:
735 if (Oprnds.size() == 1)
736 Result = new BranchInst(getBasicBlock(Oprnds[0]));
737 else if (Oprnds.size() == 3)
Misha Brukman8a96c532005-04-21 21:44:41 +0000738 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000739 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000740 else
Reid Spencer24399722004-07-09 22:21:33 +0000741 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000742 break;
743 case Instruction::Switch: {
744 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000745 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000746
747 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000748 getBasicBlock(Oprnds[1]),
749 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000750 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000751 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000752 getBasicBlock(Oprnds[i+1]));
753 Result = I;
754 break;
755 }
756
Chris Lattnerdee199f2005-05-06 22:34:01 +0000757 case 58: // Call with extra operand for calling conv
758 case 59: // tail call, Fast CC
759 case 60: // normal call, Fast CC
760 case 61: // tail call, C Calling Conv
761 case Instruction::Call: { // Normal Call, C Calling Convention
Reid Spencer060d25d2004-06-29 23:29:38 +0000762 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000763 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000764
765 Value *F = getValue(iType, Oprnds[0]);
766
Chris Lattnerdee199f2005-05-06 22:34:01 +0000767 unsigned CallingConv = CallingConv::C;
768 bool isTailCall = false;
769
770 if (Opcode == 61 || Opcode == 59)
771 isTailCall = true;
772
Reid Spencer060d25d2004-06-29 23:29:38 +0000773 // Check to make sure we have a pointer to function type
774 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000775 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000776 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000777 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000778
779 std::vector<Value *> Params;
780 if (!FTy->isVarArg()) {
781 FunctionType::param_iterator It = FTy->param_begin();
782
Chris Lattnerdee199f2005-05-06 22:34:01 +0000783 if (Opcode == 58) {
784 isTailCall = Oprnds.back() & 1;
785 CallingConv = Oprnds.back() >> 1;
786 Oprnds.pop_back();
787 } else if (Opcode == 59 || Opcode == 60)
788 CallingConv = CallingConv::Fast;
789
Reid Spencer060d25d2004-06-29 23:29:38 +0000790 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
791 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000792 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000793 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
794 }
795 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000796 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000797 } else {
798 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
799
800 unsigned FirstVariableOperand;
801 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000802 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000803
804 // Read all of the fixed arguments
805 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
806 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000807
Reid Spencer060d25d2004-06-29 23:29:38 +0000808 FirstVariableOperand = FTy->getNumParams();
809
Misha Brukman8a96c532005-04-21 21:44:41 +0000810 if ((Oprnds.size()-FirstVariableOperand) & 1)
Chris Lattner4a242b32004-10-14 01:39:18 +0000811 error("Invalid call instruction!"); // Must be pairs of type/value
Misha Brukman8a96c532005-04-21 21:44:41 +0000812
813 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000814 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000815 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
816 }
817
818 Result = new CallInst(F, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000819 if (isTailCall) cast<CallInst>(Result)->setTailCall();
820 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000821 break;
822 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000823 case 56: // Invoke with encoded CC
824 case 57: // Invoke Fast CC
825 case Instruction::Invoke: { // Invoke C CC
Misha Brukman8a96c532005-04-21 21:44:41 +0000826 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000827 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000828 Value *F = getValue(iType, Oprnds[0]);
829
830 // Check to make sure we have a pointer to function type
831 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000832 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000833 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000834 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000835 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000836 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000837
838 std::vector<Value *> Params;
839 BasicBlock *Normal, *Except;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000840 unsigned CallingConv = CallingConv::C;
841
842 if (Opcode == 57)
843 CallingConv = CallingConv::Fast;
844 else if (Opcode == 56) {
845 CallingConv = Oprnds.back();
846 Oprnds.pop_back();
847 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000848
849 if (!FTy->isVarArg()) {
850 Normal = getBasicBlock(Oprnds[1]);
851 Except = getBasicBlock(Oprnds[2]);
852
853 FunctionType::param_iterator It = FTy->param_begin();
854 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
855 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000856 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000857 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
858 }
859 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000860 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000861 } else {
862 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
863
864 Normal = getBasicBlock(Oprnds[0]);
865 Except = getBasicBlock(Oprnds[1]);
Misha Brukman8a96c532005-04-21 21:44:41 +0000866
Reid Spencer060d25d2004-06-29 23:29:38 +0000867 unsigned FirstVariableArgument = FTy->getNumParams()+2;
868 for (unsigned i = 2; i != FirstVariableArgument; ++i)
869 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
870 Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000871
Reid Spencer060d25d2004-06-29 23:29:38 +0000872 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000873 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000874
875 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
876 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
877 }
878
879 Result = new InvokeInst(F, Normal, Except, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000880 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000881 break;
882 }
883 case Instruction::Malloc:
Misha Brukman8a96c532005-04-21 21:44:41 +0000884 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000885 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000886 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000887 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000888
889 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
890 Oprnds.size() ? getValue(Type::UIntTyID,
891 Oprnds[0]) : 0);
892 break;
893
894 case Instruction::Alloca:
Misha Brukman8a96c532005-04-21 21:44:41 +0000895 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000896 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000897 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000898 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000899
900 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Misha Brukman8a96c532005-04-21 21:44:41 +0000901 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000902 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000903 break;
904 case Instruction::Free:
905 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000906 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000907 Result = new FreeInst(getValue(iType, Oprnds[0]));
908 break;
909 case Instruction::GetElementPtr: {
910 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000911 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000912
913 std::vector<Value*> Idx;
914
915 const Type *NextTy = InstTy;
916 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
917 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Misha Brukman8a96c532005-04-21 21:44:41 +0000918 if (!TopTy)
919 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000920
921 unsigned ValIdx = Oprnds[i];
922 unsigned IdxTy = 0;
923 if (!hasRestrictedGEPTypes) {
924 // Struct indices are always uints, sequential type indices can be any
925 // of the 32 or 64-bit integer types. The actual choice of type is
926 // encoded in the low two bits of the slot number.
927 if (isa<StructType>(TopTy))
928 IdxTy = Type::UIntTyID;
929 else {
930 switch (ValIdx & 3) {
931 default:
932 case 0: IdxTy = Type::UIntTyID; break;
933 case 1: IdxTy = Type::IntTyID; break;
934 case 2: IdxTy = Type::ULongTyID; break;
935 case 3: IdxTy = Type::LongTyID; break;
936 }
937 ValIdx >>= 2;
938 }
939 } else {
940 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
941 }
942
943 Idx.push_back(getValue(IdxTy, ValIdx));
944
945 // Convert ubyte struct indices into uint struct indices.
946 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
947 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
948 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
949
950 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
951 }
952
953 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
954 break;
955 }
956
957 case 62: // volatile load
958 case Instruction::Load:
959 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000960 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000961 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
962 break;
963
Misha Brukman8a96c532005-04-21 21:44:41 +0000964 case 63: // volatile store
Reid Spencer060d25d2004-06-29 23:29:38 +0000965 case Instruction::Store: {
966 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000967 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000968
969 Value *Ptr = getValue(iType, Oprnds[1]);
970 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
971 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
972 Opcode == 63);
973 break;
974 }
975 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000976 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000977 Result = new UnwindInst();
978 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000979 case Instruction::Unreachable:
980 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
981 Result = new UnreachableInst();
982 break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000983 } // end switch(Opcode)
Reid Spencer060d25d2004-06-29 23:29:38 +0000984
985 unsigned TypeSlot;
986 if (Result->getType() == InstTy)
987 TypeSlot = iType;
988 else
989 TypeSlot = getTypeSlot(Result->getType());
990
991 insertValue(Result, TypeSlot, FunctionValues);
992 BB->getInstList().push_back(Result);
993}
994
Reid Spencer04cde2c2004-07-04 11:33:49 +0000995/// Get a particular numbered basic block, which might be a forward reference.
996/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +0000997/// in a clean manner. This function is used when constructing phi, br, switch,
998/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +0000999/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001000BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001001 // Make sure there is room in the table...
1002 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1003
1004 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1005 // has already created this block, or if the forward reference has already
1006 // been created.
1007 if (ParsedBasicBlocks[ID])
1008 return ParsedBasicBlocks[ID];
1009
1010 // Otherwise, the basic block has not yet been created. Do so and add it to
1011 // the ParsedBasicBlocks list.
1012 return ParsedBasicBlocks[ID] = new BasicBlock();
1013}
1014
Misha Brukman8a96c532005-04-21 21:44:41 +00001015/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001016/// This method reads in one of the basicblock packets. This method is not used
1017/// for bytecode files after LLVM 1.0
1018/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001019BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1020 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001021
1022 BasicBlock *BB = 0;
1023
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001024 if (ParsedBasicBlocks.size() == BlockNo)
1025 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1026 else if (ParsedBasicBlocks[BlockNo] == 0)
1027 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1028 else
1029 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001030
Reid Spencer060d25d2004-06-29 23:29:38 +00001031 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001032 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001033 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001034
Reid Spencer46b002c2004-07-11 17:28:43 +00001035 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001036 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001037}
1038
Reid Spencer04cde2c2004-07-04 11:33:49 +00001039/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001040/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001041/// in order to avoid per-basic-block overhead.
1042/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001043unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001044 unsigned BlockNo = 0;
1045 std::vector<unsigned> Args;
1046
Reid Spencer46b002c2004-07-11 17:28:43 +00001047 while (moreInBlock()) {
1048 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001049 BasicBlock *BB;
1050 if (ParsedBasicBlocks.size() == BlockNo)
1051 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1052 else if (ParsedBasicBlocks[BlockNo] == 0)
1053 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1054 else
1055 BB = ParsedBasicBlocks[BlockNo];
1056 ++BlockNo;
1057 F->getBasicBlockList().push_back(BB);
1058
1059 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001060 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001061 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001062
1063 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001064 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001065
Reid Spencer46b002c2004-07-11 17:28:43 +00001066 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001067 }
1068
1069 return BlockNo;
1070}
1071
Reid Spencer04cde2c2004-07-04 11:33:49 +00001072/// Parse a symbol table. This works for both module level and function
1073/// level symbol tables. For function level symbol tables, the CurrentFunction
1074/// parameter must be non-zero and the ST parameter must correspond to
1075/// CurrentFunction's symbol table. For Module level symbol tables, the
1076/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001077void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001078 SymbolTable *ST) {
1079 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001080
Chris Lattner39cacce2003-10-10 05:43:47 +00001081 // Allow efficient basic block lookup by number.
1082 std::vector<BasicBlock*> BBMap;
1083 if (CurrentFunction)
1084 for (Function::iterator I = CurrentFunction->begin(),
1085 E = CurrentFunction->end(); I != E; ++I)
1086 BBMap.push_back(I);
1087
Reid Spencer04cde2c2004-07-04 11:33:49 +00001088 /// In LLVM 1.3 we write types separately from values so
1089 /// The types are always first in the symbol table. This is
1090 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001091 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001092 // Symtab block header: [num entries]
1093 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001094 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001095 // Symtab entry: [def slot #][name]
1096 unsigned slot = read_vbr_uint();
1097 std::string Name = read_str();
1098 const Type* T = getType(slot);
1099 ST->insert(Name, T);
1100 }
1101 }
1102
Reid Spencer46b002c2004-07-11 17:28:43 +00001103 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001104 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001105 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001106 unsigned Typ = 0;
1107 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001108 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001109
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001110 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001111 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001112 unsigned slot = read_vbr_uint();
1113 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001114
Reid Spencer04cde2c2004-07-04 11:33:49 +00001115 // if we're reading a pre 1.3 bytecode file and the type plane
1116 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001117 if (isTypeType) {
1118 const Type* T = getType(slot);
1119 if (T == 0)
1120 error("Failed type look-up for name '" + Name + "'");
1121 ST->insert(Name, T);
1122 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001123 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001124 Value *V = 0;
1125 if (Typ == Type::LabelTyID) {
1126 if (slot < BBMap.size())
1127 V = BBMap[slot];
1128 } else {
1129 V = getValue(Typ, slot, false); // Find mapping...
1130 }
1131 if (V == 0)
1132 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001133 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001134 }
Chris Lattner00950542001-06-06 20:29:01 +00001135 }
1136 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001137 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001138 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001139}
1140
Misha Brukman8a96c532005-04-21 21:44:41 +00001141/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001142void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001143 for (unsigned i = 0; i != NumEntries; ++i) {
1144 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001145 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001146 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001147 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001148 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001149 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001150 }
1151}
1152
1153/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001154void BytecodeReader::ParseCompactionTable() {
1155
Reid Spencer46b002c2004-07-11 17:28:43 +00001156 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001157 if (Handler) Handler->handleCompactionTableBegin();
1158
Misha Brukman8a96c532005-04-21 21:44:41 +00001159 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001160 // we always write them first in the compaction table
1161 // because they can't occupy a "type plane" where the
1162 // Values reside.
1163 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001164 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001165 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001166 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001167
Reid Spencer46b002c2004-07-11 17:28:43 +00001168 // Compaction tables live in separate blocks so we have to loop
1169 // until we've read the whole thing.
1170 while (moreInBlock()) {
1171 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001172 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001173 unsigned Ty = 0;
1174 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001175
Reid Spencer46b002c2004-07-11 17:28:43 +00001176 // Decode the type from value read in. Most compaction table
1177 // planes will have one or two entries in them. If that's the
1178 // case then the length is encoded in the bottom two bits and
1179 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001180 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001181 // In this case, both low-order bits are set (value 3). This
1182 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001183 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001184 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001185 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001186 // In this case, the low-order bits specify the number of entries
1187 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001188 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001189 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001190 NumEntries &= 3;
1191 }
1192
Reid Spencer04cde2c2004-07-04 11:33:49 +00001193 // if we're reading a pre 1.3 bytecode file and the type plane
1194 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001195 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001196 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001197 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001198 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001199 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001200 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001201
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001202 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001203 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001204 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001205
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001206 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001207 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001208
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001209 // Push the implicit zero.
1210 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001211
1212 // Read in each of the entries, put them in the compaction table
1213 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001214 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001215 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001216 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001217 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001218 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001219 }
1220 }
1221 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001222 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001223 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001224}
Misha Brukman8a96c532005-04-21 21:44:41 +00001225
Reid Spencer46b002c2004-07-11 17:28:43 +00001226// Parse a single type. The typeid is read in first. If its a primitive type
1227// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001228// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001229// definition.
1230const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001231 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001232 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001233 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001234
1235 const Type *Result = 0;
1236 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1237 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001238
Reid Spencer060d25d2004-06-29 23:29:38 +00001239 switch (PrimType) {
1240 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001241 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001242
1243 unsigned NumParams = read_vbr_uint();
1244
1245 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001246 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001247 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001248
1249 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1250 if (isVarArg) Params.pop_back();
1251
1252 Result = FunctionType::get(RetType, Params, isVarArg);
1253 break;
1254 }
1255 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001256 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001257 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001258 Result = ArrayType::get(ElementType, NumElements);
1259 break;
1260 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001261 case Type::PackedTyID: {
1262 const Type *ElementType = readSanitizedType();
1263 unsigned NumElements = read_vbr_uint();
1264 Result = PackedType::get(ElementType, NumElements);
1265 break;
1266 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001267 case Type::StructTyID: {
1268 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001269 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001270 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001271 error("Invalid element type (type type) for structure!");
1272
Reid Spencer060d25d2004-06-29 23:29:38 +00001273 while (Typ) { // List is terminated by void/0 typeid
1274 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001275 if (read_typeid(Typ))
1276 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001277 }
1278
1279 Result = StructType::get(Elements);
1280 break;
1281 }
1282 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001283 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001284 break;
1285 }
1286
1287 case Type::OpaqueTyID: {
1288 Result = OpaqueType::get();
1289 break;
1290 }
1291
1292 default:
Reid Spencer24399722004-07-09 22:21:33 +00001293 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001294 break;
1295 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001296 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001297 return Result;
1298}
1299
Reid Spencer5b472d92004-08-21 20:49:23 +00001300// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001301// types. We know that recursive types will only reference the current slab of
1302// values in the type plane, but they can forward reference types before they
1303// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1304// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1305// this ugly problem, we pessimistically insert an opaque type for each type we
1306// are about to read. This means that forward references will resolve to
1307// something and when we reread the type later, we can replace the opaque type
1308// with a new resolved concrete type.
1309//
Reid Spencer46b002c2004-07-11 17:28:43 +00001310void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001311 assert(Tab.size() == 0 && "should not have read type constants in before!");
1312
1313 // Insert a bunch of opaque types to be resolved later...
1314 Tab.reserve(NumEntries);
1315 for (unsigned i = 0; i != NumEntries; ++i)
1316 Tab.push_back(OpaqueType::get());
1317
Misha Brukman8a96c532005-04-21 21:44:41 +00001318 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001319 Handler->handleTypeList(NumEntries);
1320
Reid Spencer060d25d2004-06-29 23:29:38 +00001321 // Loop through reading all of the types. Forward types will make use of the
1322 // opaque types just inserted.
1323 //
1324 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001325 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001326 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001327 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001328 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001329
Misha Brukman8a96c532005-04-21 21:44:41 +00001330 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001331 // the opaque type we previously inserted with the new concrete value. This
1332 // approach helps with forward references to types. The refinement from the
1333 // abstract (opaque) type to the new type causes all uses of the abstract
1334 // type to use the concrete type (NewTy). This will also cause the opaque
1335 // type to be deleted.
1336 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1337
1338 // This should have replaced the old opaque type with the new type in the
1339 // value table... or with a preexisting type that was already in the system.
1340 // Let's just make sure it did.
1341 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1342 }
1343}
1344
Reid Spencer04cde2c2004-07-04 11:33:49 +00001345/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001346Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001347 // We must check for a ConstantExpr before switching by type because
1348 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001349 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001350 // 0 if not expr; numArgs if is expr
1351 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001352
Reid Spencer060d25d2004-06-29 23:29:38 +00001353 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001354 // 'undef' is encoded with 'exprnumargs' == 1.
1355 if (!hasNoUndefValue)
1356 if (--isExprNumArgs == 0)
1357 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001358
Reid Spencer060d25d2004-06-29 23:29:38 +00001359 // FIXME: Encoding of constant exprs could be much more compact!
1360 std::vector<Constant*> ArgVec;
1361 ArgVec.reserve(isExprNumArgs);
1362 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001363
1364 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1365 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001366
Reid Spencer060d25d2004-06-29 23:29:38 +00001367 // Read the slot number and types of each of the arguments
1368 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1369 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001370 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001371 if (read_typeid(ArgTypeSlot))
1372 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001373
Reid Spencer060d25d2004-06-29 23:29:38 +00001374 // Get the arg value from its slot if it exists, otherwise a placeholder
1375 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1376 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001377
Reid Spencer060d25d2004-06-29 23:29:38 +00001378 // Construct a ConstantExpr of the appropriate kind
1379 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001380 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001381 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001382
Reid Spencer060d25d2004-06-29 23:29:38 +00001383 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001384 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001385 return Result;
1386 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1387 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1388
1389 if (hasRestrictedGEPTypes) {
1390 const Type *BaseTy = ArgVec[0]->getType();
1391 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1392 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1393 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1394 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1395 if (isa<StructType>(*GTI)) {
1396 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001397 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001398 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1399 }
1400 }
1401
1402 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001403 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001404 return Result;
1405 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001406 if (ArgVec.size() != 3)
1407 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001408 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001409 ArgVec[2]);
1410 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001411 return Result;
1412 } else { // All other 2-operand expressions
1413 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001414 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001415 return Result;
1416 }
1417 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001418
Reid Spencer060d25d2004-06-29 23:29:38 +00001419 // Ok, not an ConstantExpr. We now know how to read the given type...
1420 const Type *Ty = getType(TypeID);
1421 switch (Ty->getTypeID()) {
1422 case Type::BoolTyID: {
1423 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001424 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001425 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001426 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001427 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001428 return Result;
1429 }
1430
1431 case Type::UByteTyID: // Unsigned integer types...
1432 case Type::UShortTyID:
1433 case Type::UIntTyID: {
1434 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001435 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001436 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001437 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001438 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001439 return Result;
1440 }
1441
1442 case Type::ULongTyID: {
1443 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001444 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001445 return Result;
1446 }
1447
1448 case Type::SByteTyID: // Signed integer types...
1449 case Type::ShortTyID:
1450 case Type::IntTyID: {
1451 case Type::LongTyID:
1452 int64_t Val = read_vbr_int64();
Misha Brukman8a96c532005-04-21 21:44:41 +00001453 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001454 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001455 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001456 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001457 return Result;
1458 }
1459
1460 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001461 float Val;
1462 read_float(Val);
1463 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001464 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001465 return Result;
1466 }
1467
1468 case Type::DoubleTyID: {
1469 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001470 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001471 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001472 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001473 return Result;
1474 }
1475
Reid Spencer060d25d2004-06-29 23:29:38 +00001476 case Type::ArrayTyID: {
1477 const ArrayType *AT = cast<ArrayType>(Ty);
1478 unsigned NumElements = AT->getNumElements();
1479 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1480 std::vector<Constant*> Elements;
1481 Elements.reserve(NumElements);
1482 while (NumElements--) // Read all of the elements of the constant.
1483 Elements.push_back(getConstantValue(TypeSlot,
1484 read_vbr_uint()));
1485 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001486 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001487 return Result;
1488 }
1489
1490 case Type::StructTyID: {
1491 const StructType *ST = cast<StructType>(Ty);
1492
1493 std::vector<Constant *> Elements;
1494 Elements.reserve(ST->getNumElements());
1495 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1496 Elements.push_back(getConstantValue(ST->getElementType(i),
1497 read_vbr_uint()));
1498
1499 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001500 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001501 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001502 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001503
Brian Gaeke715c90b2004-08-20 06:00:58 +00001504 case Type::PackedTyID: {
1505 const PackedType *PT = cast<PackedType>(Ty);
1506 unsigned NumElements = PT->getNumElements();
1507 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1508 std::vector<Constant*> Elements;
1509 Elements.reserve(NumElements);
1510 while (NumElements--) // Read all of the elements of the constant.
1511 Elements.push_back(getConstantValue(TypeSlot,
1512 read_vbr_uint()));
1513 Constant* Result = ConstantPacked::get(PT, Elements);
1514 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1515 return Result;
1516 }
1517
Chris Lattner638c3812004-11-19 16:24:05 +00001518 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001519 const PointerType *PT = cast<PointerType>(Ty);
1520 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001521
Reid Spencer060d25d2004-06-29 23:29:38 +00001522 // Check to see if we have already read this global variable...
1523 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001524 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001525 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1526 if (!GV) error("GlobalValue not in ValueTable!");
1527 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1528 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001529 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001530 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001531 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001532 }
1533
1534 default:
Reid Spencer24399722004-07-09 22:21:33 +00001535 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001536 Ty->getDescription());
1537 break;
1538 }
Reid Spencer24399722004-07-09 22:21:33 +00001539 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001540}
1541
Misha Brukman8a96c532005-04-21 21:44:41 +00001542/// Resolve references for constants. This function resolves the forward
1543/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001544/// replaceAllUsesWith method of Value class to substitute the placeholder
1545/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001546void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1547 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001548 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001549 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001550 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001551
Chris Lattner29b789b2003-11-19 17:27:18 +00001552 Value *PH = I->second; // Get the placeholder...
1553 PH->replaceAllUsesWith(NewV);
1554 delete PH; // Delete the old placeholder
1555 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001556}
1557
Reid Spencer04cde2c2004-07-04 11:33:49 +00001558/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001559void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1560 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001561 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001562 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001563 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001564 const Type *Ty = getType(Typ);
1565 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001566 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001567
Reid Spencer060d25d2004-06-29 23:29:38 +00001568 const ArrayType *ATy = cast<ArrayType>(Ty);
1569 if (ATy->getElementType() != Type::SByteTy &&
1570 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001571 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001572
Reid Spencer060d25d2004-06-29 23:29:38 +00001573 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001574 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001575 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001576
Reid Spencer060d25d2004-06-29 23:29:38 +00001577 std::vector<Constant*> Elements(ATy->getNumElements());
1578 if (ATy->getElementType() == Type::SByteTy)
1579 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1580 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1581 else
1582 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1583 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001584
Reid Spencer060d25d2004-06-29 23:29:38 +00001585 // Create the constant, inserting it as needed.
1586 Constant *C = ConstantArray::get(ATy, Elements);
1587 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001588 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001589 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001590 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001591}
1592
Reid Spencer04cde2c2004-07-04 11:33:49 +00001593/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001594void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001595 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001596 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001597 if (Handler) Handler->handleGlobalConstantsBegin();
1598
1599 /// In LLVM 1.3 Type does not derive from Value so the types
1600 /// do not occupy a plane. Consequently, we read the types
1601 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001602 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001603 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001604 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001605 }
1606
Reid Spencer46b002c2004-07-11 17:28:43 +00001607 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001608 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001609 unsigned Typ = 0;
1610 bool isTypeType = read_typeid(Typ);
1611
1612 /// In LLVM 1.2 and before, Types were written to the
1613 /// bytecode file in the "Type Type" plane (#12).
1614 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001615 if (isTypeType) {
1616 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001617 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001618 /// Use of Type::VoidTyID is a misnomer. It actually means
1619 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001620 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1621 ParseStringConstants(NumEntries, Tab);
1622 } else {
1623 for (unsigned i = 0; i < NumEntries; ++i) {
1624 Constant *C = ParseConstantValue(Typ);
1625 assert(C && "ParseConstantValue returned NULL!");
1626 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001627
Reid Spencer060d25d2004-06-29 23:29:38 +00001628 // If we are reading a function constant table, make sure that we adjust
1629 // the slot number to be the real global constant number.
1630 //
1631 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1632 ModuleValues[Typ])
1633 Slot += ModuleValues[Typ]->size();
Chris Lattner389bd042004-12-09 06:19:44 +00001634 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001635 }
1636 }
1637 }
Chris Lattner02dce162004-12-04 05:28:27 +00001638
1639 // After we have finished parsing the constant pool, we had better not have
1640 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001641 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001642 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001643 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001644 error(utostr(ConstantFwdRefs.size()) +
1645 " unresolved constant reference exist. First one is '" +
1646 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001647 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001648 }
Chris Lattner02dce162004-12-04 05:28:27 +00001649
Reid Spencer060d25d2004-06-29 23:29:38 +00001650 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001651 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001652}
Chris Lattner00950542001-06-06 20:29:01 +00001653
Reid Spencer04cde2c2004-07-04 11:33:49 +00001654/// Parse the contents of a function. Note that this function can be
1655/// called lazily by materializeFunction
1656/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001657void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001658
1659 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001660 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1661
Reid Spencer060d25d2004-06-29 23:29:38 +00001662 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001663 switch (LinkageType) {
1664 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1665 case 1: Linkage = GlobalValue::WeakLinkage; break;
1666 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1667 case 3: Linkage = GlobalValue::InternalLinkage; break;
1668 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001669 default:
Reid Spencer24399722004-07-09 22:21:33 +00001670 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001671 Linkage = GlobalValue::InternalLinkage;
1672 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001673 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001674
Reid Spencer46b002c2004-07-11 17:28:43 +00001675 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001676 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001677
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001678 // Keep track of how many basic blocks we have read in...
1679 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001680 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001681
Reid Spencer060d25d2004-06-29 23:29:38 +00001682 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001683 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001684 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001685 BufPtr OldAt = At;
1686 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001687
1688 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001689 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001690 if (!InsertedArguments) {
1691 // Insert arguments into the value table before we parse the first basic
1692 // block in the function, but after we potentially read in the
1693 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001694 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001695 InsertedArguments = true;
1696 }
1697
Reid Spencer04cde2c2004-07-04 11:33:49 +00001698 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001699 break;
1700
Reid Spencerad89bd62004-07-25 18:07:36 +00001701 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001702 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001703 break;
1704
Chris Lattner00950542001-06-06 20:29:01 +00001705 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001706 if (!InsertedArguments) {
1707 // Insert arguments into the value table before we parse the first basic
1708 // block in the function, but after we potentially read in the
1709 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001710 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001711 InsertedArguments = true;
1712 }
1713
Reid Spencer060d25d2004-06-29 23:29:38 +00001714 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001715 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001716 break;
1717 }
1718
Reid Spencerad89bd62004-07-25 18:07:36 +00001719 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001720 // Insert arguments into the value table before we parse the instruction
1721 // list for the function, but after we potentially read in the compaction
1722 // table.
1723 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001724 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001725 InsertedArguments = true;
1726 }
1727
Misha Brukman8a96c532005-04-21 21:44:41 +00001728 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001729 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001730 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001731 break;
1732 }
1733
Reid Spencerad89bd62004-07-25 18:07:36 +00001734 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001735 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001736 break;
1737
1738 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001739 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001740 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001741 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001742 break;
1743 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001744 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001745
Misha Brukman12c29d12003-09-22 23:38:23 +00001746 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001747 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001748 }
1749
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001750 // Make sure there were no references to non-existant basic blocks.
1751 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001752 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001753
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001754 ParsedBasicBlocks.clear();
1755
Chris Lattner97330cf2003-10-09 23:10:14 +00001756 // Resolve forward references. Replace any uses of a forward reference value
1757 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001758 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001759 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1760 I = ForwardReferences.begin();
1761 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001762 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001763 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001764 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001765 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001766 }
Chris Lattner00950542001-06-06 20:29:01 +00001767
Misha Brukman12c29d12003-09-22 23:38:23 +00001768 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001769 FunctionTypes.clear();
1770 CompactionTypes.clear();
1771 CompactionValues.clear();
1772 freeTable(FunctionValues);
1773
Reid Spencer04cde2c2004-07-04 11:33:49 +00001774 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001775}
1776
Reid Spencer04cde2c2004-07-04 11:33:49 +00001777/// This function parses LLVM functions lazily. It obtains the type of the
1778/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001779/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001780/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001781void BytecodeReader::ParseFunctionLazily() {
1782 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001783 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001784
Reid Spencer060d25d2004-06-29 23:29:38 +00001785 Function *Func = FunctionSignatureList.back();
1786 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001787
Reid Spencer060d25d2004-06-29 23:29:38 +00001788 // Save the information for future reading of the function
1789 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001790
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001791 // This function has a body but it's not loaded so it appears `External'.
1792 // Mark it as a `Ghost' instead to notify the users that it has a body.
1793 Func->setLinkage(GlobalValue::GhostLinkage);
1794
Reid Spencer060d25d2004-06-29 23:29:38 +00001795 // Pretend we've `parsed' this function
1796 At = BlockEnd;
1797}
Chris Lattner89e02532004-01-18 21:08:15 +00001798
Misha Brukman8a96c532005-04-21 21:44:41 +00001799/// The ParserFunction method lazily parses one function. Use this method to
1800/// casue the parser to parse a specific function in the module. Note that
1801/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001802/// ParseAllFunctionBodies.
1803/// @see ParseAllFunctionBodies
1804/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001805void BytecodeReader::ParseFunction(Function* Func) {
1806 // Find {start, end} pointers and slot in the map. If not there, we're done.
1807 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001808
Reid Spencer060d25d2004-06-29 23:29:38 +00001809 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001810 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001811 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001812 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001813 }
1814
Reid Spencer060d25d2004-06-29 23:29:38 +00001815 BlockStart = At = Fi->second.Buf;
1816 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001817 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001818
1819 LazyFunctionLoadMap.erase(Fi);
1820
Reid Spencer46b002c2004-07-11 17:28:43 +00001821 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001822}
1823
Reid Spencer04cde2c2004-07-04 11:33:49 +00001824/// The ParseAllFunctionBodies method parses through all the previously
1825/// unparsed functions in the bytecode file. If you want to completely parse
1826/// a bytecode file, this method should be called after Parsebytecode because
1827/// Parsebytecode only records the locations in the bytecode file of where
1828/// the function definitions are located. This function uses that information
1829/// to materialize the functions.
1830/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001831void BytecodeReader::ParseAllFunctionBodies() {
1832 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1833 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001834
Reid Spencer46b002c2004-07-11 17:28:43 +00001835 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001836 Function* Func = Fi->first;
1837 BlockStart = At = Fi->second.Buf;
1838 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001839 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001840 ++Fi;
1841 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001842 LazyFunctionLoadMap.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001843}
Chris Lattner89e02532004-01-18 21:08:15 +00001844
Reid Spencer04cde2c2004-07-04 11:33:49 +00001845/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001846void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001847 // Read the number of types
1848 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001849
1850 // Ignore the type plane identifier for types if the bc file is pre 1.3
1851 if (hasTypeDerivedFromValue)
1852 read_vbr_uint();
1853
Reid Spencer46b002c2004-07-11 17:28:43 +00001854 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001855}
1856
Reid Spencer04cde2c2004-07-04 11:33:49 +00001857/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001858void BytecodeReader::ParseModuleGlobalInfo() {
1859
Reid Spencer04cde2c2004-07-04 11:33:49 +00001860 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001861
Chris Lattner70cc3392001-09-10 07:58:01 +00001862 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001863 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001864 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001865 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1866 // Linkage, bit4+ = slot#
1867 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001868 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001869 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001870 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001871 bool isConstant = VarType & 1;
1872 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001873 GlobalValue::LinkageTypes Linkage;
1874
Chris Lattnerc08912f2004-01-14 16:44:44 +00001875 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001876 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1877 case 1: Linkage = GlobalValue::WeakLinkage; break;
1878 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1879 case 3: Linkage = GlobalValue::InternalLinkage; break;
1880 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001881 default:
Reid Spencer24399722004-07-09 22:21:33 +00001882 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001883 Linkage = GlobalValue::InternalLinkage;
1884 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001885 }
1886
1887 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001888 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001889 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001890 }
1891
Reid Spencer46b002c2004-07-11 17:28:43 +00001892 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001893 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001894 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001895
Chris Lattner52e20b02003-03-19 20:54:26 +00001896 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001897
Chris Lattner70cc3392001-09-10 07:58:01 +00001898 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001899 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001900 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001901 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001902
Reid Spencer060d25d2004-06-29 23:29:38 +00001903 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001904 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001905 initSlot = read_vbr_uint();
1906 GlobalInits.push_back(std::make_pair(GV, initSlot));
1907 }
1908
1909 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001910 if (Handler)
1911 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001912
1913 // Get next item
1914 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001915 }
1916
Chris Lattner52e20b02003-03-19 20:54:26 +00001917 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001918 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001919
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001920 if (hasNoFlagsForFunctions)
1921 FnSignature = (FnSignature << 5) + 1;
1922
1923 // List is terminated by VoidTy.
1924 while ((FnSignature >> 5) != Type::VoidTyID) {
1925 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001926 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001927 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001928 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001929 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001930 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001931
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001932 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001933 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001934 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001935
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001936
Chris Lattner18549c22004-11-15 21:43:03 +00001937 // Insert the place holder.
Misha Brukman8a96c532005-04-21 21:44:41 +00001938 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001939 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001940 insertValue(Func, FnSignature >> 5, ModuleValues);
1941
1942 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001943 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001944
Chris Lattner97fbc502004-11-15 22:38:52 +00001945 // Save this for later so we know type of lazily instantiated functions.
1946 // Note that known-external functions do not have FunctionInfo blocks, so we
1947 // do not add them to the FunctionSignatureList.
1948 if ((Flags & (1 << 4)) == 0)
1949 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001950
Chris Lattner479ffeb2005-05-06 20:42:57 +00001951 // Look at the low bits. If there is a calling conv here, apply it,
1952 // read it as a vbr.
1953 Flags &= 15;
1954 if (Flags)
1955 Func->setCallingConv(Flags-1);
1956 else
1957 Func->setCallingConv(read_vbr_uint());
1958
Reid Spencer04cde2c2004-07-04 11:33:49 +00001959 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001960
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001961 // Get the next function signature.
1962 FnSignature = read_vbr_uint();
1963 if (hasNoFlagsForFunctions)
1964 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001965 }
1966
Misha Brukman8a96c532005-04-21 21:44:41 +00001967 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001968 // remove elements efficiently from the back of the vector.
1969 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001970
Reid Spencerad89bd62004-07-25 18:07:36 +00001971 // If this bytecode format has dependent library information in it ..
1972 if (!hasNoDependentLibraries) {
1973 // Read in the number of dependent library items that follow
1974 unsigned num_dep_libs = read_vbr_uint();
1975 std::string dep_lib;
1976 while( num_dep_libs-- ) {
1977 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001978 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001979 if (Handler)
1980 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001981 }
1982
Reid Spencer5b472d92004-08-21 20:49:23 +00001983
Reid Spencerad89bd62004-07-25 18:07:36 +00001984 // Read target triple and place into the module
1985 std::string triple = read_str();
1986 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001987 if (Handler)
1988 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001989 }
1990
1991 if (hasInconsistentModuleGlobalInfo)
1992 align32();
1993
Chris Lattner00950542001-06-06 20:29:01 +00001994 // This is for future proofing... in the future extra fields may be added that
1995 // we don't understand, so we transparently ignore them.
1996 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001997 At = BlockEnd;
1998
Reid Spencer04cde2c2004-07-04 11:33:49 +00001999 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002000}
2001
Reid Spencer04cde2c2004-07-04 11:33:49 +00002002/// Parse the version information and decode it by setting flags on the
2003/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002004void BytecodeReader::ParseVersionInfo() {
2005 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002006
2007 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002008 Module::Endianness Endianness;
2009 Module::PointerSize PointerSize;
2010 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2011 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2012
2013 bool hasNoEndianness = Version & 4;
2014 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002015
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002016 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002017
2018 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002019 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002020 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002021 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002022 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002023 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002024 has32BitTypes = false;
2025 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002026 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002027 hasNoUndefValue = false;
2028 hasNoFlagsForFunctions = false;
2029 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002030
2031 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002032 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002033 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002034 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002035 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002036
Chris Lattner80b97342004-01-17 23:25:43 +00002037 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002038
2039 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002040 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002041
2042 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2043 // included the size for the alignment at the end, where the rest of the
2044 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002045
2046 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2047 // structures and longs for sequential types.
2048 hasRestrictedGEPTypes = true;
2049
Reid Spencer04cde2c2004-07-04 11:33:49 +00002050 // LLVM 1.2 and before had the Type class derive from Value class. This
2051 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002052 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002053 // type planes for Values.
2054 hasTypeDerivedFromValue = true;
2055
Chris Lattner5fa428f2004-04-05 01:27:26 +00002056 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002057
Reid Spencer5b472d92004-08-21 20:49:23 +00002058 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002059
Reid Spencer5b472d92004-08-21 20:49:23 +00002060 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002061 // especially for small files where the 8 bytes per block is a large
2062 // fraction of the total block size. In LLVM 1.3, the block type and length
2063 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2064 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002065 hasLongBlockHeaders = true;
2066
Reid Spencer5b472d92004-08-21 20:49:23 +00002067 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002068 // this has been reduced to vbr_uint24. It shouldn't make much difference
2069 // since we haven't run into a module with > 24 million types, but for
2070 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2071 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002072 has32BitTypes = true;
2073
Misha Brukman8a96c532005-04-21 21:44:41 +00002074 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002075 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2076 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002077 hasNoDependentLibraries = true;
2078
2079 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002080
2081 case 3: // LLVM 1.3 (Released)
2082 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002083 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002084 // of GEP references to a constant array), this can increase the file size
2085 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002086 hasAlignment = true;
2087
2088 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002089
Reid Spencer5b472d92004-08-21 20:49:23 +00002090 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002091 // In version 4, we did not support the 'undef' constant.
2092 hasNoUndefValue = true;
2093
2094 // In version 4 and above, we did not include space for flags for functions
2095 // in the module info block.
2096 hasNoFlagsForFunctions = true;
2097
2098 // In version 4 and above, we did not include the 'unreachable' instruction
2099 // in the opcode numbering in the bytecode file.
2100 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002101 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002102
2103 // FALL THROUGH
2104
Chris Lattnerdee199f2005-05-06 22:34:01 +00002105 case 5: // 1.4 (Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002106 break;
2107
Chris Lattner036b8aa2003-03-06 17:55:45 +00002108 default:
Reid Spencer24399722004-07-09 22:21:33 +00002109 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002110 }
2111
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002112 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2113 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002114
Brian Gaekefe2102b2004-07-14 20:33:13 +00002115 TheModule->setEndianness(Endianness);
2116 TheModule->setPointerSize(PointerSize);
2117
Reid Spencer46b002c2004-07-11 17:28:43 +00002118 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002119}
2120
Reid Spencer04cde2c2004-07-04 11:33:49 +00002121/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002122void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002123 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002124
Reid Spencer060d25d2004-06-29 23:29:38 +00002125 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002126
2127 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002128 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002129 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002130
Reid Spencer060d25d2004-06-29 23:29:38 +00002131 bool SeenModuleGlobalInfo = false;
2132 bool SeenGlobalTypePlane = false;
2133 BufPtr MyEnd = BlockEnd;
2134 while (At < MyEnd) {
2135 BufPtr OldAt = At;
2136 read_block(Type, Size);
2137
Chris Lattner00950542001-06-06 20:29:01 +00002138 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002139
Reid Spencerad89bd62004-07-25 18:07:36 +00002140 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002141 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002142 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002143
Reid Spencer5b472d92004-08-21 20:49:23 +00002144 if (Size > 0)
2145 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002146 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002147 break;
2148
Misha Brukman8a96c532005-04-21 21:44:41 +00002149 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002150 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002151 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002152 ParseModuleGlobalInfo();
2153 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002154 break;
2155
Reid Spencerad89bd62004-07-25 18:07:36 +00002156 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002157 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002158 break;
2159
Reid Spencerad89bd62004-07-25 18:07:36 +00002160 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002161 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002162 break;
Chris Lattner00950542001-06-06 20:29:01 +00002163
Reid Spencerad89bd62004-07-25 18:07:36 +00002164 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002165 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002166 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002167
Chris Lattner00950542001-06-06 20:29:01 +00002168 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002169 At += Size;
2170 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002171 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002172 }
Chris Lattner00950542001-06-06 20:29:01 +00002173 break;
2174 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002175 BlockEnd = MyEnd;
2176 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002177 }
2178
Chris Lattner52e20b02003-03-19 20:54:26 +00002179 // After the module constant pool has been read, we can safely initialize
2180 // global variables...
2181 while (!GlobalInits.empty()) {
2182 GlobalVariable *GV = GlobalInits.back().first;
2183 unsigned Slot = GlobalInits.back().second;
2184 GlobalInits.pop_back();
2185
2186 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002187 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002188
2189 const llvm::PointerType* GVType = GV->getType();
2190 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002191 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002192 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002193 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002194 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002195 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002196 } else
Reid Spencer24399722004-07-09 22:21:33 +00002197 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002198 }
2199
Chris Lattneraba5ff52005-05-05 20:57:00 +00002200 if (!ConstantFwdRefs.empty())
2201 error("Use of undefined constants in a module");
2202
Reid Spencer060d25d2004-06-29 23:29:38 +00002203 /// Make sure we pulled them all out. If we didn't then there's a declaration
2204 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002205 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002206 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002207}
2208
Reid Spencer04cde2c2004-07-04 11:33:49 +00002209/// This function completely parses a bytecode buffer given by the \p Buf
2210/// and \p Length parameters.
Misha Brukman8a96c532005-04-21 21:44:41 +00002211void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002212 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002213
Reid Spencer060d25d2004-06-29 23:29:38 +00002214 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002215 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002216 At = MemStart = BlockStart = Buf;
2217 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002218
Reid Spencer060d25d2004-06-29 23:29:38 +00002219 // Create the module
2220 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002221
Reid Spencer04cde2c2004-07-04 11:33:49 +00002222 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002223
Reid Spencerf0c977c2004-11-07 18:20:55 +00002224 // Read the four bytes of the signature.
2225 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002226
Reid Spencerf0c977c2004-11-07 18:20:55 +00002227 // If this is a compressed file
2228 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002229
Reid Spencerf0c977c2004-11-07 18:20:55 +00002230 // Invoke the decompression of the bytecode. Note that we have to skip the
2231 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002232 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2233 // member for retention until BytecodeReader is destructed.
2234 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2235 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002236
2237 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002238 // into the new decompressed block. After decompression, the
2239 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002240 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002241 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002242 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002243
Reid Spencerf0c977c2004-11-07 18:20:55 +00002244 // else if this isn't a regular (uncompressed) bytecode file, then its
2245 // and error, generate that now.
2246 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2247 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002248 }
2249
Reid Spencer060d25d2004-06-29 23:29:38 +00002250 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002251 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002252
Reid Spencerad89bd62004-07-25 18:07:36 +00002253 // Get the module block and size and verify. This is handled specially
2254 // because the module block/size is always written in long format. Other
2255 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002256 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002257 Type = read_uint();
2258 Size = read_uint();
2259 if (Type != BytecodeFormat::ModuleBlockID) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002260 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002261 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002262 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002263
2264 // It looks like the darwin ranlib program is broken, and adds trailing
2265 // garbage to the end of some bytecode files. This hack allows the bc
2266 // reader to ignore trailing garbage on bytecode files.
2267 if (At + Size < MemEnd)
2268 MemEnd = BlockEnd = At+Size;
2269
2270 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002271 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002272 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002273
2274 // Parse the module contents
2275 this->ParseModule();
2276
Reid Spencer060d25d2004-06-29 23:29:38 +00002277 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002278 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002279 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002280
Reid Spencer5c15fe52004-07-05 00:57:50 +00002281 // Tell the handler we're done with the module
Misha Brukman8a96c532005-04-21 21:44:41 +00002282 if (Handler)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002283 Handler->handleModuleEnd(ModuleID);
2284
2285 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002286 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002287
Reid Spencer46b002c2004-07-11 17:28:43 +00002288 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002289 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002290 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002291 delete TheModule;
2292 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002293 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002294 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002295 decompressedBlock = 0;
2296 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002297 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002298 } catch (...) {
2299 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002300 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002301 freeState();
2302 delete TheModule;
2303 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002304 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002305 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002306 decompressedBlock = 0;
2307 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002308 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002309 }
Chris Lattner00950542001-06-06 20:29:01 +00002310}
Reid Spencer060d25d2004-06-29 23:29:38 +00002311
2312//===----------------------------------------------------------------------===//
2313//=== Default Implementations of Handler Methods
2314//===----------------------------------------------------------------------===//
2315
2316BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002317