blob: c20eeddcbf081c1fbc77974daca61354f76c5e50 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
Reid Spencer0b118202006-01-16 21:12:35 +000020#include "llvm/Assembly/AutoUpgrade.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000021#include "llvm/Bytecode/BytecodeHandler.h"
22#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000023#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000024#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000025#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000026#include "llvm/Instructions.h"
27#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
48 Op(UndefValue::get(Type::IntTy), this) {
49 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
57 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000078 if (hasAlignment) {
79 BufPtr Save = At;
Jeff Cohen05ebc8d2006-01-25 17:18:50 +000080 At = (const unsigned char *)((intptr_t)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000081 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000082 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000083 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000084 error("Ran out of data while aligning!");
85 }
Reid Spencer060d25d2004-06-29 23:29:38 +000086}
87
Reid Spencer04cde2c2004-07-04 11:33:49 +000088/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000089inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000090 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000091 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000092 At += 4;
93 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
94}
95
Reid Spencer04cde2c2004-07-04 11:33:49 +000096/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000097inline unsigned BytecodeReader::read_vbr_uint() {
98 unsigned Shift = 0;
99 unsigned Result = 0;
100 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000101
Reid Spencer060d25d2004-06-29 23:29:38 +0000102 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000103 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000104 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000105 Result |= (unsigned)((*At++) & 0x7F) << Shift;
106 Shift += 7;
107 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000108 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 return Result;
110}
111
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000113inline uint64_t BytecodeReader::read_vbr_uint64() {
114 unsigned Shift = 0;
115 uint64_t Result = 0;
116 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000117
Reid Spencer060d25d2004-06-29 23:29:38 +0000118 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000119 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000120 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000121 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
122 Shift += 7;
123 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000124 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000125 return Result;
126}
127
Reid Spencer04cde2c2004-07-04 11:33:49 +0000128/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000129inline int64_t BytecodeReader::read_vbr_int64() {
130 uint64_t R = read_vbr_uint64();
131 if (R & 1) {
132 if (R != 1)
133 return -(int64_t)(R >> 1);
134 else // There is no such thing as -0 with integers. "-0" really means
135 // 0x8000000000000000.
136 return 1LL << 63;
137 } else
138 return (int64_t)(R >> 1);
139}
140
Reid Spencer04cde2c2004-07-04 11:33:49 +0000141/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000142inline std::string BytecodeReader::read_str() {
143 unsigned Size = read_vbr_uint();
144 const unsigned char *OldAt = At;
145 At += Size;
146 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000147 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000148 return std::string((char*)OldAt, Size);
149}
150
Reid Spencer04cde2c2004-07-04 11:33:49 +0000151/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000152inline void BytecodeReader::read_data(void *Ptr, void *End) {
153 unsigned char *Start = (unsigned char *)Ptr;
154 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000155 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000156 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000157 std::copy(At, At+Amount, Start);
158 At += Amount;
159}
160
Reid Spencer46b002c2004-07-11 17:28:43 +0000161/// Read a float value in little-endian order
162inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000163 /// FIXME: This isn't optimal, it has size problems on some platforms
164 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000165 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000166 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000167}
168
169/// Read a double value in little-endian order
170inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000171 /// FIXME: This isn't optimal, it has size problems on some platforms
172 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000173 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
174 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
175 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
176 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000177 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000178}
179
Reid Spencer04cde2c2004-07-04 11:33:49 +0000180/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000181inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000182 if ( hasLongBlockHeaders ) {
183 Type = read_uint();
184 Size = read_uint();
185 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000186 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000187 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000188 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000189 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000190 Type = BytecodeFormat::ModuleBlockID; break;
191 case BytecodeFormat::Function:
192 Type = BytecodeFormat::FunctionBlockID; break;
193 case BytecodeFormat::ConstantPool:
194 Type = BytecodeFormat::ConstantPoolBlockID; break;
195 case BytecodeFormat::SymbolTable:
196 Type = BytecodeFormat::SymbolTableBlockID; break;
197 case BytecodeFormat::ModuleGlobalInfo:
198 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
199 case BytecodeFormat::GlobalTypePlane:
200 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
201 case BytecodeFormat::InstructionList:
202 Type = BytecodeFormat::InstructionListBlockID; break;
203 case BytecodeFormat::CompactionTable:
204 Type = BytecodeFormat::CompactionTableBlockID; break;
205 case BytecodeFormat::BasicBlock:
206 /// This block type isn't used after version 1.1. However, we have to
207 /// still allow the value in case this is an old bc format file.
208 /// We just let its value creep thru.
209 break;
210 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000211 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000212 break;
213 }
214 } else {
215 Size = read_uint();
216 Type = Size & 0x1F; // mask low order five bits
217 Size >>= 5; // get rid of five low order bits, leaving high 27
218 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000219 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000220 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000221 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000222 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000223 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000224}
225
226
227/// In LLVM 1.2 and before, Types were derived from Value and so they were
228/// written as part of the type planes along with any other Value. In LLVM
229/// 1.3 this changed so that Type does not derive from Value. Consequently,
230/// the BytecodeReader's containers for Values can't contain Types because
231/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000232/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
233/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000234/// the types are always read/written first and then the Values. Furthermore
235/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
236/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
237/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
238/// For LLVM 1.2 and before, this function will decrement the type id by
239/// one to account for the missing Type::TypeTyID enumerator if the value is
240/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
241/// function returns true, otherwise false. This helps detect situations
242/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000243/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000244inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
245 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
246 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000247 TypeId = Type::VoidTyID; // sanitize it
248 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000249 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000250 --TypeId; // shift all planes down because type type plane is missing
251 }
252 return false;
253}
254
255/// Reads a vbr uint to read in a type id and does the necessary
256/// conversion on it by calling sanitizeTypeId.
257/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
258/// @see sanitizeTypeId
259inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
260 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000261 if ( !has32BitTypes )
262 if ( TypeId == 0x00FFFFFF )
263 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000264 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000265}
266
267//===----------------------------------------------------------------------===//
268// IR Lookup Methods
269//===----------------------------------------------------------------------===//
270
Reid Spencer04cde2c2004-07-04 11:33:49 +0000271/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000272inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000273 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000274 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000275 return TyID >= Type::FirstDerivedTyID;
276}
277
Reid Spencer04cde2c2004-07-04 11:33:49 +0000278/// Obtain a type given a typeid and account for things like compaction tables,
279/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000280const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000281 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000282 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000283 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000284
285 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000286 ID -= Type::FirstDerivedTyID;
287
Reid Spencer060d25d2004-06-29 23:29:38 +0000288 if (!CompactionTypes.empty()) {
289 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000290 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000291 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000292 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000293
294 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000295 if (ID < ModuleTypes.size())
296 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000297
Reid Spencer46b002c2004-07-11 17:28:43 +0000298 // Nope, is it a function-level type?
299 ID -= ModuleTypes.size();
300 if (ID < FunctionTypes.size())
301 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000302
Reid Spencer46b002c2004-07-11 17:28:43 +0000303 error("Illegal type reference!");
304 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000305}
306
Reid Spencer04cde2c2004-07-04 11:33:49 +0000307/// Get a sanitized type id. This just makes sure that the \p ID
308/// is both sanitized and not the "type type" of pre-1.3 bytecode.
309/// @see sanitizeTypeId
310inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000311 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000312 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000313 return getType(ID);
314}
315
316/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000317/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000318/// then calls getType to return the type value.
319inline const Type* BytecodeReader::readSanitizedType() {
320 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000321 if (read_typeid(ID))
322 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000323 return getType(ID);
324}
325
326/// Get the slot number associated with a type accounting for primitive
327/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000328unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
329 if (Ty->isPrimitiveType())
330 return Ty->getTypeID();
331
332 // Scan the compaction table for the type if needed.
333 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000334 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
335 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000336 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000337
Chris Lattner45b5dd22004-08-03 23:41:28 +0000338 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000339 }
340
341 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000342 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
343 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000344
345 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000346 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000347 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000348
Chris Lattnereebac5f2005-10-03 21:26:53 +0000349 // If we don't have our cache yet, build it now.
350 if (ModuleTypeIDCache.empty()) {
351 unsigned N = 0;
352 ModuleTypeIDCache.reserve(ModuleTypes.size());
353 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
354 I != E; ++I, ++N)
355 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
356
357 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
358 }
359
360 // Binary search the cache for the entry.
361 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
362 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
363 std::make_pair(Ty, 0U));
364 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000365 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000366
367 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000368}
369
Reid Spencer04cde2c2004-07-04 11:33:49 +0000370/// This is just like getType, but when a compaction table is in use, it is
371/// ignored. It also ignores function level types.
372/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000373const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
374 if (Slot < Type::FirstDerivedTyID) {
375 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000376 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000377 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000378 return Ty;
379 }
380 Slot -= Type::FirstDerivedTyID;
381 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000382 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000383 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000384}
385
Reid Spencer04cde2c2004-07-04 11:33:49 +0000386/// This is just like getTypeSlot, but when a compaction table is in use, it
387/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000388unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
389 if (Ty->isPrimitiveType())
390 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000391
392 // If we don't have our cache yet, build it now.
393 if (ModuleTypeIDCache.empty()) {
394 unsigned N = 0;
395 ModuleTypeIDCache.reserve(ModuleTypes.size());
396 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
397 I != E; ++I, ++N)
398 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
399
400 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
401 }
402
403 // Binary search the cache for the entry.
404 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
405 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
406 std::make_pair(Ty, 0U));
407 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000408 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000409
410 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000411}
412
Misha Brukman8a96c532005-04-21 21:44:41 +0000413/// Retrieve a value of a given type and slot number, possibly creating
414/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000415Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000416 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000417 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000418
Chris Lattner89e02532004-01-18 21:08:15 +0000419 // If there is a compaction table active, it defines the low-level numbers.
420 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000421 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
422 if (Num < CompactionValues[type].size())
423 return CompactionValues[type][Num];
424 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000425 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000426 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000427 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000428
Chris Lattner45b5dd22004-08-03 23:41:28 +0000429 // If the type plane was compactified, figure out the global type ID by
430 // adding the derived type ids and the distance.
431 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
432 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000433
Reid Spencer060d25d2004-06-29 23:29:38 +0000434 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000435 const Type *Ty = getType(type);
436 if (!isa<OpaqueType>(Ty)) {
437 if (Num == 0)
438 return Constant::getNullValue(Ty);
439 --Num;
440 }
Chris Lattner89e02532004-01-18 21:08:15 +0000441 }
442
Chris Lattner52f86d62004-01-20 00:54:06 +0000443 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
444 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000445 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000446 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000447 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000448 }
449
Misha Brukman8a96c532005-04-21 21:44:41 +0000450 if (FunctionValues.size() > type &&
451 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000452 Num < FunctionValues[type]->size())
453 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000454
Chris Lattner74734132002-08-17 22:01:27 +0000455 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000456
Reid Spencer551ccae2004-09-01 22:55:40 +0000457 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000458 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000459 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000460 if (I != ForwardReferences.end() && I->first == KeyValue)
461 return I->second; // We have already created this placeholder
462
Reid Spencer551ccae2004-09-01 22:55:40 +0000463 // If the type exists (it should)
464 if (const Type* Ty = getType(type)) {
465 // Create the place holder
466 Value *Val = new Argument(Ty);
467 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
468 return Val;
469 }
Reid Spencer233fe722006-08-22 16:09:19 +0000470 error("Can't create placeholder for value of type slot #" + utostr(type));
471 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000472}
473
Misha Brukman8a96c532005-04-21 21:44:41 +0000474/// This is just like getValue, but when a compaction table is in use, it
475/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000476/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000477Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
478 if (SlotNo == 0)
479 return Constant::getNullValue(getType(TyID));
480
481 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
482 TyID -= Type::FirstDerivedTyID;
483 if (TyID >= CompactionTypes.size())
484 error("Type ID out of range for compaction table!");
485 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000486 }
487
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000488 --SlotNo;
489
Reid Spencer060d25d2004-06-29 23:29:38 +0000490 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
491 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000492 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
493 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000494 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000495 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000496 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000497 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000498 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000499 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000500 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
501 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000502 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000503 }
504 return ModuleValues[TyID]->getOperand(SlotNo);
505}
506
Reid Spencer04cde2c2004-07-04 11:33:49 +0000507/// Just like getValue, except that it returns a null pointer
508/// only on error. It always returns a constant (meaning that if the value is
509/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000510/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000511/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000512Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
513 if (Value *V = getValue(TypeSlot, Slot, false))
514 if (Constant *C = dyn_cast<Constant>(V))
515 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000516 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000517 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000518 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000519
Chris Lattner389bd042004-12-09 06:19:44 +0000520 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000521 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
522
523 if (I != ConstantFwdRefs.end() && I->first == Key) {
524 return I->second;
525 } else {
526 // Create a placeholder for the constant reference and
527 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000528 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000529
Reid Spencer060d25d2004-06-29 23:29:38 +0000530 // Keep track of the fact that we have a forward ref to recycle it
531 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
532 return C;
533 }
534}
535
536//===----------------------------------------------------------------------===//
537// IR Construction Methods
538//===----------------------------------------------------------------------===//
539
Reid Spencer04cde2c2004-07-04 11:33:49 +0000540/// As values are created, they are inserted into the appropriate place
541/// with this method. The ValueTable argument must be one of ModuleValues
542/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000543unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000544 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000545 if (ValueTab.size() <= type)
546 ValueTab.resize(type+1);
547
548 if (!ValueTab[type]) ValueTab[type] = new ValueList();
549
550 ValueTab[type]->push_back(Val);
551
Chris Lattneraba5ff52005-05-05 20:57:00 +0000552 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000553 return ValueTab[type]->size()-1 + HasOffset;
554}
555
Reid Spencer04cde2c2004-07-04 11:33:49 +0000556/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000557void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000558 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000559 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000560 for (FunctionType::param_iterator It = FT->param_begin();
561 It != FT->param_end(); ++It, ++AI)
562 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
563}
564
Reid Spencer1628cec2006-10-26 06:15:43 +0000565// Convert previous opcode values into the current value and/or construct
566// the instruction. This function handles all *abnormal* cases for instruction
567// generation based on obsolete opcode values. The normal cases are handled
568// in ParseInstruction below. Generally this function just produces a new
569// Opcode value (first argument). In a few cases (VAArg, VANext) the upgrade
570// path requies that the instruction (sequence) be generated differently from
571// the normal case in order to preserve the original semantics. In these
572// cases the result of the function will be a non-zero Instruction pointer. In
573// all other cases, zero will be returned indicating that the *normal*
574// instruction generation should be used, but with the new Opcode value.
575//
576Instruction*
577BytecodeReader::handleObsoleteOpcodes(
578 unsigned &Opcode, ///< The old opcode, possibly updated by this function
579 std::vector<unsigned> &Oprnds, ///< The operands to the instruction
580 unsigned &iType, ///< The type code from the bytecode file
581 const Type* InstTy, ///< The type of the instruction
582 BasicBlock* BB ///< The basic block to insert into, if we need to
583) {
584
585 // First, short circuit this if no conversion is required. When signless
586 // instructions were implemented the entire opcode sequence was revised so
587 // we key on this first which means that the opcode value read is the one
588 // we should use.
589 if (!hasSignlessInstructions)
590 return 0; // The opcode is fine the way it is.
591
592 // Declare the resulting instruction we might build. In general we just
593 // change the Opcode argument but in a few cases we need to generate the
594 // Instruction here because the upgrade case is significantly different from
595 // the normal case.
596 Instruction *Result = 0;
597
598 // If this is a bytecode format that did not include the unreachable
599 // instruction, bump up the opcode number to adjust it.
600 if (hasNoUnreachableInst)
601 if (Opcode >= Instruction::Unreachable && Opcode < 62)
602 ++Opcode;
603
604 // We're dealing with an upgrade situation. For each of the opcode values,
605 // perform the necessary conversion.
606 switch (Opcode) {
607 default: // Error
608 // This switch statement provides cases for all known opcodes prior to
609 // version 6 bytecode format. We know we're in an upgrade situation so
610 // if there isn't a match in this switch, then something is horribly
611 // wrong.
612 error("Unknown obsolete opcode encountered.");
613 break;
614 case 1: // Ret
615 Opcode = Instruction::Ret;
616 break;
617 case 2: // Br
618 Opcode = Instruction::Br;
619 break;
620 case 3: // Switch
621 Opcode = Instruction::Switch;
622 break;
623 case 4: // Invoke
624 Opcode = Instruction::Invoke;
625 break;
626 case 5: // Unwind
627 Opcode = Instruction::Unwind;
628 break;
629 case 6: // Unreachable
630 Opcode = Instruction::Unreachable;
631 break;
632 case 7: // Add
633 Opcode = Instruction::Add;
634 break;
635 case 8: // Sub
636 Opcode = Instruction::Sub;
637 break;
638 case 9: // Mul
639 Opcode = Instruction::Mul;
640 break;
641 case 10: // Div
642 // The type of the instruction is based on the operands. We need to select
643 // fdiv, udiv or sdiv based on that type. The iType values are hardcoded
644 // to the values used in bytecode version 5 (and prior) because it is
645 // likely these codes will change in future versions of LLVM.
646 if (iType == 10 || iType == 11 )
647 Opcode = Instruction::FDiv;
648 else if (iType >= 2 && iType <= 9 && iType % 2 != 0)
649 Opcode = Instruction::SDiv;
650 else
651 Opcode = Instruction::UDiv;
652 break;
653
654 case 11: // Rem
Reid Spencer0a783f72006-11-02 01:53:59 +0000655 // As with "Div", make the signed/unsigned or floating point Rem
656 // instruction choice based on the type of the operands.
657 if (iType == 10 || iType == 11)
658 Opcode = Instruction::FRem;
659 else if (iType >= 2 && iType <= 9 && iType % 2 != 0)
660 Opcode = Instruction::SRem;
661 else
662 Opcode = Instruction::URem;
Reid Spencer1628cec2006-10-26 06:15:43 +0000663 break;
664 case 12: // And
665 Opcode = Instruction::And;
666 break;
667 case 13: // Or
668 Opcode = Instruction::Or;
669 break;
670 case 14: // Xor
671 Opcode = Instruction::Xor;
672 break;
673 case 15: // SetEQ
674 Opcode = Instruction::SetEQ;
675 break;
676 case 16: // SetNE
677 Opcode = Instruction::SetNE;
678 break;
679 case 17: // SetLE
680 Opcode = Instruction::SetLE;
681 break;
682 case 18: // SetGE
683 Opcode = Instruction::SetGE;
684 break;
685 case 19: // SetLT
686 Opcode = Instruction::SetLT;
687 break;
688 case 20: // SetGT
689 Opcode = Instruction::SetGT;
690 break;
691 case 21: // Malloc
692 Opcode = Instruction::Malloc;
693 break;
694 case 22: // Free
695 Opcode = Instruction::Free;
696 break;
697 case 23: // Alloca
698 Opcode = Instruction::Alloca;
699 break;
700 case 24: // Load
701 Opcode = Instruction::Load;
702 break;
703 case 25: // Store
704 Opcode = Instruction::Store;
705 break;
706 case 26: // GetElementPtr
707 Opcode = Instruction::GetElementPtr;
708 break;
709 case 27: // PHI
710 Opcode = Instruction::PHI;
711 break;
712 case 28: // Cast
713 Opcode = Instruction::Cast;
714 break;
715 case 29: // Call
716 Opcode = Instruction::Call;
717 break;
718 case 30: // Shl
719 Opcode = Instruction::Shl;
720 break;
721 case 31: // Shr
722 Opcode = Instruction::Shr;
723 break;
724 case 32: { //VANext_old ( <= llvm 1.5 )
725 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
726 Function* NF = TheModule->getOrInsertFunction(
727 "llvm.va_copy", ArgTy, ArgTy, (Type *)0);
728
729 // In llvm 1.6 the VANext instruction was dropped because it was only
730 // necessary to have a VAArg instruction. The code below transforms an
731 // old vanext instruction into the equivalent code given only the
732 // availability of the new vaarg instruction. Essentially, the transform
733 // is as follows:
734 // b = vanext a, t ->
735 // foo = alloca 1 of t
736 // bar = vacopy a
737 // store bar -> foo
738 // tmp = vaarg foo, t
739 // b = load foo
740 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
741 BB->getInstList().push_back(foo);
742 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
743 BB->getInstList().push_back(bar);
744 BB->getInstList().push_back(new StoreInst(bar, foo));
745 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
746 BB->getInstList().push_back(tmp);
747 Result = new LoadInst(foo);
748 break;
749 }
750 case 33: { //VAArg_old
751 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
752 Function* NF = TheModule->getOrInsertFunction(
753 "llvm.va_copy", ArgTy, ArgTy, (Type *)0);
754
755 // In llvm 1.6 the VAArg's instruction semantics were changed. The code
756 // below transforms an old vaarg instruction into the equivalent code
757 // given only the availability of the new vaarg instruction. Essentially,
758 // the transform is as follows:
759 // b = vaarg a, t ->
760 // foo = alloca 1 of t
761 // bar = vacopy a
762 // store bar -> foo
763 // b = vaarg foo, t
764 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
765 BB->getInstList().push_back(foo);
766 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
767 BB->getInstList().push_back(bar);
768 BB->getInstList().push_back(new StoreInst(bar, foo));
769 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
770 break;
771 }
772 case 34: // Select
773 Opcode = Instruction::Select;
774 break;
775 case 35: // UserOp1
776 Opcode = Instruction::UserOp1;
777 break;
778 case 36: // UserOp2
779 Opcode = Instruction::UserOp2;
780 break;
781 case 37: // VAArg
782 Opcode = Instruction::VAArg;
783 break;
784 case 38: // ExtractElement
785 Opcode = Instruction::ExtractElement;
786 break;
787 case 39: // InsertElement
788 Opcode = Instruction::InsertElement;
789 break;
790 case 40: // ShuffleVector
791 Opcode = Instruction::ShuffleVector;
792 break;
793 case 56: // Invoke with encoded CC
794 case 57: // Invoke Fast CC
795 case 58: // Call with extra operand for calling conv
796 case 59: // tail call, Fast CC
797 case 60: // normal call, Fast CC
798 case 61: // tail call, C Calling Conv
799 case 62: // volatile load
800 case 63: // volatile store
801 // In all these cases, we pass the opcode through. The new version uses
802 // the same code (for now, this might change in 2.0). These are listed
803 // here to document the opcodes in use in vers 5 bytecode and to make it
804 // easier to migrate these opcodes in the future.
805 break;
806 }
807 return Result;
808}
809
Reid Spencer060d25d2004-06-29 23:29:38 +0000810//===----------------------------------------------------------------------===//
811// Bytecode Parsing Methods
812//===----------------------------------------------------------------------===//
813
Reid Spencer04cde2c2004-07-04 11:33:49 +0000814/// This method parses a single instruction. The instruction is
815/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000816/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000817void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000818 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000819 BufPtr SaveAt = At;
820
821 // Clear instruction data
822 Oprnds.clear();
823 unsigned iType = 0;
824 unsigned Opcode = 0;
825 unsigned Op = read_uint();
826
827 // bits Instruction format: Common to all formats
828 // --------------------------
829 // 01-00: Opcode type, fixed to 1.
830 // 07-02: Opcode
831 Opcode = (Op >> 2) & 63;
832 Oprnds.resize((Op >> 0) & 03);
833
834 // Extract the operands
835 switch (Oprnds.size()) {
836 case 1:
837 // bits Instruction format:
838 // --------------------------
839 // 19-08: Resulting type plane
840 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
841 //
842 iType = (Op >> 8) & 4095;
843 Oprnds[0] = (Op >> 20) & 4095;
844 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
845 Oprnds.resize(0);
846 break;
847 case 2:
848 // bits Instruction format:
849 // --------------------------
850 // 15-08: Resulting type plane
851 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000852 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000853 //
854 iType = (Op >> 8) & 255;
855 Oprnds[0] = (Op >> 16) & 255;
856 Oprnds[1] = (Op >> 24) & 255;
857 break;
858 case 3:
859 // bits Instruction format:
860 // --------------------------
861 // 13-08: Resulting type plane
862 // 19-14: Operand #1
863 // 25-20: Operand #2
864 // 31-26: Operand #3
865 //
866 iType = (Op >> 8) & 63;
867 Oprnds[0] = (Op >> 14) & 63;
868 Oprnds[1] = (Op >> 20) & 63;
869 Oprnds[2] = (Op >> 26) & 63;
870 break;
871 case 0:
872 At -= 4; // Hrm, try this again...
873 Opcode = read_vbr_uint();
874 Opcode >>= 2;
875 iType = read_vbr_uint();
876
877 unsigned NumOprnds = read_vbr_uint();
878 Oprnds.resize(NumOprnds);
879
880 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000881 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000882
883 for (unsigned i = 0; i != NumOprnds; ++i)
884 Oprnds[i] = read_vbr_uint();
885 align32();
886 break;
887 }
888
Reid Spencer04cde2c2004-07-04 11:33:49 +0000889 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000890
Reid Spencer1628cec2006-10-26 06:15:43 +0000891 // Make the necessary adjustments for dealing with backwards compatibility
892 // of opcodes.
893 Instruction* Result =
894 handleObsoleteOpcodes(Opcode, Oprnds, iType, InstTy, BB);
895
Reid Spencer46b002c2004-07-11 17:28:43 +0000896 // We have enough info to inform the handler now.
Reid Spencer1628cec2006-10-26 06:15:43 +0000897 if (Handler)
898 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000899
Reid Spencer1628cec2006-10-26 06:15:43 +0000900 // If the backwards compatibility code didn't produce an instruction then
901 // we do the *normal* thing ..
902 if (!Result) {
903 // First, handle the easy binary operators case
904 if (Opcode >= Instruction::BinaryOpsBegin &&
905 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
906 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
907 getValue(iType, Oprnds[0]),
908 getValue(iType, Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000909
Reid Spencer1628cec2006-10-26 06:15:43 +0000910 // Indicate that we don't think this is a call instruction (yet).
911 // Process based on the Opcode read
912 switch (Opcode) {
913 default: // There was an error, this shouldn't happen.
914 if (Result == 0)
915 error("Illegal instruction read!");
916 break;
917 case Instruction::VAArg:
918 if (Oprnds.size() != 2)
919 error("Invalid VAArg instruction!");
920 Result = new VAArgInst(getValue(iType, Oprnds[0]),
921 getSanitizedType(Oprnds[1]));
922 break;
923 case Instruction::ExtractElement: {
924 if (Oprnds.size() != 2)
925 error("Invalid extractelement instruction!");
926 Value *V1 = getValue(iType, Oprnds[0]);
927 Value *V2 = getValue(Type::UIntTyID, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000928
Reid Spencer1628cec2006-10-26 06:15:43 +0000929 if (!ExtractElementInst::isValidOperands(V1, V2))
930 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000931
Reid Spencer1628cec2006-10-26 06:15:43 +0000932 Result = new ExtractElementInst(V1, V2);
933 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000934 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000935 case Instruction::InsertElement: {
936 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
937 if (!PackedTy || Oprnds.size() != 3)
938 error("Invalid insertelement instruction!");
939
940 Value *V1 = getValue(iType, Oprnds[0]);
941 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
942 Value *V3 = getValue(Type::UIntTyID, Oprnds[2]);
943
944 if (!InsertElementInst::isValidOperands(V1, V2, V3))
945 error("Invalid insertelement instruction!");
946 Result = new InsertElementInst(V1, V2, V3);
947 break;
948 }
949 case Instruction::ShuffleVector: {
950 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
951 if (!PackedTy || Oprnds.size() != 3)
952 error("Invalid shufflevector instruction!");
953 Value *V1 = getValue(iType, Oprnds[0]);
954 Value *V2 = getValue(iType, Oprnds[1]);
955 const PackedType *EltTy =
956 PackedType::get(Type::UIntTy, PackedTy->getNumElements());
957 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
958 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
959 error("Invalid shufflevector instruction!");
960 Result = new ShuffleVectorInst(V1, V2, V3);
961 break;
962 }
963 case Instruction::Cast:
964 if (Oprnds.size() != 2)
965 error("Invalid Cast instruction!");
966 Result = new CastInst(getValue(iType, Oprnds[0]),
967 getSanitizedType(Oprnds[1]));
968 break;
969 case Instruction::Select:
970 if (Oprnds.size() != 3)
971 error("Invalid Select instruction!");
972 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
973 getValue(iType, Oprnds[1]),
974 getValue(iType, Oprnds[2]));
975 break;
976 case Instruction::PHI: {
977 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
978 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000979
Reid Spencer1628cec2006-10-26 06:15:43 +0000980 PHINode *PN = new PHINode(InstTy);
981 PN->reserveOperandSpace(Oprnds.size());
982 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
983 PN->addIncoming(
984 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
985 Result = PN;
986 break;
987 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000988
Reid Spencer1628cec2006-10-26 06:15:43 +0000989 case Instruction::Shl:
990 case Instruction::Shr:
991 Result = new ShiftInst(Instruction::OtherOps(Opcode),
992 getValue(iType, Oprnds[0]),
993 getValue(Type::UByteTyID, Oprnds[1]));
994 break;
995 case Instruction::Ret:
996 if (Oprnds.size() == 0)
997 Result = new ReturnInst();
998 else if (Oprnds.size() == 1)
999 Result = new ReturnInst(getValue(iType, Oprnds[0]));
1000 else
1001 error("Unrecognized instruction!");
1002 break;
1003
1004 case Instruction::Br:
1005 if (Oprnds.size() == 1)
1006 Result = new BranchInst(getBasicBlock(Oprnds[0]));
1007 else if (Oprnds.size() == 3)
1008 Result = new BranchInst(getBasicBlock(Oprnds[0]),
1009 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
1010 else
1011 error("Invalid number of operands for a 'br' instruction!");
1012 break;
1013 case Instruction::Switch: {
1014 if (Oprnds.size() & 1)
1015 error("Switch statement with odd number of arguments!");
1016
1017 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
1018 getBasicBlock(Oprnds[1]),
1019 Oprnds.size()/2-1);
1020 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
1021 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
1022 getBasicBlock(Oprnds[i+1]));
1023 Result = I;
1024 break;
1025 }
1026 case 58: // Call with extra operand for calling conv
1027 case 59: // tail call, Fast CC
1028 case 60: // normal call, Fast CC
1029 case 61: // tail call, C Calling Conv
1030 case Instruction::Call: { // Normal Call, C Calling Convention
1031 if (Oprnds.size() == 0)
1032 error("Invalid call instruction encountered!");
1033
1034 Value *F = getValue(iType, Oprnds[0]);
1035
1036 unsigned CallingConv = CallingConv::C;
1037 bool isTailCall = false;
1038
1039 if (Opcode == 61 || Opcode == 59)
1040 isTailCall = true;
1041
1042 if (Opcode == 58) {
1043 isTailCall = Oprnds.back() & 1;
1044 CallingConv = Oprnds.back() >> 1;
1045 Oprnds.pop_back();
1046 } else if (Opcode == 59 || Opcode == 60) {
1047 CallingConv = CallingConv::Fast;
1048 }
1049
1050 // Check to make sure we have a pointer to function type
1051 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
1052 if (PTy == 0) error("Call to non function pointer value!");
1053 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
1054 if (FTy == 0) error("Call to non function pointer value!");
1055
1056 std::vector<Value *> Params;
1057 if (!FTy->isVarArg()) {
1058 FunctionType::param_iterator It = FTy->param_begin();
1059
1060 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
1061 if (It == FTy->param_end())
1062 error("Invalid call instruction!");
1063 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
1064 }
1065 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +00001066 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001067 } else {
1068 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
1069
1070 unsigned FirstVariableOperand;
1071 if (Oprnds.size() < FTy->getNumParams())
1072 error("Call instruction missing operands!");
1073
1074 // Read all of the fixed arguments
1075 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1076 Params.push_back(
1077 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
1078
1079 FirstVariableOperand = FTy->getNumParams();
1080
1081 if ((Oprnds.size()-FirstVariableOperand) & 1)
1082 error("Invalid call instruction!"); // Must be pairs of type/value
1083
1084 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
1085 i != e; i += 2)
1086 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +00001087 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001088
Reid Spencer1628cec2006-10-26 06:15:43 +00001089 Result = new CallInst(F, Params);
1090 if (isTailCall) cast<CallInst>(Result)->setTailCall();
1091 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
1092 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001093 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001094 case 56: // Invoke with encoded CC
1095 case 57: // Invoke Fast CC
1096 case Instruction::Invoke: { // Invoke C CC
1097 if (Oprnds.size() < 3)
1098 error("Invalid invoke instruction!");
1099 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +00001100
Reid Spencer1628cec2006-10-26 06:15:43 +00001101 // Check to make sure we have a pointer to function type
1102 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
1103 if (PTy == 0)
1104 error("Invoke to non function pointer value!");
1105 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
1106 if (FTy == 0)
1107 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001108
Reid Spencer1628cec2006-10-26 06:15:43 +00001109 std::vector<Value *> Params;
1110 BasicBlock *Normal, *Except;
1111 unsigned CallingConv = CallingConv::C;
Reid Spencer060d25d2004-06-29 23:29:38 +00001112
Reid Spencer1628cec2006-10-26 06:15:43 +00001113 if (Opcode == 57)
1114 CallingConv = CallingConv::Fast;
1115 else if (Opcode == 56) {
1116 CallingConv = Oprnds.back();
1117 Oprnds.pop_back();
1118 }
Chris Lattnerdee199f2005-05-06 22:34:01 +00001119
Reid Spencer1628cec2006-10-26 06:15:43 +00001120 if (!FTy->isVarArg()) {
1121 Normal = getBasicBlock(Oprnds[1]);
1122 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +00001123
Reid Spencer1628cec2006-10-26 06:15:43 +00001124 FunctionType::param_iterator It = FTy->param_begin();
1125 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
1126 if (It == FTy->param_end())
1127 error("Invalid invoke instruction!");
1128 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
1129 }
1130 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +00001131 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001132 } else {
1133 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
1134
1135 Normal = getBasicBlock(Oprnds[0]);
1136 Except = getBasicBlock(Oprnds[1]);
1137
1138 unsigned FirstVariableArgument = FTy->getNumParams()+2;
1139 for (unsigned i = 2; i != FirstVariableArgument; ++i)
1140 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
1141 Oprnds[i]));
1142
1143 // Must be type/value pairs. If not, error out.
1144 if (Oprnds.size()-FirstVariableArgument & 1)
1145 error("Invalid invoke instruction!");
1146
1147 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
1148 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +00001149 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001150
Reid Spencer1628cec2006-10-26 06:15:43 +00001151 Result = new InvokeInst(F, Normal, Except, Params);
1152 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
1153 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001154 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001155 case Instruction::Malloc: {
1156 unsigned Align = 0;
1157 if (Oprnds.size() == 2)
1158 Align = (1 << Oprnds[1]) >> 1;
1159 else if (Oprnds.size() > 2)
1160 error("Invalid malloc instruction!");
1161 if (!isa<PointerType>(InstTy))
1162 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001163
Reid Spencer1628cec2006-10-26 06:15:43 +00001164 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
1165 getValue(Type::UIntTyID, Oprnds[0]), Align);
1166 break;
1167 }
1168 case Instruction::Alloca: {
1169 unsigned Align = 0;
1170 if (Oprnds.size() == 2)
1171 Align = (1 << Oprnds[1]) >> 1;
1172 else if (Oprnds.size() > 2)
1173 error("Invalid alloca instruction!");
1174 if (!isa<PointerType>(InstTy))
1175 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001176
Reid Spencer1628cec2006-10-26 06:15:43 +00001177 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
1178 getValue(Type::UIntTyID, Oprnds[0]), Align);
1179 break;
1180 }
1181 case Instruction::Free:
1182 if (!isa<PointerType>(InstTy))
1183 error("Invalid free instruction!");
1184 Result = new FreeInst(getValue(iType, Oprnds[0]));
1185 break;
1186 case Instruction::GetElementPtr: {
1187 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +00001188 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001189
Reid Spencer1628cec2006-10-26 06:15:43 +00001190 std::vector<Value*> Idx;
1191
1192 const Type *NextTy = InstTy;
1193 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
1194 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
1195 if (!TopTy)
1196 error("Invalid getelementptr instruction!");
1197
1198 unsigned ValIdx = Oprnds[i];
1199 unsigned IdxTy = 0;
1200 if (!hasRestrictedGEPTypes) {
1201 // Struct indices are always uints, sequential type indices can be
1202 // any of the 32 or 64-bit integer types. The actual choice of
1203 // type is encoded in the low two bits of the slot number.
1204 if (isa<StructType>(TopTy))
1205 IdxTy = Type::UIntTyID;
1206 else {
1207 switch (ValIdx & 3) {
1208 default:
1209 case 0: IdxTy = Type::UIntTyID; break;
1210 case 1: IdxTy = Type::IntTyID; break;
1211 case 2: IdxTy = Type::ULongTyID; break;
1212 case 3: IdxTy = Type::LongTyID; break;
1213 }
1214 ValIdx >>= 2;
Reid Spencer060d25d2004-06-29 23:29:38 +00001215 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001216 } else {
1217 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +00001218 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001219
1220 Idx.push_back(getValue(IdxTy, ValIdx));
1221
1222 // Convert ubyte struct indices into uint struct indices.
1223 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
1224 if (ConstantInt *C = dyn_cast<ConstantInt>(Idx.back()))
1225 if (C->getType() == Type::UByteTy)
1226 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
1227
1228 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001229 }
1230
Reid Spencer1628cec2006-10-26 06:15:43 +00001231 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
1232 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001233 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001234 case 62: // volatile load
1235 case Instruction::Load:
1236 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
1237 error("Invalid load instruction!");
1238 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
1239 break;
1240 case 63: // volatile store
1241 case Instruction::Store: {
1242 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
1243 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001244
Reid Spencer1628cec2006-10-26 06:15:43 +00001245 Value *Ptr = getValue(iType, Oprnds[1]);
1246 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
1247 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1248 Opcode == 63);
1249 break;
1250 }
1251 case Instruction::Unwind:
1252 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
1253 Result = new UnwindInst();
1254 break;
1255 case Instruction::Unreachable:
1256 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1257 Result = new UnreachableInst();
1258 break;
1259 } // end switch(Opcode)
1260 } // end if *normal*
Reid Spencer060d25d2004-06-29 23:29:38 +00001261
Reid Spencere1e96c02006-01-19 07:02:16 +00001262 BB->getInstList().push_back(Result);
1263
Reid Spencer060d25d2004-06-29 23:29:38 +00001264 unsigned TypeSlot;
1265 if (Result->getType() == InstTy)
1266 TypeSlot = iType;
1267 else
1268 TypeSlot = getTypeSlot(Result->getType());
1269
1270 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +00001271}
1272
Reid Spencer04cde2c2004-07-04 11:33:49 +00001273/// Get a particular numbered basic block, which might be a forward reference.
1274/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +00001275/// in a clean manner. This function is used when constructing phi, br, switch,
1276/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +00001277/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001278BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001279 // Make sure there is room in the table...
1280 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1281
1282 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1283 // has already created this block, or if the forward reference has already
1284 // been created.
1285 if (ParsedBasicBlocks[ID])
1286 return ParsedBasicBlocks[ID];
1287
1288 // Otherwise, the basic block has not yet been created. Do so and add it to
1289 // the ParsedBasicBlocks list.
1290 return ParsedBasicBlocks[ID] = new BasicBlock();
1291}
1292
Misha Brukman8a96c532005-04-21 21:44:41 +00001293/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001294/// This method reads in one of the basicblock packets. This method is not used
1295/// for bytecode files after LLVM 1.0
1296/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001297BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1298 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001299
1300 BasicBlock *BB = 0;
1301
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001302 if (ParsedBasicBlocks.size() == BlockNo)
1303 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1304 else if (ParsedBasicBlocks[BlockNo] == 0)
1305 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1306 else
1307 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001308
Reid Spencer060d25d2004-06-29 23:29:38 +00001309 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001310 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001311 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001312
Reid Spencer46b002c2004-07-11 17:28:43 +00001313 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001314 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001315}
1316
Reid Spencer04cde2c2004-07-04 11:33:49 +00001317/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001318/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001319/// in order to avoid per-basic-block overhead.
1320/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001321unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001322 unsigned BlockNo = 0;
1323 std::vector<unsigned> Args;
1324
Reid Spencer46b002c2004-07-11 17:28:43 +00001325 while (moreInBlock()) {
1326 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001327 BasicBlock *BB;
1328 if (ParsedBasicBlocks.size() == BlockNo)
1329 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1330 else if (ParsedBasicBlocks[BlockNo] == 0)
1331 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1332 else
1333 BB = ParsedBasicBlocks[BlockNo];
1334 ++BlockNo;
1335 F->getBasicBlockList().push_back(BB);
1336
1337 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001338 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001339 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001340
1341 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001342 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001343
Reid Spencer46b002c2004-07-11 17:28:43 +00001344 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001345 }
1346
1347 return BlockNo;
1348}
1349
Reid Spencer04cde2c2004-07-04 11:33:49 +00001350/// Parse a symbol table. This works for both module level and function
1351/// level symbol tables. For function level symbol tables, the CurrentFunction
1352/// parameter must be non-zero and the ST parameter must correspond to
1353/// CurrentFunction's symbol table. For Module level symbol tables, the
1354/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001355void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001356 SymbolTable *ST) {
1357 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001358
Chris Lattner39cacce2003-10-10 05:43:47 +00001359 // Allow efficient basic block lookup by number.
1360 std::vector<BasicBlock*> BBMap;
1361 if (CurrentFunction)
1362 for (Function::iterator I = CurrentFunction->begin(),
1363 E = CurrentFunction->end(); I != E; ++I)
1364 BBMap.push_back(I);
1365
Reid Spencer04cde2c2004-07-04 11:33:49 +00001366 /// In LLVM 1.3 we write types separately from values so
1367 /// The types are always first in the symbol table. This is
1368 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001369 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001370 // Symtab block header: [num entries]
1371 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001372 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001373 // Symtab entry: [def slot #][name]
1374 unsigned slot = read_vbr_uint();
1375 std::string Name = read_str();
1376 const Type* T = getType(slot);
1377 ST->insert(Name, T);
1378 }
1379 }
1380
Reid Spencer46b002c2004-07-11 17:28:43 +00001381 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001382 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001383 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001384 unsigned Typ = 0;
1385 bool isTypeType = read_typeid(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001386
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001387 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001388 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001389 unsigned slot = read_vbr_uint();
1390 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001391
Reid Spencer04cde2c2004-07-04 11:33:49 +00001392 // if we're reading a pre 1.3 bytecode file and the type plane
1393 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001394 if (isTypeType) {
1395 const Type* T = getType(slot);
1396 if (T == 0)
1397 error("Failed type look-up for name '" + Name + "'");
1398 ST->insert(Name, T);
1399 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001400 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001401 Value *V = 0;
1402 if (Typ == Type::LabelTyID) {
1403 if (slot < BBMap.size())
1404 V = BBMap[slot];
1405 } else {
1406 V = getValue(Typ, slot, false); // Find mapping...
1407 }
1408 if (V == 0)
1409 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001410 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001411 }
Chris Lattner00950542001-06-06 20:29:01 +00001412 }
1413 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001414 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001415 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001416}
1417
Misha Brukman8a96c532005-04-21 21:44:41 +00001418/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001419void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001420 for (unsigned i = 0; i != NumEntries; ++i) {
1421 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001422 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001423 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001424 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001425 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001426 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001427 }
1428}
1429
1430/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001431void BytecodeReader::ParseCompactionTable() {
1432
Reid Spencer46b002c2004-07-11 17:28:43 +00001433 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001434 if (Handler) Handler->handleCompactionTableBegin();
1435
Misha Brukman8a96c532005-04-21 21:44:41 +00001436 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001437 // we always write them first in the compaction table
1438 // because they can't occupy a "type plane" where the
1439 // Values reside.
1440 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001441 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001442 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001443 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001444
Reid Spencer46b002c2004-07-11 17:28:43 +00001445 // Compaction tables live in separate blocks so we have to loop
1446 // until we've read the whole thing.
1447 while (moreInBlock()) {
1448 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001449 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001450 unsigned Ty = 0;
1451 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001452
Reid Spencer46b002c2004-07-11 17:28:43 +00001453 // Decode the type from value read in. Most compaction table
1454 // planes will have one or two entries in them. If that's the
1455 // case then the length is encoded in the bottom two bits and
1456 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001457 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001458 // In this case, both low-order bits are set (value 3). This
1459 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001460 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001461 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001463 // In this case, the low-order bits specify the number of entries
1464 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001465 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001466 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 NumEntries &= 3;
1468 }
1469
Reid Spencer04cde2c2004-07-04 11:33:49 +00001470 // if we're reading a pre 1.3 bytecode file and the type plane
1471 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001472 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001473 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001474 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001475 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001476 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001477 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001478
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001479 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001480 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001481 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001482
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001483 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001484 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001485
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001486 // Push the implicit zero.
1487 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001488
1489 // Read in each of the entries, put them in the compaction table
1490 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001491 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001492 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001493 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001494 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001495 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001496 }
1497 }
1498 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001499 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001500 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001501}
Misha Brukman8a96c532005-04-21 21:44:41 +00001502
Reid Spencer46b002c2004-07-11 17:28:43 +00001503// Parse a single type. The typeid is read in first. If its a primitive type
1504// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001505// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001506// definition.
1507const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001508 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001509 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001510 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001511
1512 const Type *Result = 0;
1513 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1514 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001515
Reid Spencer060d25d2004-06-29 23:29:38 +00001516 switch (PrimType) {
1517 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001518 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001519
1520 unsigned NumParams = read_vbr_uint();
1521
1522 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001523 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001524 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001525
1526 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1527 if (isVarArg) Params.pop_back();
1528
1529 Result = FunctionType::get(RetType, Params, isVarArg);
1530 break;
1531 }
1532 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001533 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001534 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001535 Result = ArrayType::get(ElementType, NumElements);
1536 break;
1537 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001538 case Type::PackedTyID: {
1539 const Type *ElementType = readSanitizedType();
1540 unsigned NumElements = read_vbr_uint();
1541 Result = PackedType::get(ElementType, NumElements);
1542 break;
1543 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001544 case Type::StructTyID: {
1545 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001546 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001547 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001548 error("Invalid element type (type type) for structure!");
1549
Reid Spencer060d25d2004-06-29 23:29:38 +00001550 while (Typ) { // List is terminated by void/0 typeid
1551 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001552 if (read_typeid(Typ))
1553 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001554 }
1555
1556 Result = StructType::get(Elements);
1557 break;
1558 }
1559 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001560 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001561 break;
1562 }
1563
1564 case Type::OpaqueTyID: {
1565 Result = OpaqueType::get();
1566 break;
1567 }
1568
1569 default:
Reid Spencer24399722004-07-09 22:21:33 +00001570 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001571 break;
1572 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001573 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001574 return Result;
1575}
1576
Reid Spencer5b472d92004-08-21 20:49:23 +00001577// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001578// types. We know that recursive types will only reference the current slab of
1579// values in the type plane, but they can forward reference types before they
1580// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1581// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1582// this ugly problem, we pessimistically insert an opaque type for each type we
1583// are about to read. This means that forward references will resolve to
1584// something and when we reread the type later, we can replace the opaque type
1585// with a new resolved concrete type.
1586//
Reid Spencer46b002c2004-07-11 17:28:43 +00001587void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001588 assert(Tab.size() == 0 && "should not have read type constants in before!");
1589
1590 // Insert a bunch of opaque types to be resolved later...
1591 Tab.reserve(NumEntries);
1592 for (unsigned i = 0; i != NumEntries; ++i)
1593 Tab.push_back(OpaqueType::get());
1594
Misha Brukman8a96c532005-04-21 21:44:41 +00001595 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001596 Handler->handleTypeList(NumEntries);
1597
Chris Lattnereebac5f2005-10-03 21:26:53 +00001598 // If we are about to resolve types, make sure the type cache is clear.
1599 if (NumEntries)
1600 ModuleTypeIDCache.clear();
1601
Reid Spencer060d25d2004-06-29 23:29:38 +00001602 // Loop through reading all of the types. Forward types will make use of the
1603 // opaque types just inserted.
1604 //
1605 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001606 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001607 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001608 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001609 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001610
Misha Brukman8a96c532005-04-21 21:44:41 +00001611 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001612 // the opaque type we previously inserted with the new concrete value. This
1613 // approach helps with forward references to types. The refinement from the
1614 // abstract (opaque) type to the new type causes all uses of the abstract
1615 // type to use the concrete type (NewTy). This will also cause the opaque
1616 // type to be deleted.
1617 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1618
1619 // This should have replaced the old opaque type with the new type in the
1620 // value table... or with a preexisting type that was already in the system.
1621 // Let's just make sure it did.
1622 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1623 }
1624}
1625
Reid Spencer1628cec2006-10-26 06:15:43 +00001626// Upgrade obsolete constant expression opcodes (ver. 5 and prior) to the new
1627// values used after ver 6. bytecode format. The operands are provided to the
1628// function so that decisions based on the operand type can be made when
1629// auto-upgrading obsolete opcodes to the new ones.
1630// NOTE: This code needs to be kept synchronized with handleObsoleteOpcodes.
1631// We can't use that function because of that functions argument requirements.
1632// This function only deals with the subset of opcodes that are applicable to
1633// constant expressions and is therefore simpler than handleObsoleteOpcodes.
1634inline unsigned fixCEOpcodes(
1635 unsigned Opcode, const std::vector<Constant*> &ArgVec
1636) {
1637 switch (Opcode) {
1638 default: // Pass Through
1639 // If we don't match any of the cases here then the opcode is fine the
1640 // way it is.
1641 break;
1642 case 7: // Add
1643 Opcode = Instruction::Add;
1644 break;
1645 case 8: // Sub
1646 Opcode = Instruction::Sub;
1647 break;
1648 case 9: // Mul
1649 Opcode = Instruction::Mul;
1650 break;
1651 case 10: // Div
1652 // The type of the instruction is based on the operands. We need to select
1653 // either udiv or sdiv based on that type. This expression selects the
1654 // cases where the type is floating point or signed in which case we
1655 // generated an sdiv instruction.
1656 if (ArgVec[0]->getType()->isFloatingPoint())
1657 Opcode = Instruction::FDiv;
1658 else if (ArgVec[0]->getType()->isSigned())
1659 Opcode = Instruction::SDiv;
1660 else
1661 Opcode = Instruction::UDiv;
1662 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001663 case 11: // Rem
Reid Spencer0a783f72006-11-02 01:53:59 +00001664 // As with "Div", make the signed/unsigned or floating point Rem
1665 // instruction choice based on the type of the operands.
Reid Spencer1628cec2006-10-26 06:15:43 +00001666 if (ArgVec[0]->getType()->isFloatingPoint())
Reid Spencer0a783f72006-11-02 01:53:59 +00001667 Opcode = Instruction::FRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001668 else if (ArgVec[0]->getType()->isSigned())
Reid Spencer0a783f72006-11-02 01:53:59 +00001669 Opcode = Instruction::SRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001670 else
Reid Spencer0a783f72006-11-02 01:53:59 +00001671 Opcode = Instruction::URem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001672 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001673 case 12: // And
1674 Opcode = Instruction::And;
1675 break;
1676 case 13: // Or
1677 Opcode = Instruction::Or;
1678 break;
1679 case 14: // Xor
1680 Opcode = Instruction::Xor;
1681 break;
1682 case 15: // SetEQ
1683 Opcode = Instruction::SetEQ;
1684 break;
1685 case 16: // SetNE
1686 Opcode = Instruction::SetNE;
1687 break;
1688 case 17: // SetLE
1689 Opcode = Instruction::SetLE;
1690 break;
1691 case 18: // SetGE
1692 Opcode = Instruction::SetGE;
1693 break;
1694 case 19: // SetLT
1695 Opcode = Instruction::SetLT;
1696 break;
1697 case 20: // SetGT
1698 Opcode = Instruction::SetGT;
1699 break;
1700 case 26: // GetElementPtr
1701 Opcode = Instruction::GetElementPtr;
1702 break;
1703 case 28: // Cast
1704 Opcode = Instruction::Cast;
1705 break;
1706 case 30: // Shl
1707 Opcode = Instruction::Shl;
1708 break;
1709 case 31: // Shr
1710 Opcode = Instruction::Shr;
1711 break;
1712 case 34: // Select
1713 Opcode = Instruction::Select;
1714 break;
1715 case 38: // ExtractElement
1716 Opcode = Instruction::ExtractElement;
1717 break;
1718 case 39: // InsertElement
1719 Opcode = Instruction::InsertElement;
1720 break;
1721 case 40: // ShuffleVector
1722 Opcode = Instruction::ShuffleVector;
1723 break;
1724 }
1725 return Opcode;
1726}
1727
Reid Spencer04cde2c2004-07-04 11:33:49 +00001728/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001729Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001730 // We must check for a ConstantExpr before switching by type because
1731 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001732 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001733 // 0 if not expr; numArgs if is expr
1734 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001735
Reid Spencer060d25d2004-06-29 23:29:38 +00001736 if (isExprNumArgs) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001737 if (!hasNoUndefValue) {
1738 // 'undef' is encoded with 'exprnumargs' == 1.
1739 if (isExprNumArgs == 1)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001740 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001741
Chris Lattner3bc5a602006-01-25 23:08:15 +00001742 // Inline asm is encoded with exprnumargs == ~0U.
1743 if (isExprNumArgs == ~0U) {
1744 std::string AsmStr = read_str();
1745 std::string ConstraintStr = read_str();
1746 unsigned Flags = read_vbr_uint();
1747
1748 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1749 const FunctionType *FTy =
1750 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1751
1752 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1753 error("Invalid constraints for inline asm");
1754 if (Flags & ~1U)
1755 error("Invalid flags for inline asm");
1756 bool HasSideEffects = Flags & 1;
1757 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
1758 }
1759
1760 --isExprNumArgs;
1761 }
1762
Reid Spencer060d25d2004-06-29 23:29:38 +00001763 // FIXME: Encoding of constant exprs could be much more compact!
1764 std::vector<Constant*> ArgVec;
1765 ArgVec.reserve(isExprNumArgs);
1766 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001767
1768 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1769 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001770
Reid Spencer060d25d2004-06-29 23:29:38 +00001771 // Read the slot number and types of each of the arguments
1772 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1773 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001774 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001775 if (read_typeid(ArgTypeSlot))
1776 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001777
Reid Spencer060d25d2004-06-29 23:29:38 +00001778 // Get the arg value from its slot if it exists, otherwise a placeholder
1779 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1780 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001781
Reid Spencer1628cec2006-10-26 06:15:43 +00001782 // Handle backwards compatibility for the opcode numbers
1783 if (hasSignlessInstructions)
1784 Opcode = fixCEOpcodes(Opcode, ArgVec);
1785
Reid Spencer060d25d2004-06-29 23:29:38 +00001786 // Construct a ConstantExpr of the appropriate kind
1787 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001788 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001789 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001790
Reid Spencer060d25d2004-06-29 23:29:38 +00001791 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001792 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001793 return Result;
1794 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1795 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1796
1797 if (hasRestrictedGEPTypes) {
1798 const Type *BaseTy = ArgVec[0]->getType();
1799 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1800 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1801 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1802 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1803 if (isa<StructType>(*GTI)) {
1804 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001805 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001806 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1807 }
1808 }
1809
1810 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001811 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001812 return Result;
1813 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001814 if (ArgVec.size() != 3)
1815 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001816 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001817 ArgVec[2]);
1818 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001819 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001820 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001821 if (ArgVec.size() != 2 ||
1822 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1823 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001824 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1825 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1826 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001827 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001828 if (ArgVec.size() != 3 ||
1829 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1830 error("Invalid insertelement constand expr arguments");
1831
1832 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001833 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1834 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1835 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001836 } else if (Opcode == Instruction::ShuffleVector) {
1837 if (ArgVec.size() != 3 ||
1838 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001839 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001840 Constant *Result =
1841 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1842 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1843 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001844 } else { // All other 2-operand expressions
1845 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001846 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001847 return Result;
1848 }
1849 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001850
Reid Spencer060d25d2004-06-29 23:29:38 +00001851 // Ok, not an ConstantExpr. We now know how to read the given type...
1852 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001853 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001854 switch (Ty->getTypeID()) {
1855 case Type::BoolTyID: {
1856 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001857 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001858 error("Invalid boolean value read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001859 Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001860 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001861 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001862 }
1863
1864 case Type::UByteTyID: // Unsigned integer types...
1865 case Type::UShortTyID:
1866 case Type::UIntTyID: {
1867 unsigned Val = read_vbr_uint();
Reid Spencerb83eb642006-10-20 07:07:24 +00001868 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
Reid Spencer24399722004-07-09 22:21:33 +00001869 error("Invalid unsigned byte/short/int read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001870 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001871 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001872 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001873 }
1874
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001875 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +00001876 Result = ConstantInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001877 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001878 break;
1879
Reid Spencer060d25d2004-06-29 23:29:38 +00001880 case Type::SByteTyID: // Signed integer types...
1881 case Type::ShortTyID:
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001882 case Type::IntTyID:
1883 case Type::LongTyID: {
Reid Spencer060d25d2004-06-29 23:29:38 +00001884 int64_t Val = read_vbr_int64();
Reid Spencerb83eb642006-10-20 07:07:24 +00001885 if (!ConstantInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001886 error("Invalid signed byte/short/int/long read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001887 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001888 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001889 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001890 }
1891
1892 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001893 float Val;
1894 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001895 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001896 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001897 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001898 }
1899
1900 case Type::DoubleTyID: {
1901 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001902 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001903 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001904 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001905 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001906 }
1907
Reid Spencer060d25d2004-06-29 23:29:38 +00001908 case Type::ArrayTyID: {
1909 const ArrayType *AT = cast<ArrayType>(Ty);
1910 unsigned NumElements = AT->getNumElements();
1911 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1912 std::vector<Constant*> Elements;
1913 Elements.reserve(NumElements);
1914 while (NumElements--) // Read all of the elements of the constant.
1915 Elements.push_back(getConstantValue(TypeSlot,
1916 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001917 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001918 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001919 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001920 }
1921
1922 case Type::StructTyID: {
1923 const StructType *ST = cast<StructType>(Ty);
1924
1925 std::vector<Constant *> Elements;
1926 Elements.reserve(ST->getNumElements());
1927 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1928 Elements.push_back(getConstantValue(ST->getElementType(i),
1929 read_vbr_uint()));
1930
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001931 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001932 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001933 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001934 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001935
Brian Gaeke715c90b2004-08-20 06:00:58 +00001936 case Type::PackedTyID: {
1937 const PackedType *PT = cast<PackedType>(Ty);
1938 unsigned NumElements = PT->getNumElements();
1939 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1940 std::vector<Constant*> Elements;
1941 Elements.reserve(NumElements);
1942 while (NumElements--) // Read all of the elements of the constant.
1943 Elements.push_back(getConstantValue(TypeSlot,
1944 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001945 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001946 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001947 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001948 }
1949
Chris Lattner638c3812004-11-19 16:24:05 +00001950 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001951 const PointerType *PT = cast<PointerType>(Ty);
1952 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001953
Reid Spencer060d25d2004-06-29 23:29:38 +00001954 // Check to see if we have already read this global variable...
1955 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001956 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001957 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1958 if (!GV) error("GlobalValue not in ValueTable!");
1959 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1960 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001961 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001962 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001963 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001964 }
1965
1966 default:
Reid Spencer24399722004-07-09 22:21:33 +00001967 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001968 Ty->getDescription());
1969 break;
1970 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001971
1972 // Check that we didn't read a null constant if they are implicit for this
1973 // type plane. Do not do this check for constantexprs, as they may be folded
1974 // to a null value in a way that isn't predicted when a .bc file is initially
1975 // produced.
1976 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1977 !hasImplicitNull(TypeID) &&
1978 "Cannot read null values from bytecode!");
1979 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001980}
1981
Misha Brukman8a96c532005-04-21 21:44:41 +00001982/// Resolve references for constants. This function resolves the forward
1983/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001984/// replaceAllUsesWith method of Value class to substitute the placeholder
1985/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001986void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1987 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001988 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001989 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001990 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001991
Chris Lattner29b789b2003-11-19 17:27:18 +00001992 Value *PH = I->second; // Get the placeholder...
1993 PH->replaceAllUsesWith(NewV);
1994 delete PH; // Delete the old placeholder
1995 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001996}
1997
Reid Spencer04cde2c2004-07-04 11:33:49 +00001998/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001999void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
2000 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002001 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00002002 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00002003 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00002004 const Type *Ty = getType(Typ);
2005 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002006 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00002007
Reid Spencer060d25d2004-06-29 23:29:38 +00002008 const ArrayType *ATy = cast<ArrayType>(Ty);
2009 if (ATy->getElementType() != Type::SByteTy &&
2010 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00002011 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00002012
Reid Spencer060d25d2004-06-29 23:29:38 +00002013 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00002014 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00002015 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00002016
Reid Spencer060d25d2004-06-29 23:29:38 +00002017 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00002018 const Type* ElemType = ATy->getElementType();
2019 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
2020 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00002021
Reid Spencer060d25d2004-06-29 23:29:38 +00002022 // Create the constant, inserting it as needed.
2023 Constant *C = ConstantArray::get(ATy, Elements);
2024 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00002025 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00002026 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00002027 }
Misha Brukman12c29d12003-09-22 23:38:23 +00002028}
2029
Reid Spencer04cde2c2004-07-04 11:33:49 +00002030/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00002031void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002032 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00002033 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002034 if (Handler) Handler->handleGlobalConstantsBegin();
2035
2036 /// In LLVM 1.3 Type does not derive from Value so the types
2037 /// do not occupy a plane. Consequently, we read the types
2038 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00002039 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002040 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00002041 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00002042 }
2043
Reid Spencer46b002c2004-07-11 17:28:43 +00002044 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002045 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00002046 unsigned Typ = 0;
2047 bool isTypeType = read_typeid(Typ);
2048
2049 /// In LLVM 1.2 and before, Types were written to the
2050 /// bytecode file in the "Type Type" plane (#12).
2051 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00002052 if (isTypeType) {
2053 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00002054 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002055 /// Use of Type::VoidTyID is a misnomer. It actually means
2056 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00002057 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
2058 ParseStringConstants(NumEntries, Tab);
2059 } else {
2060 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00002061 Value *V = ParseConstantPoolValue(Typ);
2062 assert(V && "ParseConstantPoolValue returned NULL!");
2063 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00002064
Reid Spencer060d25d2004-06-29 23:29:38 +00002065 // If we are reading a function constant table, make sure that we adjust
2066 // the slot number to be the real global constant number.
2067 //
2068 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
2069 ModuleValues[Typ])
2070 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00002071 if (Constant *C = dyn_cast<Constant>(V))
2072 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002073 }
2074 }
2075 }
Chris Lattner02dce162004-12-04 05:28:27 +00002076
2077 // After we have finished parsing the constant pool, we had better not have
2078 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00002079 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00002080 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00002081 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00002082 error(utostr(ConstantFwdRefs.size()) +
2083 " unresolved constant reference exist. First one is '" +
2084 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00002085 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00002086 }
Chris Lattner02dce162004-12-04 05:28:27 +00002087
Reid Spencer060d25d2004-06-29 23:29:38 +00002088 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002089 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00002090}
Chris Lattner00950542001-06-06 20:29:01 +00002091
Reid Spencer04cde2c2004-07-04 11:33:49 +00002092/// Parse the contents of a function. Note that this function can be
2093/// called lazily by materializeFunction
2094/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00002095void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002096
2097 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00002098 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
2099
Reid Spencer060d25d2004-06-29 23:29:38 +00002100 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00002101 switch (LinkageType) {
2102 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2103 case 1: Linkage = GlobalValue::WeakLinkage; break;
2104 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2105 case 3: Linkage = GlobalValue::InternalLinkage; break;
2106 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002107 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
2108 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
2109 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002110 default:
Reid Spencer24399722004-07-09 22:21:33 +00002111 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00002112 Linkage = GlobalValue::InternalLinkage;
2113 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002114 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00002115
Reid Spencer46b002c2004-07-11 17:28:43 +00002116 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00002117 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00002118
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002119 // Keep track of how many basic blocks we have read in...
2120 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00002121 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002122
Reid Spencer060d25d2004-06-29 23:29:38 +00002123 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00002124 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00002125 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00002126 BufPtr OldAt = At;
2127 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00002128
2129 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00002130 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00002131 if (!InsertedArguments) {
2132 // Insert arguments into the value table before we parse the first basic
2133 // block in the function, but after we potentially read in the
2134 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00002135 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002136 InsertedArguments = true;
2137 }
2138
Reid Spencer04cde2c2004-07-04 11:33:49 +00002139 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00002140 break;
2141
Reid Spencerad89bd62004-07-25 18:07:36 +00002142 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002143 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00002144 break;
2145
Chris Lattner00950542001-06-06 20:29:01 +00002146 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00002147 if (!InsertedArguments) {
2148 // Insert arguments into the value table before we parse the first basic
2149 // block in the function, but after we potentially read in the
2150 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00002151 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002152 InsertedArguments = true;
2153 }
2154
Reid Spencer060d25d2004-06-29 23:29:38 +00002155 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002156 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00002157 break;
2158 }
2159
Reid Spencerad89bd62004-07-25 18:07:36 +00002160 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00002161 // Insert arguments into the value table before we parse the instruction
2162 // list for the function, but after we potentially read in the compaction
2163 // table.
2164 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002165 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002166 InsertedArguments = true;
2167 }
2168
Misha Brukman8a96c532005-04-21 21:44:41 +00002169 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00002170 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002171 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00002172 break;
2173 }
2174
Reid Spencerad89bd62004-07-25 18:07:36 +00002175 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002176 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002177 break;
2178
2179 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002180 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00002181 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00002182 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00002183 break;
2184 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002185 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00002186
Misha Brukman12c29d12003-09-22 23:38:23 +00002187 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00002188 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002189 }
2190
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002191 // Make sure there were no references to non-existant basic blocks.
2192 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00002193 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00002194
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002195 ParsedBasicBlocks.clear();
2196
Chris Lattner97330cf2003-10-09 23:10:14 +00002197 // Resolve forward references. Replace any uses of a forward reference value
2198 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002199 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00002200 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
2201 I = ForwardReferences.begin();
2202 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002203 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00002204 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002205 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002206 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00002207 }
Chris Lattner00950542001-06-06 20:29:01 +00002208
Reid Spencere2a5fb02006-01-27 11:49:27 +00002209 // If upgraded intrinsic functions were detected during reading of the
2210 // module information, then we need to look for instructions that need to
2211 // be upgraded. This can't be done while the instructions are read in because
2212 // additional instructions inserted mess up the slot numbering.
2213 if (!upgradedFunctions.empty()) {
2214 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
2215 for (BasicBlock::iterator II = BI->begin(), IE = BI->end();
Jim Laskeyf4321a32006-03-13 13:07:37 +00002216 II != IE;)
2217 if (CallInst* CI = dyn_cast<CallInst>(II++)) {
Reid Spencere2a5fb02006-01-27 11:49:27 +00002218 std::map<Function*,Function*>::iterator FI =
2219 upgradedFunctions.find(CI->getCalledFunction());
Chris Lattnerbad08002006-03-02 23:59:12 +00002220 if (FI != upgradedFunctions.end())
2221 UpgradeIntrinsicCall(CI, FI->second);
Reid Spencere2a5fb02006-01-27 11:49:27 +00002222 }
2223 }
2224
Misha Brukman12c29d12003-09-22 23:38:23 +00002225 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00002226 FunctionTypes.clear();
2227 CompactionTypes.clear();
2228 CompactionValues.clear();
2229 freeTable(FunctionValues);
2230
Reid Spencer04cde2c2004-07-04 11:33:49 +00002231 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00002232}
2233
Reid Spencer04cde2c2004-07-04 11:33:49 +00002234/// This function parses LLVM functions lazily. It obtains the type of the
2235/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00002236/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00002237/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00002238void BytecodeReader::ParseFunctionLazily() {
2239 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002240 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00002241
Reid Spencer060d25d2004-06-29 23:29:38 +00002242 Function *Func = FunctionSignatureList.back();
2243 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00002244
Reid Spencer060d25d2004-06-29 23:29:38 +00002245 // Save the information for future reading of the function
2246 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00002247
Misha Brukmana3e6ad62004-11-14 21:02:55 +00002248 // This function has a body but it's not loaded so it appears `External'.
2249 // Mark it as a `Ghost' instead to notify the users that it has a body.
2250 Func->setLinkage(GlobalValue::GhostLinkage);
2251
Reid Spencer060d25d2004-06-29 23:29:38 +00002252 // Pretend we've `parsed' this function
2253 At = BlockEnd;
2254}
Chris Lattner89e02532004-01-18 21:08:15 +00002255
Misha Brukman8a96c532005-04-21 21:44:41 +00002256/// The ParserFunction method lazily parses one function. Use this method to
2257/// casue the parser to parse a specific function in the module. Note that
2258/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00002259/// ParseAllFunctionBodies.
2260/// @see ParseAllFunctionBodies
2261/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002262bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
2263
2264 if (setjmp(context))
2265 return true;
2266
Reid Spencer060d25d2004-06-29 23:29:38 +00002267 // Find {start, end} pointers and slot in the map. If not there, we're done.
2268 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00002269
Reid Spencer060d25d2004-06-29 23:29:38 +00002270 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00002271 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00002272 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00002273 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00002274 }
2275
Reid Spencer060d25d2004-06-29 23:29:38 +00002276 BlockStart = At = Fi->second.Buf;
2277 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00002278 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00002279
2280 LazyFunctionLoadMap.erase(Fi);
2281
Reid Spencer46b002c2004-07-11 17:28:43 +00002282 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00002283 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00002284}
2285
Reid Spencer04cde2c2004-07-04 11:33:49 +00002286/// The ParseAllFunctionBodies method parses through all the previously
2287/// unparsed functions in the bytecode file. If you want to completely parse
2288/// a bytecode file, this method should be called after Parsebytecode because
2289/// Parsebytecode only records the locations in the bytecode file of where
2290/// the function definitions are located. This function uses that information
2291/// to materialize the functions.
2292/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002293bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
2294 if (setjmp(context))
2295 return true;
2296
Reid Spencer060d25d2004-06-29 23:29:38 +00002297 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
2298 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00002299
Reid Spencer46b002c2004-07-11 17:28:43 +00002300 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002301 Function* Func = Fi->first;
2302 BlockStart = At = Fi->second.Buf;
2303 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002304 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002305 ++Fi;
2306 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002307 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00002308 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00002309}
Chris Lattner89e02532004-01-18 21:08:15 +00002310
Reid Spencer04cde2c2004-07-04 11:33:49 +00002311/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00002312void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002313 // Read the number of types
2314 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00002315
2316 // Ignore the type plane identifier for types if the bc file is pre 1.3
2317 if (hasTypeDerivedFromValue)
2318 read_vbr_uint();
2319
Reid Spencer46b002c2004-07-11 17:28:43 +00002320 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00002321}
2322
Reid Spencer04cde2c2004-07-04 11:33:49 +00002323/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00002324void BytecodeReader::ParseModuleGlobalInfo() {
2325
Reid Spencer04cde2c2004-07-04 11:33:49 +00002326 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00002327
Chris Lattner404cddf2005-11-12 01:33:40 +00002328 // SectionID - If a global has an explicit section specified, this map
2329 // remembers the ID until we can translate it into a string.
2330 std::map<GlobalValue*, unsigned> SectionID;
2331
Chris Lattner70cc3392001-09-10 07:58:01 +00002332 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002333 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002334 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00002335 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
2336 // Linkage, bit4+ = slot#
2337 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00002338 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00002339 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00002340 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00002341 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002342 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002343 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00002344 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002345
2346 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
2347 if (LinkageID == 3 && !hasInitializer) {
2348 unsigned ExtWord = read_vbr_uint();
2349 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
2350 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
2351 hasInitializer = ExtWord & 1;
2352 LinkageID = (ExtWord >> 1) & 7;
2353 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00002354
2355 if (ExtWord & (1 << 9)) // Has a section ID.
2356 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002357 }
Chris Lattnere3869c82003-04-16 21:16:05 +00002358
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002359 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002360 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00002361 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2362 case 1: Linkage = GlobalValue::WeakLinkage; break;
2363 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2364 case 3: Linkage = GlobalValue::InternalLinkage; break;
2365 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002366 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
2367 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
2368 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00002369 default:
Reid Spencer24399722004-07-09 22:21:33 +00002370 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00002371 Linkage = GlobalValue::InternalLinkage;
2372 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002373 }
2374
2375 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00002376 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00002377 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00002378
Chris Lattnere73bd452005-11-06 07:43:39 +00002379 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002380 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00002381
Chris Lattner52e20b02003-03-19 20:54:26 +00002382 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00002383
Chris Lattner70cc3392001-09-10 07:58:01 +00002384 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00002385 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00002386 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002387 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00002388 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00002389
Chris Lattner404cddf2005-11-12 01:33:40 +00002390 if (GlobalSectionID != 0)
2391 SectionID[GV] = GlobalSectionID;
2392
Reid Spencer060d25d2004-06-29 23:29:38 +00002393 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00002394 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002395 initSlot = read_vbr_uint();
2396 GlobalInits.push_back(std::make_pair(GV, initSlot));
2397 }
2398
2399 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00002400 if (Handler)
2401 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002402
2403 // Get next item
2404 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002405 }
2406
Chris Lattner52e20b02003-03-19 20:54:26 +00002407 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002408 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00002409
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002410 if (hasNoFlagsForFunctions)
2411 FnSignature = (FnSignature << 5) + 1;
2412
2413 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00002414 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
2415 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00002416 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00002417 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002418 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00002419 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00002420 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00002421
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002422 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00002423 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00002424 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00002425
Chris Lattner18549c22004-11-15 21:43:03 +00002426 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00002427 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002428 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00002429
Chris Lattnere73bd452005-11-06 07:43:39 +00002430 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002431
2432 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00002433 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00002434
Chris Lattner97fbc502004-11-15 22:38:52 +00002435 // Save this for later so we know type of lazily instantiated functions.
2436 // Note that known-external functions do not have FunctionInfo blocks, so we
2437 // do not add them to the FunctionSignatureList.
2438 if ((Flags & (1 << 4)) == 0)
2439 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00002440
Chris Lattnere73bd452005-11-06 07:43:39 +00002441 // Get the calling convention from the low bits.
2442 unsigned CC = Flags & 15;
2443 unsigned Alignment = 0;
2444 if (FnSignature & (1 << 31)) { // Has extension word?
2445 unsigned ExtWord = read_vbr_uint();
2446 Alignment = (1 << (ExtWord & 31)) >> 1;
2447 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00002448
2449 if (ExtWord & (1 << 10)) // Has a section ID.
2450 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002451
2452 // Parse external declaration linkage
2453 switch ((ExtWord >> 11) & 3) {
2454 case 0: break;
2455 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
2456 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
2457 default: assert(0 && "Unsupported external linkage");
2458 }
Chris Lattnere73bd452005-11-06 07:43:39 +00002459 }
2460
Chris Lattner54b369e2005-11-06 07:46:13 +00002461 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00002462 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00002463
Reid Spencer04cde2c2004-07-04 11:33:49 +00002464 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002465
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002466 // Get the next function signature.
2467 FnSignature = read_vbr_uint();
2468 if (hasNoFlagsForFunctions)
2469 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00002470 }
2471
Misha Brukman8a96c532005-04-21 21:44:41 +00002472 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002473 // remove elements efficiently from the back of the vector.
2474 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002475
Chris Lattner404cddf2005-11-12 01:33:40 +00002476 /// SectionNames - This contains the list of section names encoded in the
2477 /// moduleinfoblock. Functions and globals with an explicit section index
2478 /// into this to get their section name.
2479 std::vector<std::string> SectionNames;
2480
2481 if (hasInconsistentModuleGlobalInfo) {
2482 align32();
2483 } else if (!hasNoDependentLibraries) {
2484 // If this bytecode format has dependent library information in it, read in
2485 // the number of dependent library items that follow.
Reid Spencerad89bd62004-07-25 18:07:36 +00002486 unsigned num_dep_libs = read_vbr_uint();
2487 std::string dep_lib;
Chris Lattner404cddf2005-11-12 01:33:40 +00002488 while (num_dep_libs--) {
Reid Spencerad89bd62004-07-25 18:07:36 +00002489 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00002490 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002491 if (Handler)
2492 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002493 }
2494
Chris Lattner404cddf2005-11-12 01:33:40 +00002495 // Read target triple and place into the module.
Reid Spencerad89bd62004-07-25 18:07:36 +00002496 std::string triple = read_str();
2497 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00002498 if (Handler)
2499 Handler->handleTargetTriple(triple);
Chris Lattner404cddf2005-11-12 01:33:40 +00002500
Chris Lattner7e6db762006-01-23 23:43:17 +00002501 if (!hasAlignment && At != BlockEnd) {
Chris Lattner404cddf2005-11-12 01:33:40 +00002502 // If the file has section info in it, read the section names now.
2503 unsigned NumSections = read_vbr_uint();
2504 while (NumSections--)
2505 SectionNames.push_back(read_str());
2506 }
Chris Lattner7e6db762006-01-23 23:43:17 +00002507
2508 // If the file has module-level inline asm, read it now.
2509 if (!hasAlignment && At != BlockEnd)
Chris Lattner66316012006-01-24 04:14:29 +00002510 TheModule->setModuleInlineAsm(read_str());
Reid Spencerad89bd62004-07-25 18:07:36 +00002511 }
2512
Chris Lattner404cddf2005-11-12 01:33:40 +00002513 // If any globals are in specified sections, assign them now.
2514 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2515 SectionID.end(); I != E; ++I)
2516 if (I->second) {
2517 if (I->second > SectionID.size())
2518 error("SectionID out of range for global!");
2519 I->first->setSection(SectionNames[I->second-1]);
2520 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002521
Chris Lattner00950542001-06-06 20:29:01 +00002522 // This is for future proofing... in the future extra fields may be added that
2523 // we don't understand, so we transparently ignore them.
2524 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002525 At = BlockEnd;
2526
Reid Spencer04cde2c2004-07-04 11:33:49 +00002527 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002528}
2529
Reid Spencer04cde2c2004-07-04 11:33:49 +00002530/// Parse the version information and decode it by setting flags on the
2531/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002532void BytecodeReader::ParseVersionInfo() {
2533 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002534
2535 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002536 Module::Endianness Endianness;
2537 Module::PointerSize PointerSize;
2538 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2539 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2540
2541 bool hasNoEndianness = Version & 4;
2542 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002543
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002544 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002545
2546 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002547 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002548 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002549 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002550 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002551 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002552 has32BitTypes = false;
2553 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002554 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002555 hasNoUndefValue = false;
2556 hasNoFlagsForFunctions = false;
2557 hasNoUnreachableInst = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00002558 hasSignlessInstructions = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002559
Reid Spencer1628cec2006-10-26 06:15:43 +00002560 // Determine which backwards compatibility flags to set based on the
2561 // bytecode file's version number
Chris Lattner036b8aa2003-03-06 17:55:45 +00002562 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002563 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002564 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002565 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002566 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002567
Chris Lattner80b97342004-01-17 23:25:43 +00002568 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002569
2570 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002571 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002572
2573 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2574 // included the size for the alignment at the end, where the rest of the
2575 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002576
2577 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2578 // structures and longs for sequential types.
2579 hasRestrictedGEPTypes = true;
2580
Reid Spencer04cde2c2004-07-04 11:33:49 +00002581 // LLVM 1.2 and before had the Type class derive from Value class. This
2582 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002583 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002584 // type planes for Values.
2585 hasTypeDerivedFromValue = true;
2586
Chris Lattner5fa428f2004-04-05 01:27:26 +00002587 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002588
Reid Spencer5b472d92004-08-21 20:49:23 +00002589 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002590
Reid Spencer5b472d92004-08-21 20:49:23 +00002591 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002592 // especially for small files where the 8 bytes per block is a large
2593 // fraction of the total block size. In LLVM 1.3, the block type and length
2594 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2595 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002596 hasLongBlockHeaders = true;
2597
Reid Spencer5b472d92004-08-21 20:49:23 +00002598 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002599 // this has been reduced to vbr_uint24. It shouldn't make much difference
2600 // since we haven't run into a module with > 24 million types, but for
2601 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2602 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002603 has32BitTypes = true;
2604
Misha Brukman8a96c532005-04-21 21:44:41 +00002605 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002606 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2607 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002608 hasNoDependentLibraries = true;
2609
2610 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002611
2612 case 3: // LLVM 1.3 (Released)
2613 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002614 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002615 // of GEP references to a constant array), this can increase the file size
2616 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002617 hasAlignment = true;
2618
2619 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002620
Reid Spencer5b472d92004-08-21 20:49:23 +00002621 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002622 // In version 4, we did not support the 'undef' constant.
2623 hasNoUndefValue = true;
2624
2625 // In version 4 and above, we did not include space for flags for functions
2626 // in the module info block.
2627 hasNoFlagsForFunctions = true;
2628
2629 // In version 4 and above, we did not include the 'unreachable' instruction
2630 // in the opcode numbering in the bytecode file.
2631 hasNoUnreachableInst = true;
2632
2633 // FALL THROUGH
2634
Chris Lattnerdee199f2005-05-06 22:34:01 +00002635 case 5: // 1.4 (Released)
Reid Spencer1628cec2006-10-26 06:15:43 +00002636 // In version 5 and prior, instructions were signless while integer types
2637 // were signed. In version 6, instructions became signed and types became
2638 // signless. For example in version 5 we have the DIV instruction but in
2639 // version 6 we have FDIV, SDIV and UDIV to replace it. This caused a
2640 // renumbering of the instruction codes in version 6 that must be dealt with
2641 // when reading old bytecode files.
2642 hasSignlessInstructions = true;
2643
2644 // FALL THROUGH
2645
2646 case 6: // SignlessTypes Implementation (1.9 release)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002647 break;
2648
Chris Lattner036b8aa2003-03-06 17:55:45 +00002649 default:
Reid Spencer24399722004-07-09 22:21:33 +00002650 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002651 }
2652
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002653 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2654 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002655
Brian Gaekefe2102b2004-07-14 20:33:13 +00002656 TheModule->setEndianness(Endianness);
2657 TheModule->setPointerSize(PointerSize);
2658
Reid Spencer46b002c2004-07-11 17:28:43 +00002659 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002660}
2661
Reid Spencer04cde2c2004-07-04 11:33:49 +00002662/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002663void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002664 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002665
Reid Spencer060d25d2004-06-29 23:29:38 +00002666 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002667
2668 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002669 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002670 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002671
Reid Spencer060d25d2004-06-29 23:29:38 +00002672 bool SeenModuleGlobalInfo = false;
2673 bool SeenGlobalTypePlane = false;
2674 BufPtr MyEnd = BlockEnd;
2675 while (At < MyEnd) {
2676 BufPtr OldAt = At;
2677 read_block(Type, Size);
2678
Chris Lattner00950542001-06-06 20:29:01 +00002679 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002680
Reid Spencerad89bd62004-07-25 18:07:36 +00002681 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002682 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002683 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002684
Reid Spencer5b472d92004-08-21 20:49:23 +00002685 if (Size > 0)
2686 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002687 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002688 break;
2689
Misha Brukman8a96c532005-04-21 21:44:41 +00002690 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002691 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002692 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002693 ParseModuleGlobalInfo();
2694 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002695 break;
2696
Reid Spencerad89bd62004-07-25 18:07:36 +00002697 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002698 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002699 break;
2700
Reid Spencerad89bd62004-07-25 18:07:36 +00002701 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002702 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002703 break;
Chris Lattner00950542001-06-06 20:29:01 +00002704
Reid Spencerad89bd62004-07-25 18:07:36 +00002705 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002706 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002707 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002708
Chris Lattner00950542001-06-06 20:29:01 +00002709 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002710 At += Size;
2711 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002712 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002713 }
Chris Lattner00950542001-06-06 20:29:01 +00002714 break;
2715 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002716 BlockEnd = MyEnd;
2717 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002718 }
2719
Chris Lattner52e20b02003-03-19 20:54:26 +00002720 // After the module constant pool has been read, we can safely initialize
2721 // global variables...
2722 while (!GlobalInits.empty()) {
2723 GlobalVariable *GV = GlobalInits.back().first;
2724 unsigned Slot = GlobalInits.back().second;
2725 GlobalInits.pop_back();
2726
2727 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002728 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002729
2730 const llvm::PointerType* GVType = GV->getType();
2731 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002732 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002733 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002734 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002735 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002736 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002737 } else
Reid Spencer24399722004-07-09 22:21:33 +00002738 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002739 }
2740
Chris Lattneraba5ff52005-05-05 20:57:00 +00002741 if (!ConstantFwdRefs.empty())
2742 error("Use of undefined constants in a module");
2743
Reid Spencer060d25d2004-06-29 23:29:38 +00002744 /// Make sure we pulled them all out. If we didn't then there's a declaration
2745 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002746 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002747 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002748}
2749
Reid Spencer04cde2c2004-07-04 11:33:49 +00002750/// This function completely parses a bytecode buffer given by the \p Buf
2751/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002752bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002753 const std::string &ModuleID,
2754 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002755
Reid Spencer233fe722006-08-22 16:09:19 +00002756 /// We handle errors by
2757 if (setjmp(context)) {
2758 // Cleanup after error
2759 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002760 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002761 delete TheModule;
2762 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002763 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002764 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002765 decompressedBlock = 0;
2766 }
Reid Spencer233fe722006-08-22 16:09:19 +00002767 // Set caller's error message, if requested
2768 if (ErrMsg)
2769 *ErrMsg = ErrorMsg;
2770 // Indicate an error occurred
2771 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002772 }
Reid Spencer233fe722006-08-22 16:09:19 +00002773
2774 RevisionNum = 0;
2775 At = MemStart = BlockStart = Buf;
2776 MemEnd = BlockEnd = Buf + Length;
2777
2778 // Create the module
2779 TheModule = new Module(ModuleID);
2780
2781 if (Handler) Handler->handleStart(TheModule, Length);
2782
2783 // Read the four bytes of the signature.
2784 unsigned Sig = read_uint();
2785
2786 // If this is a compressed file
2787 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2788
2789 // Invoke the decompression of the bytecode. Note that we have to skip the
2790 // file's magic number which is not part of the compressed block. Hence,
2791 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2792 // member for retention until BytecodeReader is destructed.
2793 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2794 (char*)Buf+4,Length-4,decompressedBlock);
2795
2796 // We must adjust the buffer pointers used by the bytecode reader to point
2797 // into the new decompressed block. After decompression, the
2798 // decompressedBlock will point to a contiguous memory area that has
2799 // the decompressed data.
2800 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2801 MemEnd = BlockEnd = Buf + decompressedLength;
2802
2803 // else if this isn't a regular (uncompressed) bytecode file, then its
2804 // and error, generate that now.
2805 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2806 error("Invalid bytecode signature: " + utohexstr(Sig));
2807 }
2808
2809 // Tell the handler we're starting a module
2810 if (Handler) Handler->handleModuleBegin(ModuleID);
2811
2812 // Get the module block and size and verify. This is handled specially
2813 // because the module block/size is always written in long format. Other
2814 // blocks are written in short format so the read_block method is used.
2815 unsigned Type, Size;
2816 Type = read_uint();
2817 Size = read_uint();
2818 if (Type != BytecodeFormat::ModuleBlockID) {
2819 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2820 + utostr(Size));
2821 }
2822
2823 // It looks like the darwin ranlib program is broken, and adds trailing
2824 // garbage to the end of some bytecode files. This hack allows the bc
2825 // reader to ignore trailing garbage on bytecode files.
2826 if (At + Size < MemEnd)
2827 MemEnd = BlockEnd = At+Size;
2828
2829 if (At + Size != MemEnd)
2830 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2831 + ", Size:" + utostr(Size));
2832
2833 // Parse the module contents
2834 this->ParseModule();
2835
2836 // Check for missing functions
2837 if (hasFunctions())
2838 error("Function expected, but bytecode stream ended!");
2839
2840 // Look for intrinsic functions to upgrade, upgrade them, and save the
2841 // mapping from old function to new for use later when instructions are
2842 // converted.
2843 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2844 FI != FE; ++FI)
2845 if (Function* newF = UpgradeIntrinsicFunction(FI)) {
2846 upgradedFunctions.insert(std::make_pair(FI, newF));
2847 FI->setName("");
2848 }
2849
2850 // Tell the handler we're done with the module
2851 if (Handler)
2852 Handler->handleModuleEnd(ModuleID);
2853
2854 // Tell the handler we're finished the parse
2855 if (Handler) Handler->handleFinish();
2856
2857 return false;
2858
Chris Lattner00950542001-06-06 20:29:01 +00002859}
Reid Spencer060d25d2004-06-29 23:29:38 +00002860
2861//===----------------------------------------------------------------------===//
2862//=== Default Implementations of Handler Methods
2863//===----------------------------------------------------------------------===//
2864
2865BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002866