blob: 6bb06c3ce46f024867df2855111bf9904a5997fa [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"
Jim Laskeycb6682f2005-08-17 19:34:49 +000030#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000032#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000033#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Reid Spencer46b002c2004-07-11 17:28:43 +000036namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000037 /// @brief A class for maintaining the slot number definition
38 /// as a placeholder for the actual definition for forward constants defs.
39 class ConstantPlaceHolder : public ConstantExpr {
40 ConstantPlaceHolder(); // DO NOT IMPLEMENT
41 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
42 public:
Chris Lattner61323322005-01-31 01:11:13 +000043 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000044 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000045 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
46 Op(UndefValue::get(Type::IntTy), this) {
47 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000048 };
Reid Spencer46b002c2004-07-11 17:28:43 +000049}
Reid Spencer060d25d2004-06-29 23:29:38 +000050
Reid Spencer24399722004-07-09 22:21:33 +000051// Provide some details on error
52inline void BytecodeReader::error(std::string err) {
53 err += " (Vers=" ;
54 err += itostr(RevisionNum) ;
55 err += ", Pos=" ;
56 err += itostr(At-MemStart);
57 err += ")";
58 throw err;
59}
60
Reid Spencer060d25d2004-06-29 23:29:38 +000061//===----------------------------------------------------------------------===//
62// Bytecode Reading Methods
63//===----------------------------------------------------------------------===//
64
Reid Spencer04cde2c2004-07-04 11:33:49 +000065/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000066inline bool BytecodeReader::moreInBlock() {
67 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000068}
69
Reid Spencer04cde2c2004-07-04 11:33:49 +000070/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000071inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000072 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000073 error(std::string("Attempt to read past the end of ") + block_name +
74 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000075}
Chris Lattner36392bc2003-10-08 21:18:57 +000076
Reid Spencer04cde2c2004-07-04 11:33:49 +000077/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000078inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000079 if (hasAlignment) {
80 BufPtr Save = At;
81 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000082 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000083 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000084 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000085 error("Ran out of data while aligning!");
86 }
Reid Spencer060d25d2004-06-29 23:29:38 +000087}
88
Reid Spencer04cde2c2004-07-04 11:33:49 +000089/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000090inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000091 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000092 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000093 At += 4;
94 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
95}
96
Reid Spencer04cde2c2004-07-04 11:33:49 +000097/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000098inline unsigned BytecodeReader::read_vbr_uint() {
99 unsigned Shift = 0;
100 unsigned Result = 0;
101 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000102
Reid Spencer060d25d2004-06-29 23:29:38 +0000103 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000104 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000105 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 Result |= (unsigned)((*At++) & 0x7F) << Shift;
107 Shift += 7;
108 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000109 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000110 return Result;
111}
112
Reid Spencer04cde2c2004-07-04 11:33:49 +0000113/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000114inline uint64_t BytecodeReader::read_vbr_uint64() {
115 unsigned Shift = 0;
116 uint64_t Result = 0;
117 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000118
Reid Spencer060d25d2004-06-29 23:29:38 +0000119 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000120 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000121 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000122 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
123 Shift += 7;
124 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000125 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000126 return Result;
127}
128
Reid Spencer04cde2c2004-07-04 11:33:49 +0000129/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000130inline int64_t BytecodeReader::read_vbr_int64() {
131 uint64_t R = read_vbr_uint64();
132 if (R & 1) {
133 if (R != 1)
134 return -(int64_t)(R >> 1);
135 else // There is no such thing as -0 with integers. "-0" really means
136 // 0x8000000000000000.
137 return 1LL << 63;
138 } else
139 return (int64_t)(R >> 1);
140}
141
Reid Spencer04cde2c2004-07-04 11:33:49 +0000142/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000143inline std::string BytecodeReader::read_str() {
144 unsigned Size = read_vbr_uint();
145 const unsigned char *OldAt = At;
146 At += Size;
147 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000148 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000149 return std::string((char*)OldAt, Size);
150}
151
Reid Spencer04cde2c2004-07-04 11:33:49 +0000152/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000153inline void BytecodeReader::read_data(void *Ptr, void *End) {
154 unsigned char *Start = (unsigned char *)Ptr;
155 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000156 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000157 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000158 std::copy(At, At+Amount, Start);
159 At += Amount;
160}
161
Reid Spencer46b002c2004-07-11 17:28:43 +0000162/// Read a float value in little-endian order
163inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000164 /// FIXME: This isn't optimal, it has size problems on some platforms
165 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000166 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000167 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000168}
169
170/// Read a double value in little-endian order
171inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000172 /// FIXME: This isn't optimal, it has size problems on some platforms
173 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000174 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
175 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
176 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
177 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000178 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000179}
180
Reid Spencer04cde2c2004-07-04 11:33:49 +0000181/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000182inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000183 if ( hasLongBlockHeaders ) {
184 Type = read_uint();
185 Size = read_uint();
186 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000187 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000188 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000189 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000190 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000191 Type = BytecodeFormat::ModuleBlockID; break;
192 case BytecodeFormat::Function:
193 Type = BytecodeFormat::FunctionBlockID; break;
194 case BytecodeFormat::ConstantPool:
195 Type = BytecodeFormat::ConstantPoolBlockID; break;
196 case BytecodeFormat::SymbolTable:
197 Type = BytecodeFormat::SymbolTableBlockID; break;
198 case BytecodeFormat::ModuleGlobalInfo:
199 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
200 case BytecodeFormat::GlobalTypePlane:
201 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
202 case BytecodeFormat::InstructionList:
203 Type = BytecodeFormat::InstructionListBlockID; break;
204 case BytecodeFormat::CompactionTable:
205 Type = BytecodeFormat::CompactionTableBlockID; break;
206 case BytecodeFormat::BasicBlock:
207 /// This block type isn't used after version 1.1. However, we have to
208 /// still allow the value in case this is an old bc format file.
209 /// We just let its value creep thru.
210 break;
211 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000212 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000213 break;
214 }
215 } else {
216 Size = read_uint();
217 Type = Size & 0x1F; // mask low order five bits
218 Size >>= 5; // get rid of five low order bits, leaving high 27
219 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000220 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000221 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000222 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000223 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000224 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000225}
226
227
228/// In LLVM 1.2 and before, Types were derived from Value and so they were
229/// written as part of the type planes along with any other Value. In LLVM
230/// 1.3 this changed so that Type does not derive from Value. Consequently,
231/// the BytecodeReader's containers for Values can't contain Types because
232/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000233/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
234/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000235/// the types are always read/written first and then the Values. Furthermore
236/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
237/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
238/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
239/// For LLVM 1.2 and before, this function will decrement the type id by
240/// one to account for the missing Type::TypeTyID enumerator if the value is
241/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
242/// function returns true, otherwise false. This helps detect situations
243/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000244/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000245inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
246 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
247 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000248 TypeId = Type::VoidTyID; // sanitize it
249 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000250 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000251 --TypeId; // shift all planes down because type type plane is missing
252 }
253 return false;
254}
255
256/// Reads a vbr uint to read in a type id and does the necessary
257/// conversion on it by calling sanitizeTypeId.
258/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
259/// @see sanitizeTypeId
260inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
261 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000262 if ( !has32BitTypes )
263 if ( TypeId == 0x00FFFFFF )
264 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000265 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000266}
267
268//===----------------------------------------------------------------------===//
269// IR Lookup Methods
270//===----------------------------------------------------------------------===//
271
Reid Spencer04cde2c2004-07-04 11:33:49 +0000272/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000273inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000274 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000275 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000276 return TyID >= Type::FirstDerivedTyID;
277}
278
Reid Spencer04cde2c2004-07-04 11:33:49 +0000279/// Obtain a type given a typeid and account for things like compaction tables,
280/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000281const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000282 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000283 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000284 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000285
286 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000287 ID -= Type::FirstDerivedTyID;
288
Reid Spencer060d25d2004-06-29 23:29:38 +0000289 if (!CompactionTypes.empty()) {
290 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000291 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000292 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000293 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000294
295 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000296 if (ID < ModuleTypes.size())
297 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000298
Reid Spencer46b002c2004-07-11 17:28:43 +0000299 // Nope, is it a function-level type?
300 ID -= ModuleTypes.size();
301 if (ID < FunctionTypes.size())
302 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000303
Reid Spencer46b002c2004-07-11 17:28:43 +0000304 error("Illegal type reference!");
305 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000306}
307
Reid Spencer04cde2c2004-07-04 11:33:49 +0000308/// Get a sanitized type id. This just makes sure that the \p ID
309/// is both sanitized and not the "type type" of pre-1.3 bytecode.
310/// @see sanitizeTypeId
311inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000312 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000313 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000314 return getType(ID);
315}
316
317/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000318/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000319/// then calls getType to return the type value.
320inline const Type* BytecodeReader::readSanitizedType() {
321 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000322 if (read_typeid(ID))
323 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000324 return getType(ID);
325}
326
327/// Get the slot number associated with a type accounting for primitive
328/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000329unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
330 if (Ty->isPrimitiveType())
331 return Ty->getTypeID();
332
333 // Scan the compaction table for the type if needed.
334 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000335 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
336 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000337 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000338
Chris Lattner45b5dd22004-08-03 23:41:28 +0000339 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000340 }
341
342 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000343 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
344 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000345
346 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000347 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000348 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000349
350 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000351 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000352 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000353 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000354 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000355}
356
Reid Spencer04cde2c2004-07-04 11:33:49 +0000357/// This is just like getType, but when a compaction table is in use, it is
358/// ignored. It also ignores function level types.
359/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000360const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
361 if (Slot < Type::FirstDerivedTyID) {
362 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000363 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000364 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000365 return Ty;
366 }
367 Slot -= Type::FirstDerivedTyID;
368 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000369 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000370 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000371}
372
Reid Spencer04cde2c2004-07-04 11:33:49 +0000373/// This is just like getTypeSlot, but when a compaction table is in use, it
374/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000375unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
376 if (Ty->isPrimitiveType())
377 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000378 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000379 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000380 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000381 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000382 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
383}
384
Misha Brukman8a96c532005-04-21 21:44:41 +0000385/// Retrieve a value of a given type and slot number, possibly creating
386/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000387Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000388 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000389 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000390
Chris Lattner89e02532004-01-18 21:08:15 +0000391 // If there is a compaction table active, it defines the low-level numbers.
392 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000393 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
394 if (Num < CompactionValues[type].size())
395 return CompactionValues[type][Num];
396 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000397 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000398 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000399 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000400
Chris Lattner45b5dd22004-08-03 23:41:28 +0000401 // If the type plane was compactified, figure out the global type ID by
402 // adding the derived type ids and the distance.
403 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
404 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000405
Reid Spencer060d25d2004-06-29 23:29:38 +0000406 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000407 const Type *Ty = getType(type);
408 if (!isa<OpaqueType>(Ty)) {
409 if (Num == 0)
410 return Constant::getNullValue(Ty);
411 --Num;
412 }
Chris Lattner89e02532004-01-18 21:08:15 +0000413 }
414
Chris Lattner52f86d62004-01-20 00:54:06 +0000415 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
416 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000417 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000418 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000419 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000420 }
421
Misha Brukman8a96c532005-04-21 21:44:41 +0000422 if (FunctionValues.size() > type &&
423 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000424 Num < FunctionValues[type]->size())
425 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000426
Chris Lattner74734132002-08-17 22:01:27 +0000427 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000428
Reid Spencer551ccae2004-09-01 22:55:40 +0000429 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000430 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000431 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000432 if (I != ForwardReferences.end() && I->first == KeyValue)
433 return I->second; // We have already created this placeholder
434
Reid Spencer551ccae2004-09-01 22:55:40 +0000435 // If the type exists (it should)
436 if (const Type* Ty = getType(type)) {
437 // Create the place holder
438 Value *Val = new Argument(Ty);
439 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
440 return Val;
441 }
442 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000443}
444
Misha Brukman8a96c532005-04-21 21:44:41 +0000445/// This is just like getValue, but when a compaction table is in use, it
446/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000447/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000448Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
449 if (SlotNo == 0)
450 return Constant::getNullValue(getType(TyID));
451
452 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
453 TyID -= Type::FirstDerivedTyID;
454 if (TyID >= CompactionTypes.size())
455 error("Type ID out of range for compaction table!");
456 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000457 }
458
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000459 --SlotNo;
460
Reid Spencer060d25d2004-06-29 23:29:38 +0000461 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
462 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000463 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
464 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000465 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000466 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000467 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000468 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000469 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000470 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000471 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
472 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000473 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000474 }
475 return ModuleValues[TyID]->getOperand(SlotNo);
476}
477
Reid Spencer04cde2c2004-07-04 11:33:49 +0000478/// Just like getValue, except that it returns a null pointer
479/// only on error. It always returns a constant (meaning that if the value is
480/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000481/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000482/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000483Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
484 if (Value *V = getValue(TypeSlot, Slot, false))
485 if (Constant *C = dyn_cast<Constant>(V))
486 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000487 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000488 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000489 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000490
Chris Lattner389bd042004-12-09 06:19:44 +0000491 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000492 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
493
494 if (I != ConstantFwdRefs.end() && I->first == Key) {
495 return I->second;
496 } else {
497 // Create a placeholder for the constant reference and
498 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000499 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000500
Reid Spencer060d25d2004-06-29 23:29:38 +0000501 // Keep track of the fact that we have a forward ref to recycle it
502 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
503 return C;
504 }
505}
506
507//===----------------------------------------------------------------------===//
508// IR Construction Methods
509//===----------------------------------------------------------------------===//
510
Reid Spencer04cde2c2004-07-04 11:33:49 +0000511/// As values are created, they are inserted into the appropriate place
512/// with this method. The ValueTable argument must be one of ModuleValues
513/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000514unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000515 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000516 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000517 !hasImplicitNull(type) &&
518 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000519
520 if (ValueTab.size() <= type)
521 ValueTab.resize(type+1);
522
523 if (!ValueTab[type]) ValueTab[type] = new ValueList();
524
525 ValueTab[type]->push_back(Val);
526
Chris Lattneraba5ff52005-05-05 20:57:00 +0000527 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000528 return ValueTab[type]->size()-1 + HasOffset;
529}
530
Reid Spencer04cde2c2004-07-04 11:33:49 +0000531/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000532void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000533 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000534 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000535 for (FunctionType::param_iterator It = FT->param_begin();
536 It != FT->param_end(); ++It, ++AI)
537 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
538}
539
540//===----------------------------------------------------------------------===//
541// Bytecode Parsing Methods
542//===----------------------------------------------------------------------===//
543
Reid Spencer04cde2c2004-07-04 11:33:49 +0000544/// This method parses a single instruction. The instruction is
545/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000546/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000547void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000548 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000549 BufPtr SaveAt = At;
550
551 // Clear instruction data
552 Oprnds.clear();
553 unsigned iType = 0;
554 unsigned Opcode = 0;
555 unsigned Op = read_uint();
556
557 // bits Instruction format: Common to all formats
558 // --------------------------
559 // 01-00: Opcode type, fixed to 1.
560 // 07-02: Opcode
561 Opcode = (Op >> 2) & 63;
562 Oprnds.resize((Op >> 0) & 03);
563
564 // Extract the operands
565 switch (Oprnds.size()) {
566 case 1:
567 // bits Instruction format:
568 // --------------------------
569 // 19-08: Resulting type plane
570 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
571 //
572 iType = (Op >> 8) & 4095;
573 Oprnds[0] = (Op >> 20) & 4095;
574 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
575 Oprnds.resize(0);
576 break;
577 case 2:
578 // bits Instruction format:
579 // --------------------------
580 // 15-08: Resulting type plane
581 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000582 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000583 //
584 iType = (Op >> 8) & 255;
585 Oprnds[0] = (Op >> 16) & 255;
586 Oprnds[1] = (Op >> 24) & 255;
587 break;
588 case 3:
589 // bits Instruction format:
590 // --------------------------
591 // 13-08: Resulting type plane
592 // 19-14: Operand #1
593 // 25-20: Operand #2
594 // 31-26: Operand #3
595 //
596 iType = (Op >> 8) & 63;
597 Oprnds[0] = (Op >> 14) & 63;
598 Oprnds[1] = (Op >> 20) & 63;
599 Oprnds[2] = (Op >> 26) & 63;
600 break;
601 case 0:
602 At -= 4; // Hrm, try this again...
603 Opcode = read_vbr_uint();
604 Opcode >>= 2;
605 iType = read_vbr_uint();
606
607 unsigned NumOprnds = read_vbr_uint();
608 Oprnds.resize(NumOprnds);
609
610 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000611 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000612
613 for (unsigned i = 0; i != NumOprnds; ++i)
614 Oprnds[i] = read_vbr_uint();
615 align32();
616 break;
617 }
618
Reid Spencer04cde2c2004-07-04 11:33:49 +0000619 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000620
Reid Spencer46b002c2004-07-11 17:28:43 +0000621 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000622 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000623
624 // Declare the resulting instruction we'll build.
625 Instruction *Result = 0;
626
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000627 // If this is a bytecode format that did not include the unreachable
628 // instruction, bump up all opcodes numbers to make space.
629 if (hasNoUnreachableInst) {
630 if (Opcode >= Instruction::Unreachable &&
631 Opcode < 62) {
632 ++Opcode;
633 }
634 }
635
Reid Spencer060d25d2004-06-29 23:29:38 +0000636 // Handle binary operators
637 if (Opcode >= Instruction::BinaryOpsBegin &&
638 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
639 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
640 getValue(iType, Oprnds[0]),
641 getValue(iType, Oprnds[1]));
642
643 switch (Opcode) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000644 default:
645 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000646 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000647 break;
648 case Instruction::VAArg:
Misha Brukman8a96c532005-04-21 21:44:41 +0000649 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000650 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000651 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000652 case 32: { //VANext_old
653 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
654 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
655
656 //b = vanext a, t ->
657 //foo = alloca 1 of t
658 //bar = vacopy a
659 //store bar -> foo
660 //tmp = vaarg foo, t
661 //b = load foo
662 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
663 BB->getInstList().push_back(foo);
664 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
665 BB->getInstList().push_back(bar);
666 BB->getInstList().push_back(new StoreInst(bar, foo));
667 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
668 BB->getInstList().push_back(tmp);
669 Result = new LoadInst(foo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000670 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000671 }
672 case 33: { //VAArg_old
673 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
674 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
675
Jeff Cohen00b168892005-07-27 06:12:32 +0000676 //b = vaarg a, t ->
Andrew Lenharth558bc882005-06-18 18:34:52 +0000677 //foo = alloca 1 of t
Jeff Cohen00b168892005-07-27 06:12:32 +0000678 //bar = vacopy a
Andrew Lenharth558bc882005-06-18 18:34:52 +0000679 //store bar -> foo
680 //b = vaarg foo, t
681 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
682 BB->getInstList().push_back(foo);
683 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
684 BB->getInstList().push_back(bar);
685 BB->getInstList().push_back(new StoreInst(bar, foo));
686 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
687 break;
688 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000689 case Instruction::Cast:
Misha Brukman8a96c532005-04-21 21:44:41 +0000690 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000691 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000692 break;
693 case Instruction::Select:
694 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
695 getValue(iType, Oprnds[1]),
696 getValue(iType, Oprnds[2]));
697 break;
698 case Instruction::PHI: {
699 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000700 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000701
702 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000703 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000704 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
705 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
706 Result = PN;
707 break;
708 }
709
710 case Instruction::Shl:
711 case Instruction::Shr:
712 Result = new ShiftInst((Instruction::OtherOps)Opcode,
713 getValue(iType, Oprnds[0]),
714 getValue(Type::UByteTyID, Oprnds[1]));
715 break;
716 case Instruction::Ret:
717 if (Oprnds.size() == 0)
718 Result = new ReturnInst();
719 else if (Oprnds.size() == 1)
720 Result = new ReturnInst(getValue(iType, Oprnds[0]));
721 else
Reid Spencer24399722004-07-09 22:21:33 +0000722 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000723 break;
724
725 case Instruction::Br:
726 if (Oprnds.size() == 1)
727 Result = new BranchInst(getBasicBlock(Oprnds[0]));
728 else if (Oprnds.size() == 3)
Misha Brukman8a96c532005-04-21 21:44:41 +0000729 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000730 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000731 else
Reid Spencer24399722004-07-09 22:21:33 +0000732 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000733 break;
734 case Instruction::Switch: {
735 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000736 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000737
738 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000739 getBasicBlock(Oprnds[1]),
740 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000741 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000742 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000743 getBasicBlock(Oprnds[i+1]));
744 Result = I;
745 break;
746 }
747
Chris Lattnerdee199f2005-05-06 22:34:01 +0000748 case 58: // Call with extra operand for calling conv
749 case 59: // tail call, Fast CC
750 case 60: // normal call, Fast CC
751 case 61: // tail call, C Calling Conv
752 case Instruction::Call: { // Normal Call, C Calling Convention
Reid Spencer060d25d2004-06-29 23:29:38 +0000753 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000754 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000755
756 Value *F = getValue(iType, Oprnds[0]);
757
Chris Lattnerdee199f2005-05-06 22:34:01 +0000758 unsigned CallingConv = CallingConv::C;
759 bool isTailCall = false;
760
761 if (Opcode == 61 || Opcode == 59)
762 isTailCall = true;
763
Reid Spencer060d25d2004-06-29 23:29:38 +0000764 // Check to make sure we have a pointer to function type
765 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000766 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000767 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000768 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000769
770 std::vector<Value *> Params;
771 if (!FTy->isVarArg()) {
772 FunctionType::param_iterator It = FTy->param_begin();
773
Chris Lattnerdee199f2005-05-06 22:34:01 +0000774 if (Opcode == 58) {
775 isTailCall = Oprnds.back() & 1;
776 CallingConv = Oprnds.back() >> 1;
777 Oprnds.pop_back();
778 } else if (Opcode == 59 || Opcode == 60)
779 CallingConv = CallingConv::Fast;
780
Reid Spencer060d25d2004-06-29 23:29:38 +0000781 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
782 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000783 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000784 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
785 }
786 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000787 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000788 } else {
789 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
790
791 unsigned FirstVariableOperand;
792 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000793 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000794
795 // Read all of the fixed arguments
796 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
797 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000798
Reid Spencer060d25d2004-06-29 23:29:38 +0000799 FirstVariableOperand = FTy->getNumParams();
800
Misha Brukman8a96c532005-04-21 21:44:41 +0000801 if ((Oprnds.size()-FirstVariableOperand) & 1)
Chris Lattner4a242b32004-10-14 01:39:18 +0000802 error("Invalid call instruction!"); // Must be pairs of type/value
Misha Brukman8a96c532005-04-21 21:44:41 +0000803
804 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000805 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000806 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
807 }
808
809 Result = new CallInst(F, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000810 if (isTailCall) cast<CallInst>(Result)->setTailCall();
811 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000812 break;
813 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000814 case 56: // Invoke with encoded CC
815 case 57: // Invoke Fast CC
816 case Instruction::Invoke: { // Invoke C CC
Misha Brukman8a96c532005-04-21 21:44:41 +0000817 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000818 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000819 Value *F = getValue(iType, Oprnds[0]);
820
821 // Check to make sure we have a pointer to function type
822 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000823 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000824 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000825 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000826 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000827 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000828
829 std::vector<Value *> Params;
830 BasicBlock *Normal, *Except;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000831 unsigned CallingConv = CallingConv::C;
832
833 if (Opcode == 57)
834 CallingConv = CallingConv::Fast;
835 else if (Opcode == 56) {
836 CallingConv = Oprnds.back();
837 Oprnds.pop_back();
838 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000839
840 if (!FTy->isVarArg()) {
841 Normal = getBasicBlock(Oprnds[1]);
842 Except = getBasicBlock(Oprnds[2]);
843
844 FunctionType::param_iterator It = FTy->param_begin();
845 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
846 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000847 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000848 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
849 }
850 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000851 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000852 } else {
853 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
854
855 Normal = getBasicBlock(Oprnds[0]);
856 Except = getBasicBlock(Oprnds[1]);
Misha Brukman8a96c532005-04-21 21:44:41 +0000857
Reid Spencer060d25d2004-06-29 23:29:38 +0000858 unsigned FirstVariableArgument = FTy->getNumParams()+2;
859 for (unsigned i = 2; i != FirstVariableArgument; ++i)
860 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
861 Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000862
Reid Spencer060d25d2004-06-29 23:29:38 +0000863 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000864 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000865
866 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
867 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
868 }
869
870 Result = new InvokeInst(F, Normal, Except, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000871 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000872 break;
873 }
874 case Instruction::Malloc:
Misha Brukman8a96c532005-04-21 21:44:41 +0000875 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000876 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000877 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000878 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000879
880 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
881 Oprnds.size() ? getValue(Type::UIntTyID,
882 Oprnds[0]) : 0);
883 break;
884
885 case Instruction::Alloca:
Misha Brukman8a96c532005-04-21 21:44:41 +0000886 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000887 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000888 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000889 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000890
891 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Misha Brukman8a96c532005-04-21 21:44:41 +0000892 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000893 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000894 break;
895 case Instruction::Free:
896 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000897 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000898 Result = new FreeInst(getValue(iType, Oprnds[0]));
899 break;
900 case Instruction::GetElementPtr: {
901 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000902 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000903
904 std::vector<Value*> Idx;
905
906 const Type *NextTy = InstTy;
907 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
908 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Misha Brukman8a96c532005-04-21 21:44:41 +0000909 if (!TopTy)
910 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000911
912 unsigned ValIdx = Oprnds[i];
913 unsigned IdxTy = 0;
914 if (!hasRestrictedGEPTypes) {
915 // Struct indices are always uints, sequential type indices can be any
916 // of the 32 or 64-bit integer types. The actual choice of type is
917 // encoded in the low two bits of the slot number.
918 if (isa<StructType>(TopTy))
919 IdxTy = Type::UIntTyID;
920 else {
921 switch (ValIdx & 3) {
922 default:
923 case 0: IdxTy = Type::UIntTyID; break;
924 case 1: IdxTy = Type::IntTyID; break;
925 case 2: IdxTy = Type::ULongTyID; break;
926 case 3: IdxTy = Type::LongTyID; break;
927 }
928 ValIdx >>= 2;
929 }
930 } else {
931 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
932 }
933
934 Idx.push_back(getValue(IdxTy, ValIdx));
935
936 // Convert ubyte struct indices into uint struct indices.
937 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
938 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
939 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
940
941 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
942 }
943
944 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
945 break;
946 }
947
948 case 62: // volatile load
949 case Instruction::Load:
950 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000951 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000952 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
953 break;
954
Misha Brukman8a96c532005-04-21 21:44:41 +0000955 case 63: // volatile store
Reid Spencer060d25d2004-06-29 23:29:38 +0000956 case Instruction::Store: {
957 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000958 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000959
960 Value *Ptr = getValue(iType, Oprnds[1]);
961 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
962 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
963 Opcode == 63);
964 break;
965 }
966 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000967 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000968 Result = new UnwindInst();
969 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000970 case Instruction::Unreachable:
971 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
972 Result = new UnreachableInst();
973 break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000974 } // end switch(Opcode)
Reid Spencer060d25d2004-06-29 23:29:38 +0000975
976 unsigned TypeSlot;
977 if (Result->getType() == InstTy)
978 TypeSlot = iType;
979 else
980 TypeSlot = getTypeSlot(Result->getType());
981
982 insertValue(Result, TypeSlot, FunctionValues);
983 BB->getInstList().push_back(Result);
984}
985
Reid Spencer04cde2c2004-07-04 11:33:49 +0000986/// Get a particular numbered basic block, which might be a forward reference.
987/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +0000988/// in a clean manner. This function is used when constructing phi, br, switch,
989/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +0000990/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000991BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000992 // Make sure there is room in the table...
993 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
994
995 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
996 // has already created this block, or if the forward reference has already
997 // been created.
998 if (ParsedBasicBlocks[ID])
999 return ParsedBasicBlocks[ID];
1000
1001 // Otherwise, the basic block has not yet been created. Do so and add it to
1002 // the ParsedBasicBlocks list.
1003 return ParsedBasicBlocks[ID] = new BasicBlock();
1004}
1005
Misha Brukman8a96c532005-04-21 21:44:41 +00001006/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001007/// This method reads in one of the basicblock packets. This method is not used
1008/// for bytecode files after LLVM 1.0
1009/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001010BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1011 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001012
1013 BasicBlock *BB = 0;
1014
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001015 if (ParsedBasicBlocks.size() == BlockNo)
1016 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1017 else if (ParsedBasicBlocks[BlockNo] == 0)
1018 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1019 else
1020 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001021
Reid Spencer060d25d2004-06-29 23:29:38 +00001022 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001023 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001024 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001025
Reid Spencer46b002c2004-07-11 17:28:43 +00001026 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001027 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001028}
1029
Reid Spencer04cde2c2004-07-04 11:33:49 +00001030/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001031/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001032/// in order to avoid per-basic-block overhead.
1033/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001034unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001035 unsigned BlockNo = 0;
1036 std::vector<unsigned> Args;
1037
Reid Spencer46b002c2004-07-11 17:28:43 +00001038 while (moreInBlock()) {
1039 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001040 BasicBlock *BB;
1041 if (ParsedBasicBlocks.size() == BlockNo)
1042 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1043 else if (ParsedBasicBlocks[BlockNo] == 0)
1044 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1045 else
1046 BB = ParsedBasicBlocks[BlockNo];
1047 ++BlockNo;
1048 F->getBasicBlockList().push_back(BB);
1049
1050 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001051 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001052 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001053
1054 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001055 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001056
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001058 }
1059
1060 return BlockNo;
1061}
1062
Reid Spencer04cde2c2004-07-04 11:33:49 +00001063/// Parse a symbol table. This works for both module level and function
1064/// level symbol tables. For function level symbol tables, the CurrentFunction
1065/// parameter must be non-zero and the ST parameter must correspond to
1066/// CurrentFunction's symbol table. For Module level symbol tables, the
1067/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001068void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001069 SymbolTable *ST) {
1070 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001071
Chris Lattner39cacce2003-10-10 05:43:47 +00001072 // Allow efficient basic block lookup by number.
1073 std::vector<BasicBlock*> BBMap;
1074 if (CurrentFunction)
1075 for (Function::iterator I = CurrentFunction->begin(),
1076 E = CurrentFunction->end(); I != E; ++I)
1077 BBMap.push_back(I);
1078
Reid Spencer04cde2c2004-07-04 11:33:49 +00001079 /// In LLVM 1.3 we write types separately from values so
1080 /// The types are always first in the symbol table. This is
1081 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001082 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001083 // Symtab block header: [num entries]
1084 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001085 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001086 // Symtab entry: [def slot #][name]
1087 unsigned slot = read_vbr_uint();
1088 std::string Name = read_str();
1089 const Type* T = getType(slot);
1090 ST->insert(Name, T);
1091 }
1092 }
1093
Reid Spencer46b002c2004-07-11 17:28:43 +00001094 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001095 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001096 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001097 unsigned Typ = 0;
1098 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001099 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001100
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001101 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001102 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001103 unsigned slot = read_vbr_uint();
1104 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001105
Reid Spencer04cde2c2004-07-04 11:33:49 +00001106 // if we're reading a pre 1.3 bytecode file and the type plane
1107 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001108 if (isTypeType) {
1109 const Type* T = getType(slot);
1110 if (T == 0)
1111 error("Failed type look-up for name '" + Name + "'");
1112 ST->insert(Name, T);
1113 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001114 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001115 Value *V = 0;
1116 if (Typ == Type::LabelTyID) {
1117 if (slot < BBMap.size())
1118 V = BBMap[slot];
1119 } else {
1120 V = getValue(Typ, slot, false); // Find mapping...
1121 }
1122 if (V == 0)
1123 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001124 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001125 }
Chris Lattner00950542001-06-06 20:29:01 +00001126 }
1127 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001128 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001129 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001130}
1131
Misha Brukman8a96c532005-04-21 21:44:41 +00001132/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001133void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001134 for (unsigned i = 0; i != NumEntries; ++i) {
1135 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001136 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001137 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001138 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001139 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001140 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001141 }
1142}
1143
1144/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001145void BytecodeReader::ParseCompactionTable() {
1146
Reid Spencer46b002c2004-07-11 17:28:43 +00001147 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001148 if (Handler) Handler->handleCompactionTableBegin();
1149
Misha Brukman8a96c532005-04-21 21:44:41 +00001150 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001151 // we always write them first in the compaction table
1152 // because they can't occupy a "type plane" where the
1153 // Values reside.
1154 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001155 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001156 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001157 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001158
Reid Spencer46b002c2004-07-11 17:28:43 +00001159 // Compaction tables live in separate blocks so we have to loop
1160 // until we've read the whole thing.
1161 while (moreInBlock()) {
1162 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001163 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001164 unsigned Ty = 0;
1165 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001166
Reid Spencer46b002c2004-07-11 17:28:43 +00001167 // Decode the type from value read in. Most compaction table
1168 // planes will have one or two entries in them. If that's the
1169 // case then the length is encoded in the bottom two bits and
1170 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001171 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001172 // In this case, both low-order bits are set (value 3). This
1173 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001174 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001175 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001176 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001177 // In this case, the low-order bits specify the number of entries
1178 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001179 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001180 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001181 NumEntries &= 3;
1182 }
1183
Reid Spencer04cde2c2004-07-04 11:33:49 +00001184 // if we're reading a pre 1.3 bytecode file and the type plane
1185 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001186 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001187 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001188 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001189 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001190 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001191 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001192
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001193 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001194 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001195 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001196
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001197 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001198 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001199
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001200 // Push the implicit zero.
1201 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001202
1203 // Read in each of the entries, put them in the compaction table
1204 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001205 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001206 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001207 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001208 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001209 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001210 }
1211 }
1212 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001213 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001214 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001215}
Misha Brukman8a96c532005-04-21 21:44:41 +00001216
Reid Spencer46b002c2004-07-11 17:28:43 +00001217// Parse a single type. The typeid is read in first. If its a primitive type
1218// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001219// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001220// definition.
1221const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001222 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001223 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001224 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001225
1226 const Type *Result = 0;
1227 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1228 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001229
Reid Spencer060d25d2004-06-29 23:29:38 +00001230 switch (PrimType) {
1231 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001232 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001233
1234 unsigned NumParams = read_vbr_uint();
1235
1236 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001237 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001238 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001239
1240 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1241 if (isVarArg) Params.pop_back();
1242
1243 Result = FunctionType::get(RetType, Params, isVarArg);
1244 break;
1245 }
1246 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001247 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001248 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001249 Result = ArrayType::get(ElementType, NumElements);
1250 break;
1251 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001252 case Type::PackedTyID: {
1253 const Type *ElementType = readSanitizedType();
1254 unsigned NumElements = read_vbr_uint();
1255 Result = PackedType::get(ElementType, NumElements);
1256 break;
1257 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001258 case Type::StructTyID: {
1259 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001260 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001261 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001262 error("Invalid element type (type type) for structure!");
1263
Reid Spencer060d25d2004-06-29 23:29:38 +00001264 while (Typ) { // List is terminated by void/0 typeid
1265 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001266 if (read_typeid(Typ))
1267 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001268 }
1269
1270 Result = StructType::get(Elements);
1271 break;
1272 }
1273 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001274 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001275 break;
1276 }
1277
1278 case Type::OpaqueTyID: {
1279 Result = OpaqueType::get();
1280 break;
1281 }
1282
1283 default:
Reid Spencer24399722004-07-09 22:21:33 +00001284 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001285 break;
1286 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001287 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001288 return Result;
1289}
1290
Reid Spencer5b472d92004-08-21 20:49:23 +00001291// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001292// types. We know that recursive types will only reference the current slab of
1293// values in the type plane, but they can forward reference types before they
1294// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1295// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1296// this ugly problem, we pessimistically insert an opaque type for each type we
1297// are about to read. This means that forward references will resolve to
1298// something and when we reread the type later, we can replace the opaque type
1299// with a new resolved concrete type.
1300//
Reid Spencer46b002c2004-07-11 17:28:43 +00001301void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001302 assert(Tab.size() == 0 && "should not have read type constants in before!");
1303
1304 // Insert a bunch of opaque types to be resolved later...
1305 Tab.reserve(NumEntries);
1306 for (unsigned i = 0; i != NumEntries; ++i)
1307 Tab.push_back(OpaqueType::get());
1308
Misha Brukman8a96c532005-04-21 21:44:41 +00001309 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001310 Handler->handleTypeList(NumEntries);
1311
Reid Spencer060d25d2004-06-29 23:29:38 +00001312 // Loop through reading all of the types. Forward types will make use of the
1313 // opaque types just inserted.
1314 //
1315 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001316 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001317 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001318 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001319 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001320
Misha Brukman8a96c532005-04-21 21:44:41 +00001321 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001322 // the opaque type we previously inserted with the new concrete value. This
1323 // approach helps with forward references to types. The refinement from the
1324 // abstract (opaque) type to the new type causes all uses of the abstract
1325 // type to use the concrete type (NewTy). This will also cause the opaque
1326 // type to be deleted.
1327 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1328
1329 // This should have replaced the old opaque type with the new type in the
1330 // value table... or with a preexisting type that was already in the system.
1331 // Let's just make sure it did.
1332 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1333 }
1334}
1335
Reid Spencer04cde2c2004-07-04 11:33:49 +00001336/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001337Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001338 // We must check for a ConstantExpr before switching by type because
1339 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001340 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001341 // 0 if not expr; numArgs if is expr
1342 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001343
Reid Spencer060d25d2004-06-29 23:29:38 +00001344 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001345 // 'undef' is encoded with 'exprnumargs' == 1.
1346 if (!hasNoUndefValue)
1347 if (--isExprNumArgs == 0)
1348 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001349
Reid Spencer060d25d2004-06-29 23:29:38 +00001350 // FIXME: Encoding of constant exprs could be much more compact!
1351 std::vector<Constant*> ArgVec;
1352 ArgVec.reserve(isExprNumArgs);
1353 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001354
1355 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1356 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001357
Reid Spencer060d25d2004-06-29 23:29:38 +00001358 // Read the slot number and types of each of the arguments
1359 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1360 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001361 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001362 if (read_typeid(ArgTypeSlot))
1363 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001364
Reid Spencer060d25d2004-06-29 23:29:38 +00001365 // Get the arg value from its slot if it exists, otherwise a placeholder
1366 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1367 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001368
Reid Spencer060d25d2004-06-29 23:29:38 +00001369 // Construct a ConstantExpr of the appropriate kind
1370 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001371 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001372 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001373
Reid Spencer060d25d2004-06-29 23:29:38 +00001374 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001375 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001376 return Result;
1377 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1378 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1379
1380 if (hasRestrictedGEPTypes) {
1381 const Type *BaseTy = ArgVec[0]->getType();
1382 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1383 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1384 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1385 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1386 if (isa<StructType>(*GTI)) {
1387 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001388 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001389 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1390 }
1391 }
1392
1393 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001395 return Result;
1396 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001397 if (ArgVec.size() != 3)
1398 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001399 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001400 ArgVec[2]);
1401 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001402 return Result;
1403 } else { // All other 2-operand expressions
1404 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001405 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001406 return Result;
1407 }
1408 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001409
Reid Spencer060d25d2004-06-29 23:29:38 +00001410 // Ok, not an ConstantExpr. We now know how to read the given type...
1411 const Type *Ty = getType(TypeID);
1412 switch (Ty->getTypeID()) {
1413 case Type::BoolTyID: {
1414 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001415 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001416 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001417 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001418 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001419 return Result;
1420 }
1421
1422 case Type::UByteTyID: // Unsigned integer types...
1423 case Type::UShortTyID:
1424 case Type::UIntTyID: {
1425 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001426 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001427 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001428 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001429 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001430 return Result;
1431 }
1432
1433 case Type::ULongTyID: {
1434 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001435 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001436 return Result;
1437 }
1438
1439 case Type::SByteTyID: // Signed integer types...
1440 case Type::ShortTyID:
1441 case Type::IntTyID: {
1442 case Type::LongTyID:
1443 int64_t Val = read_vbr_int64();
Misha Brukman8a96c532005-04-21 21:44:41 +00001444 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001445 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001446 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001447 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001448 return Result;
1449 }
1450
1451 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001452 float Val;
1453 read_float(Val);
1454 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001455 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001456 return Result;
1457 }
1458
1459 case Type::DoubleTyID: {
1460 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001461 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001463 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001464 return Result;
1465 }
1466
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 case Type::ArrayTyID: {
1468 const ArrayType *AT = cast<ArrayType>(Ty);
1469 unsigned NumElements = AT->getNumElements();
1470 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1471 std::vector<Constant*> Elements;
1472 Elements.reserve(NumElements);
1473 while (NumElements--) // Read all of the elements of the constant.
1474 Elements.push_back(getConstantValue(TypeSlot,
1475 read_vbr_uint()));
1476 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001477 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001478 return Result;
1479 }
1480
1481 case Type::StructTyID: {
1482 const StructType *ST = cast<StructType>(Ty);
1483
1484 std::vector<Constant *> Elements;
1485 Elements.reserve(ST->getNumElements());
1486 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1487 Elements.push_back(getConstantValue(ST->getElementType(i),
1488 read_vbr_uint()));
1489
1490 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001491 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001492 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001493 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001494
Brian Gaeke715c90b2004-08-20 06:00:58 +00001495 case Type::PackedTyID: {
1496 const PackedType *PT = cast<PackedType>(Ty);
1497 unsigned NumElements = PT->getNumElements();
1498 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1499 std::vector<Constant*> Elements;
1500 Elements.reserve(NumElements);
1501 while (NumElements--) // Read all of the elements of the constant.
1502 Elements.push_back(getConstantValue(TypeSlot,
1503 read_vbr_uint()));
1504 Constant* Result = ConstantPacked::get(PT, Elements);
1505 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1506 return Result;
1507 }
1508
Chris Lattner638c3812004-11-19 16:24:05 +00001509 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001510 const PointerType *PT = cast<PointerType>(Ty);
1511 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001512
Reid Spencer060d25d2004-06-29 23:29:38 +00001513 // Check to see if we have already read this global variable...
1514 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001515 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001516 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1517 if (!GV) error("GlobalValue not in ValueTable!");
1518 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1519 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001520 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001521 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001522 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001523 }
1524
1525 default:
Reid Spencer24399722004-07-09 22:21:33 +00001526 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001527 Ty->getDescription());
1528 break;
1529 }
Reid Spencer24399722004-07-09 22:21:33 +00001530 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001531}
1532
Misha Brukman8a96c532005-04-21 21:44:41 +00001533/// Resolve references for constants. This function resolves the forward
1534/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001535/// replaceAllUsesWith method of Value class to substitute the placeholder
1536/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001537void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1538 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001539 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001540 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001541 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001542
Chris Lattner29b789b2003-11-19 17:27:18 +00001543 Value *PH = I->second; // Get the placeholder...
1544 PH->replaceAllUsesWith(NewV);
1545 delete PH; // Delete the old placeholder
1546 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001547}
1548
Reid Spencer04cde2c2004-07-04 11:33:49 +00001549/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001550void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1551 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001552 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001553 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001554 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001555 const Type *Ty = getType(Typ);
1556 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001557 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001558
Reid Spencer060d25d2004-06-29 23:29:38 +00001559 const ArrayType *ATy = cast<ArrayType>(Ty);
1560 if (ATy->getElementType() != Type::SByteTy &&
1561 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001562 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001563
Reid Spencer060d25d2004-06-29 23:29:38 +00001564 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001565 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001566 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001567
Reid Spencer060d25d2004-06-29 23:29:38 +00001568 std::vector<Constant*> Elements(ATy->getNumElements());
1569 if (ATy->getElementType() == Type::SByteTy)
1570 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1571 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1572 else
1573 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1574 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001575
Reid Spencer060d25d2004-06-29 23:29:38 +00001576 // Create the constant, inserting it as needed.
1577 Constant *C = ConstantArray::get(ATy, Elements);
1578 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001579 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001580 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001581 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001582}
1583
Reid Spencer04cde2c2004-07-04 11:33:49 +00001584/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001585void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001586 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001587 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001588 if (Handler) Handler->handleGlobalConstantsBegin();
1589
1590 /// In LLVM 1.3 Type does not derive from Value so the types
1591 /// do not occupy a plane. Consequently, we read the types
1592 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001593 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001594 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001595 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001596 }
1597
Reid Spencer46b002c2004-07-11 17:28:43 +00001598 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001599 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001600 unsigned Typ = 0;
1601 bool isTypeType = read_typeid(Typ);
1602
1603 /// In LLVM 1.2 and before, Types were written to the
1604 /// bytecode file in the "Type Type" plane (#12).
1605 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001606 if (isTypeType) {
1607 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001608 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001609 /// Use of Type::VoidTyID is a misnomer. It actually means
1610 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001611 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1612 ParseStringConstants(NumEntries, Tab);
1613 } else {
1614 for (unsigned i = 0; i < NumEntries; ++i) {
1615 Constant *C = ParseConstantValue(Typ);
1616 assert(C && "ParseConstantValue returned NULL!");
1617 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001618
Reid Spencer060d25d2004-06-29 23:29:38 +00001619 // If we are reading a function constant table, make sure that we adjust
1620 // the slot number to be the real global constant number.
1621 //
1622 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1623 ModuleValues[Typ])
1624 Slot += ModuleValues[Typ]->size();
Chris Lattner389bd042004-12-09 06:19:44 +00001625 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001626 }
1627 }
1628 }
Chris Lattner02dce162004-12-04 05:28:27 +00001629
1630 // After we have finished parsing the constant pool, we had better not have
1631 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001632 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001633 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001634 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001635 error(utostr(ConstantFwdRefs.size()) +
1636 " unresolved constant reference exist. First one is '" +
1637 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001638 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001639 }
Chris Lattner02dce162004-12-04 05:28:27 +00001640
Reid Spencer060d25d2004-06-29 23:29:38 +00001641 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001642 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001643}
Chris Lattner00950542001-06-06 20:29:01 +00001644
Reid Spencer04cde2c2004-07-04 11:33:49 +00001645/// Parse the contents of a function. Note that this function can be
1646/// called lazily by materializeFunction
1647/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001648void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001649
1650 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001651 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1652
Reid Spencer060d25d2004-06-29 23:29:38 +00001653 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001654 switch (LinkageType) {
1655 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1656 case 1: Linkage = GlobalValue::WeakLinkage; break;
1657 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1658 case 3: Linkage = GlobalValue::InternalLinkage; break;
1659 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001660 default:
Reid Spencer24399722004-07-09 22:21:33 +00001661 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001662 Linkage = GlobalValue::InternalLinkage;
1663 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001664 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001665
Reid Spencer46b002c2004-07-11 17:28:43 +00001666 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001667 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001668
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001669 // Keep track of how many basic blocks we have read in...
1670 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001671 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001672
Reid Spencer060d25d2004-06-29 23:29:38 +00001673 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001674 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001675 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001676 BufPtr OldAt = At;
1677 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001678
1679 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001680 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001681 if (!InsertedArguments) {
1682 // Insert arguments into the value table before we parse the first basic
1683 // block in the function, but after we potentially read in the
1684 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001685 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001686 InsertedArguments = true;
1687 }
1688
Reid Spencer04cde2c2004-07-04 11:33:49 +00001689 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001690 break;
1691
Reid Spencerad89bd62004-07-25 18:07:36 +00001692 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001693 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001694 break;
1695
Chris Lattner00950542001-06-06 20:29:01 +00001696 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001697 if (!InsertedArguments) {
1698 // Insert arguments into the value table before we parse the first basic
1699 // block in the function, but after we potentially read in the
1700 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001701 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001702 InsertedArguments = true;
1703 }
1704
Reid Spencer060d25d2004-06-29 23:29:38 +00001705 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001706 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001707 break;
1708 }
1709
Reid Spencerad89bd62004-07-25 18:07:36 +00001710 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001711 // Insert arguments into the value table before we parse the instruction
1712 // list for the function, but after we potentially read in the compaction
1713 // table.
1714 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001715 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001716 InsertedArguments = true;
1717 }
1718
Misha Brukman8a96c532005-04-21 21:44:41 +00001719 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001720 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001721 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001722 break;
1723 }
1724
Reid Spencerad89bd62004-07-25 18:07:36 +00001725 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001726 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001727 break;
1728
1729 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001730 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001731 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001732 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001733 break;
1734 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001735 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001736
Misha Brukman12c29d12003-09-22 23:38:23 +00001737 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001738 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001739 }
1740
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001741 // Make sure there were no references to non-existant basic blocks.
1742 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001743 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001744
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001745 ParsedBasicBlocks.clear();
1746
Chris Lattner97330cf2003-10-09 23:10:14 +00001747 // Resolve forward references. Replace any uses of a forward reference value
1748 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001749 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001750 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1751 I = ForwardReferences.begin();
1752 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001753 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001754 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001755 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001756 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001757 }
Chris Lattner00950542001-06-06 20:29:01 +00001758
Misha Brukman12c29d12003-09-22 23:38:23 +00001759 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001760 FunctionTypes.clear();
1761 CompactionTypes.clear();
1762 CompactionValues.clear();
1763 freeTable(FunctionValues);
1764
Reid Spencer04cde2c2004-07-04 11:33:49 +00001765 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001766}
1767
Reid Spencer04cde2c2004-07-04 11:33:49 +00001768/// This function parses LLVM functions lazily. It obtains the type of the
1769/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001770/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001771/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001772void BytecodeReader::ParseFunctionLazily() {
1773 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001774 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001775
Reid Spencer060d25d2004-06-29 23:29:38 +00001776 Function *Func = FunctionSignatureList.back();
1777 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001778
Reid Spencer060d25d2004-06-29 23:29:38 +00001779 // Save the information for future reading of the function
1780 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001781
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001782 // This function has a body but it's not loaded so it appears `External'.
1783 // Mark it as a `Ghost' instead to notify the users that it has a body.
1784 Func->setLinkage(GlobalValue::GhostLinkage);
1785
Reid Spencer060d25d2004-06-29 23:29:38 +00001786 // Pretend we've `parsed' this function
1787 At = BlockEnd;
1788}
Chris Lattner89e02532004-01-18 21:08:15 +00001789
Misha Brukman8a96c532005-04-21 21:44:41 +00001790/// The ParserFunction method lazily parses one function. Use this method to
1791/// casue the parser to parse a specific function in the module. Note that
1792/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001793/// ParseAllFunctionBodies.
1794/// @see ParseAllFunctionBodies
1795/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001796void BytecodeReader::ParseFunction(Function* Func) {
1797 // Find {start, end} pointers and slot in the map. If not there, we're done.
1798 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001799
Reid Spencer060d25d2004-06-29 23:29:38 +00001800 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001801 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001802 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001803 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001804 }
1805
Reid Spencer060d25d2004-06-29 23:29:38 +00001806 BlockStart = At = Fi->second.Buf;
1807 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001808 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001809
1810 LazyFunctionLoadMap.erase(Fi);
1811
Reid Spencer46b002c2004-07-11 17:28:43 +00001812 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001813}
1814
Reid Spencer04cde2c2004-07-04 11:33:49 +00001815/// The ParseAllFunctionBodies method parses through all the previously
1816/// unparsed functions in the bytecode file. If you want to completely parse
1817/// a bytecode file, this method should be called after Parsebytecode because
1818/// Parsebytecode only records the locations in the bytecode file of where
1819/// the function definitions are located. This function uses that information
1820/// to materialize the functions.
1821/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001822void BytecodeReader::ParseAllFunctionBodies() {
1823 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1824 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001825
Reid Spencer46b002c2004-07-11 17:28:43 +00001826 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001827 Function* Func = Fi->first;
1828 BlockStart = At = Fi->second.Buf;
1829 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001830 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001831 ++Fi;
1832 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001833 LazyFunctionLoadMap.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001834}
Chris Lattner89e02532004-01-18 21:08:15 +00001835
Reid Spencer04cde2c2004-07-04 11:33:49 +00001836/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001837void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001838 // Read the number of types
1839 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001840
1841 // Ignore the type plane identifier for types if the bc file is pre 1.3
1842 if (hasTypeDerivedFromValue)
1843 read_vbr_uint();
1844
Reid Spencer46b002c2004-07-11 17:28:43 +00001845 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001846}
1847
Reid Spencer04cde2c2004-07-04 11:33:49 +00001848/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001849void BytecodeReader::ParseModuleGlobalInfo() {
1850
Reid Spencer04cde2c2004-07-04 11:33:49 +00001851 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001852
Chris Lattner70cc3392001-09-10 07:58:01 +00001853 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001854 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001855 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001856 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1857 // Linkage, bit4+ = slot#
1858 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001859 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001860 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001861 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001862 bool isConstant = VarType & 1;
1863 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001864 GlobalValue::LinkageTypes Linkage;
1865
Chris Lattnerc08912f2004-01-14 16:44:44 +00001866 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001867 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1868 case 1: Linkage = GlobalValue::WeakLinkage; break;
1869 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1870 case 3: Linkage = GlobalValue::InternalLinkage; break;
1871 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001872 default:
Reid Spencer24399722004-07-09 22:21:33 +00001873 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001874 Linkage = GlobalValue::InternalLinkage;
1875 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001876 }
1877
1878 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001879 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001880 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001881 }
1882
Reid Spencer46b002c2004-07-11 17:28:43 +00001883 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001884 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001885 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001886
Chris Lattner52e20b02003-03-19 20:54:26 +00001887 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001888
Chris Lattner70cc3392001-09-10 07:58:01 +00001889 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001890 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001891 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001892 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001893
Reid Spencer060d25d2004-06-29 23:29:38 +00001894 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001895 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001896 initSlot = read_vbr_uint();
1897 GlobalInits.push_back(std::make_pair(GV, initSlot));
1898 }
1899
1900 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001901 if (Handler)
1902 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001903
1904 // Get next item
1905 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001906 }
1907
Chris Lattner52e20b02003-03-19 20:54:26 +00001908 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001909 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001910
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001911 if (hasNoFlagsForFunctions)
1912 FnSignature = (FnSignature << 5) + 1;
1913
1914 // List is terminated by VoidTy.
1915 while ((FnSignature >> 5) != Type::VoidTyID) {
1916 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001917 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001918 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001919 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001920 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001921 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001922
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001923 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001924 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001925 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001926
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001927
Chris Lattner18549c22004-11-15 21:43:03 +00001928 // Insert the place holder.
Misha Brukman8a96c532005-04-21 21:44:41 +00001929 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001930 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001931 insertValue(Func, FnSignature >> 5, ModuleValues);
1932
1933 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001934 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001935
Chris Lattner97fbc502004-11-15 22:38:52 +00001936 // Save this for later so we know type of lazily instantiated functions.
1937 // Note that known-external functions do not have FunctionInfo blocks, so we
1938 // do not add them to the FunctionSignatureList.
1939 if ((Flags & (1 << 4)) == 0)
1940 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001941
Chris Lattner479ffeb2005-05-06 20:42:57 +00001942 // Look at the low bits. If there is a calling conv here, apply it,
1943 // read it as a vbr.
1944 Flags &= 15;
1945 if (Flags)
1946 Func->setCallingConv(Flags-1);
1947 else
1948 Func->setCallingConv(read_vbr_uint());
1949
Reid Spencer04cde2c2004-07-04 11:33:49 +00001950 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001951
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001952 // Get the next function signature.
1953 FnSignature = read_vbr_uint();
1954 if (hasNoFlagsForFunctions)
1955 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001956 }
1957
Misha Brukman8a96c532005-04-21 21:44:41 +00001958 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001959 // remove elements efficiently from the back of the vector.
1960 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001961
Reid Spencerad89bd62004-07-25 18:07:36 +00001962 // If this bytecode format has dependent library information in it ..
1963 if (!hasNoDependentLibraries) {
1964 // Read in the number of dependent library items that follow
1965 unsigned num_dep_libs = read_vbr_uint();
1966 std::string dep_lib;
1967 while( num_dep_libs-- ) {
1968 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001969 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001970 if (Handler)
1971 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001972 }
1973
Reid Spencer5b472d92004-08-21 20:49:23 +00001974
Reid Spencerad89bd62004-07-25 18:07:36 +00001975 // Read target triple and place into the module
1976 std::string triple = read_str();
1977 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001978 if (Handler)
1979 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001980 }
1981
1982 if (hasInconsistentModuleGlobalInfo)
1983 align32();
1984
Chris Lattner00950542001-06-06 20:29:01 +00001985 // This is for future proofing... in the future extra fields may be added that
1986 // we don't understand, so we transparently ignore them.
1987 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001988 At = BlockEnd;
1989
Reid Spencer04cde2c2004-07-04 11:33:49 +00001990 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001991}
1992
Reid Spencer04cde2c2004-07-04 11:33:49 +00001993/// Parse the version information and decode it by setting flags on the
1994/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001995void BytecodeReader::ParseVersionInfo() {
1996 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001997
1998 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001999 Module::Endianness Endianness;
2000 Module::PointerSize PointerSize;
2001 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2002 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2003
2004 bool hasNoEndianness = Version & 4;
2005 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002006
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002007 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002008
2009 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002010 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002011 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002012 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002013 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002014 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002015 has32BitTypes = false;
2016 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002017 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002018 hasNoUndefValue = false;
2019 hasNoFlagsForFunctions = false;
2020 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002021
2022 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002023 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002024 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002025 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002026 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002027
Chris Lattner80b97342004-01-17 23:25:43 +00002028 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002029
2030 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002031 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002032
2033 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2034 // included the size for the alignment at the end, where the rest of the
2035 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002036
2037 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2038 // structures and longs for sequential types.
2039 hasRestrictedGEPTypes = true;
2040
Reid Spencer04cde2c2004-07-04 11:33:49 +00002041 // LLVM 1.2 and before had the Type class derive from Value class. This
2042 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002043 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002044 // type planes for Values.
2045 hasTypeDerivedFromValue = true;
2046
Chris Lattner5fa428f2004-04-05 01:27:26 +00002047 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002048
Reid Spencer5b472d92004-08-21 20:49:23 +00002049 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002050
Reid Spencer5b472d92004-08-21 20:49:23 +00002051 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002052 // especially for small files where the 8 bytes per block is a large
2053 // fraction of the total block size. In LLVM 1.3, the block type and length
2054 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2055 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002056 hasLongBlockHeaders = true;
2057
Reid Spencer5b472d92004-08-21 20:49:23 +00002058 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002059 // this has been reduced to vbr_uint24. It shouldn't make much difference
2060 // since we haven't run into a module with > 24 million types, but for
2061 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2062 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002063 has32BitTypes = true;
2064
Misha Brukman8a96c532005-04-21 21:44:41 +00002065 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002066 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2067 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002068 hasNoDependentLibraries = true;
2069
2070 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002071
2072 case 3: // LLVM 1.3 (Released)
2073 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002074 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002075 // of GEP references to a constant array), this can increase the file size
2076 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002077 hasAlignment = true;
2078
2079 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002080
Reid Spencer5b472d92004-08-21 20:49:23 +00002081 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002082 // In version 4, we did not support the 'undef' constant.
2083 hasNoUndefValue = true;
2084
2085 // In version 4 and above, we did not include space for flags for functions
2086 // in the module info block.
2087 hasNoFlagsForFunctions = true;
2088
2089 // In version 4 and above, we did not include the 'unreachable' instruction
2090 // in the opcode numbering in the bytecode file.
2091 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002092 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002093
2094 // FALL THROUGH
2095
Chris Lattnerdee199f2005-05-06 22:34:01 +00002096 case 5: // 1.4 (Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002097 break;
2098
Chris Lattner036b8aa2003-03-06 17:55:45 +00002099 default:
Reid Spencer24399722004-07-09 22:21:33 +00002100 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002101 }
2102
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002103 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2104 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002105
Brian Gaekefe2102b2004-07-14 20:33:13 +00002106 TheModule->setEndianness(Endianness);
2107 TheModule->setPointerSize(PointerSize);
2108
Reid Spencer46b002c2004-07-11 17:28:43 +00002109 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002110}
2111
Reid Spencer04cde2c2004-07-04 11:33:49 +00002112/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002113void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002114 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002115
Reid Spencer060d25d2004-06-29 23:29:38 +00002116 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002117
2118 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002119 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002120 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002121
Reid Spencer060d25d2004-06-29 23:29:38 +00002122 bool SeenModuleGlobalInfo = false;
2123 bool SeenGlobalTypePlane = false;
2124 BufPtr MyEnd = BlockEnd;
2125 while (At < MyEnd) {
2126 BufPtr OldAt = At;
2127 read_block(Type, Size);
2128
Chris Lattner00950542001-06-06 20:29:01 +00002129 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002130
Reid Spencerad89bd62004-07-25 18:07:36 +00002131 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002132 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002133 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002134
Reid Spencer5b472d92004-08-21 20:49:23 +00002135 if (Size > 0)
2136 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002137 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002138 break;
2139
Misha Brukman8a96c532005-04-21 21:44:41 +00002140 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002141 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002142 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002143 ParseModuleGlobalInfo();
2144 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002145 break;
2146
Reid Spencerad89bd62004-07-25 18:07:36 +00002147 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002148 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002149 break;
2150
Reid Spencerad89bd62004-07-25 18:07:36 +00002151 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002152 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002153 break;
Chris Lattner00950542001-06-06 20:29:01 +00002154
Reid Spencerad89bd62004-07-25 18:07:36 +00002155 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002156 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002157 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002158
Chris Lattner00950542001-06-06 20:29:01 +00002159 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002160 At += Size;
2161 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002162 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002163 }
Chris Lattner00950542001-06-06 20:29:01 +00002164 break;
2165 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002166 BlockEnd = MyEnd;
2167 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002168 }
2169
Chris Lattner52e20b02003-03-19 20:54:26 +00002170 // After the module constant pool has been read, we can safely initialize
2171 // global variables...
2172 while (!GlobalInits.empty()) {
2173 GlobalVariable *GV = GlobalInits.back().first;
2174 unsigned Slot = GlobalInits.back().second;
2175 GlobalInits.pop_back();
2176
2177 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002178 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002179
2180 const llvm::PointerType* GVType = GV->getType();
2181 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002182 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002183 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002184 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002185 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002186 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002187 } else
Reid Spencer24399722004-07-09 22:21:33 +00002188 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002189 }
2190
Chris Lattneraba5ff52005-05-05 20:57:00 +00002191 if (!ConstantFwdRefs.empty())
2192 error("Use of undefined constants in a module");
2193
Reid Spencer060d25d2004-06-29 23:29:38 +00002194 /// Make sure we pulled them all out. If we didn't then there's a declaration
2195 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002196 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002197 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002198}
2199
Reid Spencer04cde2c2004-07-04 11:33:49 +00002200/// This function completely parses a bytecode buffer given by the \p Buf
2201/// and \p Length parameters.
Misha Brukman8a96c532005-04-21 21:44:41 +00002202void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002203 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002204
Reid Spencer060d25d2004-06-29 23:29:38 +00002205 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002206 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002207 At = MemStart = BlockStart = Buf;
2208 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002209
Reid Spencer060d25d2004-06-29 23:29:38 +00002210 // Create the module
2211 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002212
Reid Spencer04cde2c2004-07-04 11:33:49 +00002213 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002214
Reid Spencerf0c977c2004-11-07 18:20:55 +00002215 // Read the four bytes of the signature.
2216 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002217
Reid Spencerf0c977c2004-11-07 18:20:55 +00002218 // If this is a compressed file
2219 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002220
Reid Spencerf0c977c2004-11-07 18:20:55 +00002221 // Invoke the decompression of the bytecode. Note that we have to skip the
2222 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002223 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2224 // member for retention until BytecodeReader is destructed.
2225 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2226 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002227
2228 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002229 // into the new decompressed block. After decompression, the
2230 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002231 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002232 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002233 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002234
Reid Spencerf0c977c2004-11-07 18:20:55 +00002235 // else if this isn't a regular (uncompressed) bytecode file, then its
2236 // and error, generate that now.
2237 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2238 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002239 }
2240
Reid Spencer060d25d2004-06-29 23:29:38 +00002241 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002242 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002243
Reid Spencerad89bd62004-07-25 18:07:36 +00002244 // Get the module block and size and verify. This is handled specially
2245 // because the module block/size is always written in long format. Other
2246 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002247 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002248 Type = read_uint();
2249 Size = read_uint();
2250 if (Type != BytecodeFormat::ModuleBlockID) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002251 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002252 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002253 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002254
2255 // It looks like the darwin ranlib program is broken, and adds trailing
2256 // garbage to the end of some bytecode files. This hack allows the bc
2257 // reader to ignore trailing garbage on bytecode files.
2258 if (At + Size < MemEnd)
2259 MemEnd = BlockEnd = At+Size;
2260
2261 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002262 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002263 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002264
2265 // Parse the module contents
2266 this->ParseModule();
2267
Reid Spencer060d25d2004-06-29 23:29:38 +00002268 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002269 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002270 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002271
Reid Spencer5c15fe52004-07-05 00:57:50 +00002272 // Tell the handler we're done with the module
Misha Brukman8a96c532005-04-21 21:44:41 +00002273 if (Handler)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002274 Handler->handleModuleEnd(ModuleID);
2275
2276 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002277 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002278
Reid Spencer46b002c2004-07-11 17:28:43 +00002279 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002280 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002281 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002282 delete TheModule;
2283 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002284 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002285 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002286 decompressedBlock = 0;
2287 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002288 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002289 } catch (...) {
2290 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002291 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002292 freeState();
2293 delete TheModule;
2294 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002295 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002296 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002297 decompressedBlock = 0;
2298 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002299 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002300 }
Chris Lattner00950542001-06-06 20:29:01 +00002301}
Reid Spencer060d25d2004-06-29 23:29:38 +00002302
2303//===----------------------------------------------------------------------===//
2304//=== Default Implementations of Handler Methods
2305//===----------------------------------------------------------------------===//
2306
2307BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002308