blob: 353f29c4b2a49760c96c0b916b3ffcdcb535136a [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
12// Note that this library should be as fast as possible, reentrant, and
13// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/Constants.h"
23#include "llvm/iMemory.h"
24#include "llvm/iOther.h"
25#include "llvm/iPHINode.h"
26#include "llvm/iTerminators.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Misha Brukman12c29d12003-09-22 23:38:23 +000029#include "Support/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include <sstream>
31
Chris Lattner29b789b2003-11-19 17:27:18 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Reid Spencer060d25d2004-06-29 23:29:38 +000034/// A convenience macro for calling the handler. Makes maintenance easier in
35/// case the interface to handler methods changes.
36#define HANDLE(method) \
37 if ( Handler ) Handler->handle ## method
Chris Lattner9e460f22003-10-04 20:00:03 +000038
Reid Spencer060d25d2004-06-29 23:29:38 +000039/// A convenience macro for handling parsing errors.
40#define PARSE_ERROR(inserters) { \
41 std::ostringstream errormsg; \
42 errormsg << inserters; \
43 throw std::string(errormsg.str()); \
Chris Lattner89e02532004-01-18 21:08:15 +000044 }
45
Reid Spencer060d25d2004-06-29 23:29:38 +000046/// @brief A class for maintaining the slot number definition
47/// as a placeholder for the actual definition.
48template<class SuperType>
49class PlaceholderDef : public SuperType {
50 unsigned ID;
51 PlaceholderDef(); // DO NOT IMPLEMENT
52 void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
53public:
54 PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
55 unsigned getID() { return ID; }
56};
Chris Lattner9e460f22003-10-04 20:00:03 +000057
Reid Spencer060d25d2004-06-29 23:29:38 +000058struct ConstantPlaceHolderHelper : public ConstantExpr {
59 ConstantPlaceHolderHelper(const Type *Ty)
60 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty) {}
61};
62
63typedef PlaceholderDef<ConstantPlaceHolderHelper> ConstPHolder;
64
65//===----------------------------------------------------------------------===//
66// Bytecode Reading Methods
67//===----------------------------------------------------------------------===//
68
69inline bool BytecodeReader::moreInBlock() {
70 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000071}
72
Reid Spencer060d25d2004-06-29 23:29:38 +000073inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
74 if ( At > BlockEnd )
75 PARSE_ERROR("Attempt to read past the end of " << block_name << " block.");
76}
Chris Lattner36392bc2003-10-08 21:18:57 +000077
Reid Spencer060d25d2004-06-29 23:29:38 +000078inline void BytecodeReader::align32() {
79 BufPtr Save = At;
80 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
81 if ( At > Save )
82 HANDLE(Alignment( At - Save ));
83 if (At > BlockEnd)
84 PARSE_ERROR("Ran out of data while aligning!");
85}
86
87inline unsigned BytecodeReader::read_uint() {
88 if (At+4 > BlockEnd)
89 PARSE_ERROR("Ran out of data reading uint!");
90 At += 4;
91 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
92}
93
94inline unsigned BytecodeReader::read_vbr_uint() {
95 unsigned Shift = 0;
96 unsigned Result = 0;
97 BufPtr Save = At;
98
99 do {
100 if (At == BlockEnd)
101 PARSE_ERROR("Ran out of data reading vbr_uint!");
102 Result |= (unsigned)((*At++) & 0x7F) << Shift;
103 Shift += 7;
104 } while (At[-1] & 0x80);
105 HANDLE(VBR32(At-Save));
106 return Result;
107}
108
109inline uint64_t BytecodeReader::read_vbr_uint64() {
110 unsigned Shift = 0;
111 uint64_t Result = 0;
112 BufPtr Save = At;
113
114 do {
115 if (At == BlockEnd)
116 PARSE_ERROR("Ran out of data reading vbr_uint64!");
117 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
118 Shift += 7;
119 } while (At[-1] & 0x80);
120 HANDLE(VBR64(At-Save));
121 return Result;
122}
123
124inline int64_t BytecodeReader::read_vbr_int64() {
125 uint64_t R = read_vbr_uint64();
126 if (R & 1) {
127 if (R != 1)
128 return -(int64_t)(R >> 1);
129 else // There is no such thing as -0 with integers. "-0" really means
130 // 0x8000000000000000.
131 return 1LL << 63;
132 } else
133 return (int64_t)(R >> 1);
134}
135
136inline std::string BytecodeReader::read_str() {
137 unsigned Size = read_vbr_uint();
138 const unsigned char *OldAt = At;
139 At += Size;
140 if (At > BlockEnd) // Size invalid?
141 PARSE_ERROR("Ran out of data reading a string!");
142 return std::string((char*)OldAt, Size);
143}
144
145inline void BytecodeReader::read_data(void *Ptr, void *End) {
146 unsigned char *Start = (unsigned char *)Ptr;
147 unsigned Amount = (unsigned char *)End - Start;
148 if (At+Amount > BlockEnd)
149 PARSE_ERROR("Ran out of data!");
150 std::copy(At, At+Amount, Start);
151 At += Amount;
152}
153
154inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
155 Type = read_uint();
156 Size = read_uint();
157 BlockStart = At;
158 if ( At + Size > BlockEnd )
159 PARSE_ERROR("Attempt to size a block past end of memory");
160 BlockEnd = At + Size;
161 HANDLE(Block( Type, BlockStart, Size ));
162}
163
164//===----------------------------------------------------------------------===//
165// IR Lookup Methods
166//===----------------------------------------------------------------------===//
167
168inline bool BytecodeReader::hasImplicitNull(unsigned TyID ) {
169 if (!hasExplicitPrimitiveZeros)
170 return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
171 TyID != Type::VoidTyID;
172 return TyID >= Type::FirstDerivedTyID;
173}
174
175const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000176 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000177 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000178 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000179
180 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000181 ID -= Type::FirstDerivedTyID;
182
Reid Spencer060d25d2004-06-29 23:29:38 +0000183 if (!CompactionTypes.empty()) {
184 if (ID >= CompactionTypes.size())
185 PARSE_ERROR("Type ID out of range for compaction table!");
186 return CompactionTypes[ID];
Chris Lattner89e02532004-01-18 21:08:15 +0000187 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000188
189 // Is it a module-level type?
Reid Spencer060d25d2004-06-29 23:29:38 +0000190 if (ID < ModuleTypes.size())
191 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000192
Reid Spencer060d25d2004-06-29 23:29:38 +0000193 // Nope, is it a function-level type?
194 ID -= ModuleTypes.size();
195 if (ID < FunctionTypes.size())
196 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000197
Reid Spencer060d25d2004-06-29 23:29:38 +0000198 PARSE_ERROR("Illegal type reference!");
199 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000200}
201
Reid Spencer060d25d2004-06-29 23:29:38 +0000202unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
203 if (Ty->isPrimitiveType())
204 return Ty->getTypeID();
205
206 // Scan the compaction table for the type if needed.
207 if (!CompactionTypes.empty()) {
208 std::vector<const Type*>::const_iterator I =
209 find(CompactionTypes.begin(), CompactionTypes.end(), Ty);
210
211 if (I == CompactionTypes.end())
212 PARSE_ERROR("Couldn't find type specified in compaction table!");
213 return Type::FirstDerivedTyID + (&*I - &CompactionTypes[0]);
214 }
215
216 // Check the function level types first...
217 TypeListTy::iterator I = find(FunctionTypes.begin(), FunctionTypes.end(), Ty);
218
219 if (I != FunctionTypes.end())
220 return Type::FirstDerivedTyID + ModuleTypes.size() +
221 (&*I - &FunctionTypes[0]);
222
223 // Check the module level types now...
224 I = find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
225 if (I == ModuleTypes.end())
226 PARSE_ERROR("Didn't find type in ModuleTypes.");
227 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000228}
229
Reid Spencer060d25d2004-06-29 23:29:38 +0000230const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
231 if (Slot < Type::FirstDerivedTyID) {
232 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
233 assert(Ty && "Not a primitive type ID?");
234 return Ty;
235 }
236 Slot -= Type::FirstDerivedTyID;
237 if (Slot >= ModuleTypes.size())
238 PARSE_ERROR("Illegal compaction table type reference!");
239 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000240}
241
Reid Spencer060d25d2004-06-29 23:29:38 +0000242unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
243 if (Ty->isPrimitiveType())
244 return Ty->getTypeID();
245 TypeListTy::iterator I = find(ModuleTypes.begin(),
246 ModuleTypes.end(), Ty);
247 if (I == ModuleTypes.end())
248 PARSE_ERROR("Didn't find type in ModuleTypes.");
249 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
250}
251
252Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner36392bc2003-10-08 21:18:57 +0000253 assert(type != Type::TypeTyID && "getValue() cannot get types!");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000254 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000255 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000256
Chris Lattner89e02532004-01-18 21:08:15 +0000257 // If there is a compaction table active, it defines the low-level numbers.
258 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000259 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
260 if (Num < CompactionValues[type].size())
261 return CompactionValues[type][Num];
262 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000263 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000264 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000265 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000266
267 // If the type plane was compactified, figure out the global type ID
268 // by adding the derived type ids and the distance.
269 if (CompactionValues.size() > Type::TypeTyID &&
270 !CompactionTypes.empty() &&
271 type >= Type::FirstDerivedTyID) {
272 const Type *Ty = CompactionTypes[type-Type::FirstDerivedTyID];
273 TypeListTy::iterator I =
274 find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
275 assert(I != ModuleTypes.end());
276 GlobalTyID = Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner52f86d62004-01-20 00:54:06 +0000277 }
Chris Lattner00950542001-06-06 20:29:01 +0000278
Reid Spencer060d25d2004-06-29 23:29:38 +0000279 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000280 if (Num == 0)
Reid Spencer060d25d2004-06-29 23:29:38 +0000281 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000282 --Num;
283 }
284
Chris Lattner52f86d62004-01-20 00:54:06 +0000285 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
286 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer060d25d2004-06-29 23:29:38 +0000287 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000288 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000289 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000290 }
291
Reid Spencer060d25d2004-06-29 23:29:38 +0000292 if (FunctionValues.size() > type &&
293 FunctionValues[type] &&
294 Num < FunctionValues[type]->size())
295 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000296
Chris Lattner74734132002-08-17 22:01:27 +0000297 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000298
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000299 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000300 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000301 if (I != ForwardReferences.end() && I->first == KeyValue)
302 return I->second; // We have already created this placeholder
303
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000304 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000305 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000306 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000307}
308
Reid Spencer060d25d2004-06-29 23:29:38 +0000309Value* BytecodeReader::getGlobalTableValue(const Type *Ty, unsigned SlotNo) {
310 // FIXME: getTypeSlot is inefficient!
311 unsigned TyID = getGlobalTableTypeSlot(Ty);
312
313 if (TyID != Type::LabelTyID) {
314 if (SlotNo == 0)
315 return Constant::getNullValue(Ty);
316 --SlotNo;
317 }
318
319 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
320 SlotNo >= ModuleValues[TyID]->size()) {
321 PARSE_ERROR("Corrupt compaction table entry!"
322 << TyID << ", " << SlotNo << ": " << ModuleValues.size() << ", "
323 << (void*)ModuleValues[TyID] << ", "
324 << ModuleValues[TyID]->size() << "\n");
325 }
326 return ModuleValues[TyID]->getOperand(SlotNo);
327}
328
329Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
330 if (Value *V = getValue(TypeSlot, Slot, false))
331 if (Constant *C = dyn_cast<Constant>(V))
332 return C; // If we already have the value parsed, just return it
333 else if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
334 // ConstantPointerRef's are an abomination, but at least they don't have
335 // to infest bytecode files.
336 return ConstantPointerRef::get(GV);
337 else
338 PARSE_ERROR("Reference of a value is expected to be a constant!");
339
340 const Type *Ty = getType(TypeSlot);
341 std::pair<const Type*, unsigned> Key(Ty, Slot);
342 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
343
344 if (I != ConstantFwdRefs.end() && I->first == Key) {
345 return I->second;
346 } else {
347 // Create a placeholder for the constant reference and
348 // keep track of the fact that we have a forward ref to recycle it
349 Constant *C = new ConstPHolder(Ty, Slot);
350
351 // Keep track of the fact that we have a forward ref to recycle it
352 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
353 return C;
354 }
355}
356
357//===----------------------------------------------------------------------===//
358// IR Construction Methods
359//===----------------------------------------------------------------------===//
360
361unsigned BytecodeReader::insertValue(
362 Value *Val, unsigned type, ValueTable &ValueTab) {
363 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
364 !hasImplicitNull(type) &&
365 "Cannot read null values from bytecode!");
366 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
367
368 if (ValueTab.size() <= type)
369 ValueTab.resize(type+1);
370
371 if (!ValueTab[type]) ValueTab[type] = new ValueList();
372
373 ValueTab[type]->push_back(Val);
374
375 bool HasOffset = hasImplicitNull(type);
376 return ValueTab[type]->size()-1 + HasOffset;
377}
378
379void BytecodeReader::insertArguments(Function* F ) {
380 const FunctionType *FT = F->getFunctionType();
381 Function::aiterator AI = F->abegin();
382 for (FunctionType::param_iterator It = FT->param_begin();
383 It != FT->param_end(); ++It, ++AI)
384 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
385}
386
387//===----------------------------------------------------------------------===//
388// Bytecode Parsing Methods
389//===----------------------------------------------------------------------===//
390
391void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
392 BasicBlock* BB) {
393 BufPtr SaveAt = At;
394
395 // Clear instruction data
396 Oprnds.clear();
397 unsigned iType = 0;
398 unsigned Opcode = 0;
399 unsigned Op = read_uint();
400
401 // bits Instruction format: Common to all formats
402 // --------------------------
403 // 01-00: Opcode type, fixed to 1.
404 // 07-02: Opcode
405 Opcode = (Op >> 2) & 63;
406 Oprnds.resize((Op >> 0) & 03);
407
408 // Extract the operands
409 switch (Oprnds.size()) {
410 case 1:
411 // bits Instruction format:
412 // --------------------------
413 // 19-08: Resulting type plane
414 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
415 //
416 iType = (Op >> 8) & 4095;
417 Oprnds[0] = (Op >> 20) & 4095;
418 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
419 Oprnds.resize(0);
420 break;
421 case 2:
422 // bits Instruction format:
423 // --------------------------
424 // 15-08: Resulting type plane
425 // 23-16: Operand #1
426 // 31-24: Operand #2
427 //
428 iType = (Op >> 8) & 255;
429 Oprnds[0] = (Op >> 16) & 255;
430 Oprnds[1] = (Op >> 24) & 255;
431 break;
432 case 3:
433 // bits Instruction format:
434 // --------------------------
435 // 13-08: Resulting type plane
436 // 19-14: Operand #1
437 // 25-20: Operand #2
438 // 31-26: Operand #3
439 //
440 iType = (Op >> 8) & 63;
441 Oprnds[0] = (Op >> 14) & 63;
442 Oprnds[1] = (Op >> 20) & 63;
443 Oprnds[2] = (Op >> 26) & 63;
444 break;
445 case 0:
446 At -= 4; // Hrm, try this again...
447 Opcode = read_vbr_uint();
448 Opcode >>= 2;
449 iType = read_vbr_uint();
450
451 unsigned NumOprnds = read_vbr_uint();
452 Oprnds.resize(NumOprnds);
453
454 if (NumOprnds == 0)
455 PARSE_ERROR("Zero-argument instruction found; this is invalid.");
456
457 for (unsigned i = 0; i != NumOprnds; ++i)
458 Oprnds[i] = read_vbr_uint();
459 align32();
460 break;
461 }
462
463 // Get the type of the instruction
464 const Type *InstTy = getType(iType);
465
466 // Hae enough to inform the handler now
467 HANDLE(Instruction(Opcode, InstTy, Oprnds, At-SaveAt));
468
469 // Declare the resulting instruction we'll build.
470 Instruction *Result = 0;
471
472 // Handle binary operators
473 if (Opcode >= Instruction::BinaryOpsBegin &&
474 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
475 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
476 getValue(iType, Oprnds[0]),
477 getValue(iType, Oprnds[1]));
478
479 switch (Opcode) {
480 default:
481 if (Result == 0) PARSE_ERROR("Illegal instruction read!");
482 break;
483 case Instruction::VAArg:
484 Result = new VAArgInst(getValue(iType, Oprnds[0]), getType(Oprnds[1]));
485 break;
486 case Instruction::VANext:
487 Result = new VANextInst(getValue(iType, Oprnds[0]), getType(Oprnds[1]));
488 break;
489 case Instruction::Cast:
490 Result = new CastInst(getValue(iType, Oprnds[0]), getType(Oprnds[1]));
491 break;
492 case Instruction::Select:
493 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
494 getValue(iType, Oprnds[1]),
495 getValue(iType, Oprnds[2]));
496 break;
497 case Instruction::PHI: {
498 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
499 PARSE_ERROR("Invalid phi node encountered!\n");
500
501 PHINode *PN = new PHINode(InstTy);
502 PN->op_reserve(Oprnds.size());
503 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
504 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
505 Result = PN;
506 break;
507 }
508
509 case Instruction::Shl:
510 case Instruction::Shr:
511 Result = new ShiftInst((Instruction::OtherOps)Opcode,
512 getValue(iType, Oprnds[0]),
513 getValue(Type::UByteTyID, Oprnds[1]));
514 break;
515 case Instruction::Ret:
516 if (Oprnds.size() == 0)
517 Result = new ReturnInst();
518 else if (Oprnds.size() == 1)
519 Result = new ReturnInst(getValue(iType, Oprnds[0]));
520 else
521 PARSE_ERROR("Unrecognized instruction!");
522 break;
523
524 case Instruction::Br:
525 if (Oprnds.size() == 1)
526 Result = new BranchInst(getBasicBlock(Oprnds[0]));
527 else if (Oprnds.size() == 3)
528 Result = new BranchInst(getBasicBlock(Oprnds[0]),
529 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
530 else
531 PARSE_ERROR("Invalid number of operands for a 'br' instruction!");
532 break;
533 case Instruction::Switch: {
534 if (Oprnds.size() & 1)
535 PARSE_ERROR("Switch statement with odd number of arguments!");
536
537 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
538 getBasicBlock(Oprnds[1]));
539 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
540 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
541 getBasicBlock(Oprnds[i+1]));
542 Result = I;
543 break;
544 }
545
546 case Instruction::Call: {
547 if (Oprnds.size() == 0)
548 PARSE_ERROR("Invalid call instruction encountered!");
549
550 Value *F = getValue(iType, Oprnds[0]);
551
552 // Check to make sure we have a pointer to function type
553 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
554 if (PTy == 0) PARSE_ERROR("Call to non function pointer value!");
555 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
556 if (FTy == 0) PARSE_ERROR("Call to non function pointer value!");
557
558 std::vector<Value *> Params;
559 if (!FTy->isVarArg()) {
560 FunctionType::param_iterator It = FTy->param_begin();
561
562 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
563 if (It == FTy->param_end())
564 PARSE_ERROR("Invalid call instruction!");
565 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
566 }
567 if (It != FTy->param_end())
568 PARSE_ERROR("Invalid call instruction!");
569 } else {
570 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
571
572 unsigned FirstVariableOperand;
573 if (Oprnds.size() < FTy->getNumParams())
574 PARSE_ERROR("Call instruction missing operands!");
575
576 // Read all of the fixed arguments
577 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
578 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
579
580 FirstVariableOperand = FTy->getNumParams();
581
582 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
583 PARSE_ERROR("Invalid call instruction!");
584
585 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
586 i != e; i += 2)
587 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
588 }
589
590 Result = new CallInst(F, Params);
591 break;
592 }
593 case Instruction::Invoke: {
594 if (Oprnds.size() < 3) PARSE_ERROR("Invalid invoke instruction!");
595 Value *F = getValue(iType, Oprnds[0]);
596
597 // Check to make sure we have a pointer to function type
598 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
599 if (PTy == 0) PARSE_ERROR("Invoke to non function pointer value!");
600 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
601 if (FTy == 0) PARSE_ERROR("Invoke to non function pointer value!");
602
603 std::vector<Value *> Params;
604 BasicBlock *Normal, *Except;
605
606 if (!FTy->isVarArg()) {
607 Normal = getBasicBlock(Oprnds[1]);
608 Except = getBasicBlock(Oprnds[2]);
609
610 FunctionType::param_iterator It = FTy->param_begin();
611 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
612 if (It == FTy->param_end())
613 PARSE_ERROR("Invalid invoke instruction!");
614 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
615 }
616 if (It != FTy->param_end())
617 PARSE_ERROR("Invalid invoke instruction!");
618 } else {
619 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
620
621 Normal = getBasicBlock(Oprnds[0]);
622 Except = getBasicBlock(Oprnds[1]);
623
624 unsigned FirstVariableArgument = FTy->getNumParams()+2;
625 for (unsigned i = 2; i != FirstVariableArgument; ++i)
626 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
627 Oprnds[i]));
628
629 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
630 PARSE_ERROR("Invalid invoke instruction!");
631
632 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
633 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
634 }
635
636 Result = new InvokeInst(F, Normal, Except, Params);
637 break;
638 }
639 case Instruction::Malloc:
640 if (Oprnds.size() > 2) PARSE_ERROR("Invalid malloc instruction!");
641 if (!isa<PointerType>(InstTy))
642 PARSE_ERROR("Invalid malloc instruction!");
643
644 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
645 Oprnds.size() ? getValue(Type::UIntTyID,
646 Oprnds[0]) : 0);
647 break;
648
649 case Instruction::Alloca:
650 if (Oprnds.size() > 2) PARSE_ERROR("Invalid alloca instruction!");
651 if (!isa<PointerType>(InstTy))
652 PARSE_ERROR("Invalid alloca instruction!");
653
654 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
655 Oprnds.size() ? getValue(Type::UIntTyID,
656 Oprnds[0]) :0);
657 break;
658 case Instruction::Free:
659 if (!isa<PointerType>(InstTy))
660 PARSE_ERROR("Invalid free instruction!");
661 Result = new FreeInst(getValue(iType, Oprnds[0]));
662 break;
663 case Instruction::GetElementPtr: {
664 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
665 PARSE_ERROR("Invalid getelementptr instruction!");
666
667 std::vector<Value*> Idx;
668
669 const Type *NextTy = InstTy;
670 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
671 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
672 if (!TopTy) PARSE_ERROR("Invalid getelementptr instruction!");
673
674 unsigned ValIdx = Oprnds[i];
675 unsigned IdxTy = 0;
676 if (!hasRestrictedGEPTypes) {
677 // Struct indices are always uints, sequential type indices can be any
678 // of the 32 or 64-bit integer types. The actual choice of type is
679 // encoded in the low two bits of the slot number.
680 if (isa<StructType>(TopTy))
681 IdxTy = Type::UIntTyID;
682 else {
683 switch (ValIdx & 3) {
684 default:
685 case 0: IdxTy = Type::UIntTyID; break;
686 case 1: IdxTy = Type::IntTyID; break;
687 case 2: IdxTy = Type::ULongTyID; break;
688 case 3: IdxTy = Type::LongTyID; break;
689 }
690 ValIdx >>= 2;
691 }
692 } else {
693 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
694 }
695
696 Idx.push_back(getValue(IdxTy, ValIdx));
697
698 // Convert ubyte struct indices into uint struct indices.
699 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
700 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
701 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
702
703 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
704 }
705
706 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
707 break;
708 }
709
710 case 62: // volatile load
711 case Instruction::Load:
712 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
713 PARSE_ERROR("Invalid load instruction!");
714 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
715 break;
716
717 case 63: // volatile store
718 case Instruction::Store: {
719 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
720 PARSE_ERROR("Invalid store instruction!");
721
722 Value *Ptr = getValue(iType, Oprnds[1]);
723 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
724 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
725 Opcode == 63);
726 break;
727 }
728 case Instruction::Unwind:
729 if (Oprnds.size() != 0) PARSE_ERROR("Invalid unwind instruction!");
730 Result = new UnwindInst();
731 break;
732 } // end switch(Opcode)
733
734 unsigned TypeSlot;
735 if (Result->getType() == InstTy)
736 TypeSlot = iType;
737 else
738 TypeSlot = getTypeSlot(Result->getType());
739
740 insertValue(Result, TypeSlot, FunctionValues);
741 BB->getInstList().push_back(Result);
742}
743
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000744/// getBasicBlock - Get a particular numbered basic block, which might be a
745/// forward reference. This works together with ParseBasicBlock to handle these
746/// forward references in a clean manner.
Reid Spencer060d25d2004-06-29 23:29:38 +0000747BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000748 // Make sure there is room in the table...
749 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
750
751 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
752 // has already created this block, or if the forward reference has already
753 // been created.
754 if (ParsedBasicBlocks[ID])
755 return ParsedBasicBlocks[ID];
756
757 // Otherwise, the basic block has not yet been created. Do so and add it to
758 // the ParsedBasicBlocks list.
759 return ParsedBasicBlocks[ID] = new BasicBlock();
760}
761
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000762/// ParseBasicBlock - In LLVM 1.0 bytecode files, we used to output one
763/// basicblock at a time. This method reads in one of the basicblock packets.
Reid Spencer060d25d2004-06-29 23:29:38 +0000764BasicBlock *BytecodeReader::ParseBasicBlock( unsigned BlockNo) {
765 HANDLE(BasicBlockBegin( BlockNo ));
766
767 BasicBlock *BB = 0;
768
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000769 if (ParsedBasicBlocks.size() == BlockNo)
770 ParsedBasicBlocks.push_back(BB = new BasicBlock());
771 else if (ParsedBasicBlocks[BlockNo] == 0)
772 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
773 else
774 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000775
Reid Spencer060d25d2004-06-29 23:29:38 +0000776 std::vector<unsigned> Operands;
777 while ( moreInBlock() )
778 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000779
Reid Spencer060d25d2004-06-29 23:29:38 +0000780 HANDLE(BasicBlockEnd( BlockNo ));
Misha Brukman12c29d12003-09-22 23:38:23 +0000781 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000782}
783
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000784/// ParseInstructionList - Parse all of the BasicBlock's & Instruction's in the
785/// body of a function. In post 1.0 bytecode files, we no longer emit basic
786/// block individually, in order to avoid per-basic-block overhead.
Reid Spencer060d25d2004-06-29 23:29:38 +0000787unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000788 unsigned BlockNo = 0;
789 std::vector<unsigned> Args;
790
Reid Spencer060d25d2004-06-29 23:29:38 +0000791 while ( moreInBlock() ) {
792 HANDLE(BasicBlockBegin( BlockNo ));
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000793 BasicBlock *BB;
794 if (ParsedBasicBlocks.size() == BlockNo)
795 ParsedBasicBlocks.push_back(BB = new BasicBlock());
796 else if (ParsedBasicBlocks[BlockNo] == 0)
797 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
798 else
799 BB = ParsedBasicBlocks[BlockNo];
Reid Spencer060d25d2004-06-29 23:29:38 +0000800 HANDLE(BasicBlockEnd( BlockNo ));
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000801 ++BlockNo;
802 F->getBasicBlockList().push_back(BB);
803
804 // Read instructions into this basic block until we get to a terminator
Reid Spencer060d25d2004-06-29 23:29:38 +0000805 while ( moreInBlock() && !BB->getTerminator())
806 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000807
808 if (!BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000809 PARSE_ERROR("Non-terminated basic block found!");
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000810 }
811
812 return BlockNo;
813}
814
Reid Spencer060d25d2004-06-29 23:29:38 +0000815void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
816 SymbolTable *ST) {
817 HANDLE(SymbolTableBegin(CurrentFunction,ST));
818
Chris Lattner39cacce2003-10-10 05:43:47 +0000819 // Allow efficient basic block lookup by number.
820 std::vector<BasicBlock*> BBMap;
821 if (CurrentFunction)
822 for (Function::iterator I = CurrentFunction->begin(),
823 E = CurrentFunction->end(); I != E; ++I)
824 BBMap.push_back(I);
825
Reid Spencer060d25d2004-06-29 23:29:38 +0000826 while ( moreInBlock() ) {
Chris Lattner00950542001-06-06 20:29:01 +0000827 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000828 unsigned NumEntries = read_vbr_uint();
829 unsigned Typ = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +0000830 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +0000831
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000832 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000833 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000834 unsigned slot = read_vbr_uint();
835 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +0000836
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000837 Value *V = 0;
Chris Lattner36392bc2003-10-08 21:18:57 +0000838 if (Typ == Type::TypeTyID)
839 V = (Value*)getType(slot);
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000840 else if (Typ == Type::LabelTyID) {
Chris Lattner39cacce2003-10-10 05:43:47 +0000841 if (slot < BBMap.size())
842 V = BBMap[slot];
843 } else {
Chris Lattner36392bc2003-10-08 21:18:57 +0000844 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +0000845 }
Chris Lattner52f86d62004-01-20 00:54:06 +0000846 if (V == 0)
Reid Spencer060d25d2004-06-29 23:29:38 +0000847 PARSE_ERROR("Failed value look-up for name '" << Name << "'");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000848
Chris Lattner52e20b02003-03-19 20:54:26 +0000849 V->setName(Name, ST);
Chris Lattner00950542001-06-06 20:29:01 +0000850 }
851 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000852 checkPastBlockEnd("Symbol Table");
853 HANDLE(SymbolTableEnd());
Chris Lattner00950542001-06-06 20:29:01 +0000854}
855
Reid Spencer060d25d2004-06-29 23:29:38 +0000856void BytecodeReader::ParseCompactionTable() {
857
858 HANDLE(CompactionTableBegin());
859
860 while ( moreInBlock() ) {
861 unsigned NumEntries = read_vbr_uint();
862 unsigned Ty;
863
864 if ((NumEntries & 3) == 3) {
865 NumEntries >>= 2;
866 Ty = read_vbr_uint();
867 } else {
868 Ty = NumEntries >> 2;
869 NumEntries &= 3;
870 }
871
872 if (Ty >= CompactionValues.size())
873 CompactionValues.resize(Ty+1);
874
875 if (!CompactionValues[Ty].empty())
876 PARSE_ERROR("Compaction table plane contains multiple entries!");
877
878 HANDLE(CompactionTablePlane( Ty, NumEntries ));
879
880 if (Ty == Type::TypeTyID) {
881 for (unsigned i = 0; i != NumEntries; ++i) {
882 unsigned TypeSlot = read_vbr_uint();
883 const Type *Typ = getGlobalTableType(TypeSlot);
884 CompactionTypes.push_back(Typ);
885 HANDLE(CompactionTableType( i, TypeSlot, Typ ));
886 }
887 CompactionTypes.resize(NumEntries+Type::FirstDerivedTyID);
888 } else {
889 const Type *Typ = getType(Ty);
890 // Push the implicit zero
891 CompactionValues[Ty].push_back(Constant::getNullValue(Typ));
892 for (unsigned i = 0; i != NumEntries; ++i) {
893 unsigned ValSlot = read_vbr_uint();
894 Value *V = getGlobalTableValue(Typ, ValSlot);
895 CompactionValues[Ty].push_back(V);
896 HANDLE(CompactionTableValue( i, Ty, ValSlot, Typ ));
897 }
898 }
899 }
900 HANDLE(CompactionTableEnd());
901}
902
903// Parse a single type constant.
904const Type *BytecodeReader::ParseTypeConstant() {
905 unsigned PrimType = read_vbr_uint();
906
907 const Type *Result = 0;
908 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
909 return Result;
910
911 switch (PrimType) {
912 case Type::FunctionTyID: {
913 const Type *RetType = getType(read_vbr_uint());
914
915 unsigned NumParams = read_vbr_uint();
916
917 std::vector<const Type*> Params;
918 while (NumParams--)
919 Params.push_back(getType(read_vbr_uint()));
920
921 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
922 if (isVarArg) Params.pop_back();
923
924 Result = FunctionType::get(RetType, Params, isVarArg);
925 break;
926 }
927 case Type::ArrayTyID: {
928 unsigned ElTyp = read_vbr_uint();
929 const Type *ElementType = getType(ElTyp);
930
931 unsigned NumElements = read_vbr_uint();
932
933 Result = ArrayType::get(ElementType, NumElements);
934 break;
935 }
936 case Type::StructTyID: {
937 std::vector<const Type*> Elements;
938 unsigned Typ = read_vbr_uint();
939 while (Typ) { // List is terminated by void/0 typeid
940 Elements.push_back(getType(Typ));
941 Typ = read_vbr_uint();
942 }
943
944 Result = StructType::get(Elements);
945 break;
946 }
947 case Type::PointerTyID: {
948 unsigned ElTyp = read_vbr_uint();
949 Result = PointerType::get(getType(ElTyp));
950 break;
951 }
952
953 case Type::OpaqueTyID: {
954 Result = OpaqueType::get();
955 break;
956 }
957
958 default:
959 PARSE_ERROR("Don't know how to deserialize primitive type" << PrimType << "\n");
960 break;
961 }
962 HANDLE(Type( Result ));
963 return Result;
964}
965
966// ParseTypeConstants - We have to use this weird code to handle recursive
967// types. We know that recursive types will only reference the current slab of
968// values in the type plane, but they can forward reference types before they
969// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
970// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
971// this ugly problem, we pessimistically insert an opaque type for each type we
972// are about to read. This means that forward references will resolve to
973// something and when we reread the type later, we can replace the opaque type
974// with a new resolved concrete type.
975//
976void BytecodeReader::ParseTypeConstants(TypeListTy &Tab, unsigned NumEntries){
977 assert(Tab.size() == 0 && "should not have read type constants in before!");
978
979 // Insert a bunch of opaque types to be resolved later...
980 Tab.reserve(NumEntries);
981 for (unsigned i = 0; i != NumEntries; ++i)
982 Tab.push_back(OpaqueType::get());
983
984 // Loop through reading all of the types. Forward types will make use of the
985 // opaque types just inserted.
986 //
987 for (unsigned i = 0; i != NumEntries; ++i) {
988 const Type *NewTy = ParseTypeConstant(), *OldTy = Tab[i].get();
989 if (NewTy == 0) PARSE_ERROR("Couldn't parse type!");
990
991 // Don't directly push the new type on the Tab. Instead we want to replace
992 // the opaque type we previously inserted with the new concrete value. This
993 // approach helps with forward references to types. The refinement from the
994 // abstract (opaque) type to the new type causes all uses of the abstract
995 // type to use the concrete type (NewTy). This will also cause the opaque
996 // type to be deleted.
997 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
998
999 // This should have replaced the old opaque type with the new type in the
1000 // value table... or with a preexisting type that was already in the system.
1001 // Let's just make sure it did.
1002 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1003 }
1004}
1005
1006Constant *BytecodeReader::ParseConstantValue( unsigned TypeID) {
1007 // We must check for a ConstantExpr before switching by type because
1008 // a ConstantExpr can be of any type, and has no explicit value.
1009 //
1010 // 0 if not expr; numArgs if is expr
1011 unsigned isExprNumArgs = read_vbr_uint();
1012
1013 if (isExprNumArgs) {
1014 // FIXME: Encoding of constant exprs could be much more compact!
1015 std::vector<Constant*> ArgVec;
1016 ArgVec.reserve(isExprNumArgs);
1017 unsigned Opcode = read_vbr_uint();
1018
1019 // Read the slot number and types of each of the arguments
1020 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1021 unsigned ArgValSlot = read_vbr_uint();
1022 unsigned ArgTypeSlot = read_vbr_uint();
1023
1024 // Get the arg value from its slot if it exists, otherwise a placeholder
1025 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1026 }
1027
1028 // Construct a ConstantExpr of the appropriate kind
1029 if (isExprNumArgs == 1) { // All one-operand expressions
1030 assert(Opcode == Instruction::Cast);
1031 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1032 HANDLE(ConstantExpression(Opcode, ArgVec, Result));
1033 return Result;
1034 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1035 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1036
1037 if (hasRestrictedGEPTypes) {
1038 const Type *BaseTy = ArgVec[0]->getType();
1039 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1040 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1041 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1042 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1043 if (isa<StructType>(*GTI)) {
1044 if (IdxList[i]->getType() != Type::UByteTy)
1045 PARSE_ERROR("Invalid index for getelementptr!");
1046 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1047 }
1048 }
1049
1050 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1051 HANDLE(ConstantExpression(Opcode, ArgVec, Result));
1052 return Result;
1053 } else if (Opcode == Instruction::Select) {
1054 assert(ArgVec.size() == 3);
1055 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1056 ArgVec[2]);
1057 HANDLE(ConstantExpression(Opcode, ArgVec, Result));
1058 return Result;
1059 } else { // All other 2-operand expressions
1060 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1061 HANDLE(ConstantExpression(Opcode, ArgVec, Result));
1062 return Result;
1063 }
1064 }
1065
1066 // Ok, not an ConstantExpr. We now know how to read the given type...
1067 const Type *Ty = getType(TypeID);
1068 switch (Ty->getTypeID()) {
1069 case Type::BoolTyID: {
1070 unsigned Val = read_vbr_uint();
1071 if (Val != 0 && Val != 1)
1072 PARSE_ERROR("Invalid boolean value read.");
1073 Constant* Result = ConstantBool::get(Val == 1);
1074 HANDLE(ConstantValue(Result));
1075 return Result;
1076 }
1077
1078 case Type::UByteTyID: // Unsigned integer types...
1079 case Type::UShortTyID:
1080 case Type::UIntTyID: {
1081 unsigned Val = read_vbr_uint();
1082 if (!ConstantUInt::isValueValidForType(Ty, Val))
1083 PARSE_ERROR("Invalid unsigned byte/short/int read.");
1084 Constant* Result = ConstantUInt::get(Ty, Val);
1085 HANDLE(ConstantValue(Result));
1086 return Result;
1087 }
1088
1089 case Type::ULongTyID: {
1090 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1091 HANDLE(ConstantValue(Result));
1092 return Result;
1093 }
1094
1095 case Type::SByteTyID: // Signed integer types...
1096 case Type::ShortTyID:
1097 case Type::IntTyID: {
1098 case Type::LongTyID:
1099 int64_t Val = read_vbr_int64();
1100 if (!ConstantSInt::isValueValidForType(Ty, Val))
1101 PARSE_ERROR("Invalid signed byte/short/int/long read.");
1102 Constant* Result = ConstantSInt::get(Ty, Val);
1103 HANDLE(ConstantValue(Result));
1104 return Result;
1105 }
1106
1107 case Type::FloatTyID: {
1108 float F;
1109 read_data(&F, &F+1);
1110 Constant* Result = ConstantFP::get(Ty, F);
1111 HANDLE(ConstantValue(Result));
1112 return Result;
1113 }
1114
1115 case Type::DoubleTyID: {
1116 double Val;
1117 read_data(&Val, &Val+1);
1118 Constant* Result = ConstantFP::get(Ty, Val);
1119 HANDLE(ConstantValue(Result));
1120 return Result;
1121 }
1122
1123 case Type::TypeTyID:
1124 PARSE_ERROR("Type constants shouldn't live in constant table!");
1125 break;
1126
1127 case Type::ArrayTyID: {
1128 const ArrayType *AT = cast<ArrayType>(Ty);
1129 unsigned NumElements = AT->getNumElements();
1130 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1131 std::vector<Constant*> Elements;
1132 Elements.reserve(NumElements);
1133 while (NumElements--) // Read all of the elements of the constant.
1134 Elements.push_back(getConstantValue(TypeSlot,
1135 read_vbr_uint()));
1136 Constant* Result = ConstantArray::get(AT, Elements);
1137 HANDLE(ConstantArray(AT, Elements, TypeSlot, Result));
1138 return Result;
1139 }
1140
1141 case Type::StructTyID: {
1142 const StructType *ST = cast<StructType>(Ty);
1143
1144 std::vector<Constant *> Elements;
1145 Elements.reserve(ST->getNumElements());
1146 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1147 Elements.push_back(getConstantValue(ST->getElementType(i),
1148 read_vbr_uint()));
1149
1150 Constant* Result = ConstantStruct::get(ST, Elements);
1151 HANDLE(ConstantStruct(ST, Elements, Result));
1152 return Result;
1153 }
1154
1155 case Type::PointerTyID: { // ConstantPointerRef value...
1156 const PointerType *PT = cast<PointerType>(Ty);
1157 unsigned Slot = read_vbr_uint();
1158
1159 // Check to see if we have already read this global variable...
1160 Value *Val = getValue(TypeID, Slot, false);
1161 GlobalValue *GV;
1162 if (Val) {
1163 if (!(GV = dyn_cast<GlobalValue>(Val)))
1164 PARSE_ERROR("Value of ConstantPointerRef not in ValueTable!");
1165 } else {
1166 PARSE_ERROR("Forward references are not allowed here.");
1167 }
1168
1169 Constant* Result = ConstantPointerRef::get(GV);
1170 HANDLE(ConstantPointer(PT, Slot, GV, Result));
1171 return Result;
1172 }
1173
1174 default:
1175 PARSE_ERROR("Don't know how to deserialize constant value of type '"+
1176 Ty->getDescription());
1177 break;
1178 }
1179}
1180
1181void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001182 ConstantRefsType::iterator I =
1183 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1184 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001185
Chris Lattner29b789b2003-11-19 17:27:18 +00001186 Value *PH = I->second; // Get the placeholder...
1187 PH->replaceAllUsesWith(NewV);
1188 delete PH; // Delete the old placeholder
1189 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001190}
1191
Reid Spencer060d25d2004-06-29 23:29:38 +00001192void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1193 for (; NumEntries; --NumEntries) {
1194 unsigned Typ = read_vbr_uint();
1195 const Type *Ty = getType(Typ);
1196 if (!isa<ArrayType>(Ty))
1197 PARSE_ERROR("String constant data invalid!");
1198
1199 const ArrayType *ATy = cast<ArrayType>(Ty);
1200 if (ATy->getElementType() != Type::SByteTy &&
1201 ATy->getElementType() != Type::UByteTy)
1202 PARSE_ERROR("String constant data invalid!");
1203
1204 // Read character data. The type tells us how long the string is.
1205 char Data[ATy->getNumElements()];
1206 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001207
Reid Spencer060d25d2004-06-29 23:29:38 +00001208 std::vector<Constant*> Elements(ATy->getNumElements());
1209 if (ATy->getElementType() == Type::SByteTy)
1210 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1211 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1212 else
1213 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1214 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001215
Reid Spencer060d25d2004-06-29 23:29:38 +00001216 // Create the constant, inserting it as needed.
1217 Constant *C = ConstantArray::get(ATy, Elements);
1218 unsigned Slot = insertValue(C, Typ, Tab);
1219 ResolveReferencesToConstant(C, Slot);
1220 HANDLE(ConstantString(cast<ConstantArray>(C)));
1221 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001222}
1223
Reid Spencer060d25d2004-06-29 23:29:38 +00001224void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1225 TypeListTy &TypeTab) {
1226 HANDLE(GlobalConstantsBegin());
1227 while ( moreInBlock() ) {
1228 unsigned NumEntries = read_vbr_uint();
1229 unsigned Typ = read_vbr_uint();
1230 if (Typ == Type::TypeTyID) {
1231 ParseTypeConstants(TypeTab, NumEntries);
1232 } else if (Typ == Type::VoidTyID) {
1233 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1234 ParseStringConstants(NumEntries, Tab);
1235 } else {
1236 for (unsigned i = 0; i < NumEntries; ++i) {
1237 Constant *C = ParseConstantValue(Typ);
1238 assert(C && "ParseConstantValue returned NULL!");
1239 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001240
Reid Spencer060d25d2004-06-29 23:29:38 +00001241 // If we are reading a function constant table, make sure that we adjust
1242 // the slot number to be the real global constant number.
1243 //
1244 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1245 ModuleValues[Typ])
1246 Slot += ModuleValues[Typ]->size();
1247 ResolveReferencesToConstant(C, Slot);
1248 }
1249 }
1250 }
1251 checkPastBlockEnd("Constant Pool");
1252 HANDLE(GlobalConstantsEnd());
1253}
Chris Lattner00950542001-06-06 20:29:01 +00001254
Reid Spencer060d25d2004-06-29 23:29:38 +00001255void BytecodeReader::ParseFunctionBody(Function* F ) {
1256
1257 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001258 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1259
Reid Spencer060d25d2004-06-29 23:29:38 +00001260 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001261 switch (LinkageType) {
1262 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1263 case 1: Linkage = GlobalValue::WeakLinkage; break;
1264 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1265 case 3: Linkage = GlobalValue::InternalLinkage; break;
1266 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001267 default:
1268 PARSE_ERROR("Invalid linkage type for Function.");
1269 Linkage = GlobalValue::InternalLinkage;
1270 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001271 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001272
Reid Spencer060d25d2004-06-29 23:29:38 +00001273 F->setLinkage( Linkage );
1274 HANDLE(FunctionBegin(F,FuncSize));
Chris Lattner00950542001-06-06 20:29:01 +00001275
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001276 // Keep track of how many basic blocks we have read in...
1277 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001278 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001279
Reid Spencer060d25d2004-06-29 23:29:38 +00001280 BufPtr MyEnd = BlockEnd;
1281 while ( At < MyEnd ) {
Chris Lattner00950542001-06-06 20:29:01 +00001282 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001283 BufPtr OldAt = At;
1284 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001285
1286 switch (Type) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001287 case BytecodeFormat::ConstantPool:
Chris Lattner89e02532004-01-18 21:08:15 +00001288 if (!InsertedArguments) {
1289 // Insert arguments into the value table before we parse the first basic
1290 // block in the function, but after we potentially read in the
1291 // compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001292 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001293 InsertedArguments = true;
1294 }
1295
Reid Spencer060d25d2004-06-29 23:29:38 +00001296 ParseConstantPool(FunctionValues, FunctionTypes);
Chris Lattner00950542001-06-06 20:29:01 +00001297 break;
1298
Chris Lattner89e02532004-01-18 21:08:15 +00001299 case BytecodeFormat::CompactionTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001300 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001301 break;
1302
Chris Lattner00950542001-06-06 20:29:01 +00001303 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001304 if (!InsertedArguments) {
1305 // Insert arguments into the value table before we parse the first basic
1306 // block in the function, but after we potentially read in the
1307 // compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001308 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001309 InsertedArguments = true;
1310 }
1311
Reid Spencer060d25d2004-06-29 23:29:38 +00001312 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001313 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001314 break;
1315 }
1316
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001317 case BytecodeFormat::InstructionList: {
Chris Lattner89e02532004-01-18 21:08:15 +00001318 // Insert arguments into the value table before we parse the instruction
1319 // list for the function, but after we potentially read in the compaction
1320 // table.
1321 if (!InsertedArguments) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001322 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001323 InsertedArguments = true;
1324 }
1325
Reid Spencer060d25d2004-06-29 23:29:38 +00001326 if (BlockNum)
1327 PARSE_ERROR("Already parsed basic blocks!");
1328 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001329 break;
1330 }
1331
Chris Lattner29b789b2003-11-19 17:27:18 +00001332 case BytecodeFormat::SymbolTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001333 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001334 break;
1335
1336 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001337 At += Size;
1338 if (OldAt > At)
1339 PARSE_ERROR("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001340 break;
1341 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001342 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001343
Misha Brukman12c29d12003-09-22 23:38:23 +00001344 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001346 }
1347
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001348 // Make sure there were no references to non-existant basic blocks.
1349 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer060d25d2004-06-29 23:29:38 +00001350 PARSE_ERROR("Illegal basic block operand reference");
1351
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001352 ParsedBasicBlocks.clear();
1353
Chris Lattner97330cf2003-10-09 23:10:14 +00001354 // Resolve forward references. Replace any uses of a forward reference value
1355 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001356
Chris Lattner97330cf2003-10-09 23:10:14 +00001357 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1358 // number of operands. PHI nodes often have forward references, and can also
1359 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001360 //
1361 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1362 // should be simplified back to using it!
1363 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001364 std::map<Value*, Value*> ForwardRefMapping;
1365 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1366 I = ForwardReferences.begin(), E = ForwardReferences.end();
1367 I != E; ++I)
1368 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1369 false);
1370
1371 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1372 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1373 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1374 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
1375 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1376 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1377 }
1378
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001379 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001380 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1381 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001382 Value *PlaceHolder = I->second;
1383 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001384
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001385 // Now that all the uses are gone, delete the placeholder...
1386 // If we couldn't find a def (error case), then leak a little
1387 // memory, because otherwise we can't remove all uses!
1388 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001389 }
Chris Lattner00950542001-06-06 20:29:01 +00001390
Misha Brukman12c29d12003-09-22 23:38:23 +00001391 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001392 FunctionTypes.clear();
1393 CompactionTypes.clear();
1394 CompactionValues.clear();
1395 freeTable(FunctionValues);
1396
1397 HANDLE(FunctionEnd(F));
Chris Lattner00950542001-06-06 20:29:01 +00001398}
1399
Reid Spencer060d25d2004-06-29 23:29:38 +00001400void BytecodeReader::ParseFunctionLazily() {
1401 if (FunctionSignatureList.empty())
1402 PARSE_ERROR("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001403
Reid Spencer060d25d2004-06-29 23:29:38 +00001404 Function *Func = FunctionSignatureList.back();
1405 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001406
Reid Spencer060d25d2004-06-29 23:29:38 +00001407 // Save the information for future reading of the function
1408 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001409
Reid Spencer060d25d2004-06-29 23:29:38 +00001410 // Pretend we've `parsed' this function
1411 At = BlockEnd;
1412}
Chris Lattner89e02532004-01-18 21:08:15 +00001413
Reid Spencer060d25d2004-06-29 23:29:38 +00001414void BytecodeReader::ParseFunction(Function* Func) {
1415 // Find {start, end} pointers and slot in the map. If not there, we're done.
1416 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001417
Reid Spencer060d25d2004-06-29 23:29:38 +00001418 // Make sure we found it
1419 if ( Fi == LazyFunctionLoadMap.end() ) {
1420 PARSE_ERROR("Unrecognized function of type " << Func->getType()->getDescription());
1421 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001422 }
1423
Reid Spencer060d25d2004-06-29 23:29:38 +00001424 BlockStart = At = Fi->second.Buf;
1425 BlockEnd = Fi->second.EndBuf;
1426 assert(Fi->first == Func);
1427
1428 LazyFunctionLoadMap.erase(Fi);
1429
1430 this->ParseFunctionBody( Func );
Chris Lattner89e02532004-01-18 21:08:15 +00001431}
1432
Reid Spencer060d25d2004-06-29 23:29:38 +00001433void BytecodeReader::ParseAllFunctionBodies() {
1434 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1435 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001436
Reid Spencer060d25d2004-06-29 23:29:38 +00001437 while ( Fi != Fe ) {
1438 Function* Func = Fi->first;
1439 BlockStart = At = Fi->second.Buf;
1440 BlockEnd = Fi->second.EndBuf;
1441 this->ParseFunctionBody(Func);
1442 ++Fi;
1443 }
1444}
Chris Lattner89e02532004-01-18 21:08:15 +00001445
Reid Spencer060d25d2004-06-29 23:29:38 +00001446void BytecodeReader::ParseGlobalTypes() {
1447 ValueTable T;
1448 ParseConstantPool(T, ModuleTypes);
1449}
1450
1451void BytecodeReader::ParseModuleGlobalInfo() {
1452
1453 HANDLE(ModuleGlobalsBegin());
Chris Lattner00950542001-06-06 20:29:01 +00001454
Chris Lattner70cc3392001-09-10 07:58:01 +00001455 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001456 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001457 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001458 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1459 // Linkage, bit4+ = slot#
1460 unsigned SlotNo = VarType >> 5;
1461 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 bool isConstant = VarType & 1;
1463 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001464 GlobalValue::LinkageTypes Linkage;
1465
Chris Lattnerc08912f2004-01-14 16:44:44 +00001466 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001467 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1468 case 1: Linkage = GlobalValue::WeakLinkage; break;
1469 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1470 case 3: Linkage = GlobalValue::InternalLinkage; break;
1471 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001472 default:
1473 PARSE_ERROR("Unknown linkage type: " << LinkageID);
1474 Linkage = GlobalValue::InternalLinkage;
1475 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001476 }
1477
1478 const Type *Ty = getType(SlotNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001479 if ( !Ty ) {
1480 PARSE_ERROR("Global has no type! SlotNo=" << SlotNo);
1481 }
1482
1483 if ( !isa<PointerType>(Ty)) {
1484 PARSE_ERROR("Global not a pointer type! Ty= " << Ty->getDescription());
1485 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001486
Chris Lattner52e20b02003-03-19 20:54:26 +00001487 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001488
Chris Lattner70cc3392001-09-10 07:58:01 +00001489 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001490 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001491 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001492 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001493
Reid Spencer060d25d2004-06-29 23:29:38 +00001494 unsigned initSlot = 0;
1495 if (hasInitializer) {
1496 initSlot = read_vbr_uint();
1497 GlobalInits.push_back(std::make_pair(GV, initSlot));
1498 }
1499
1500 // Notify handler about the global value.
1501 HANDLE(GlobalVariable( ElTy, isConstant, Linkage, SlotNo, initSlot ));
1502
1503 // Get next item
1504 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001505 }
1506
Chris Lattner52e20b02003-03-19 20:54:26 +00001507 // Read the function objects for all of the functions that are coming
Reid Spencer060d25d2004-06-29 23:29:38 +00001508 unsigned FnSignature = read_vbr_uint();
Chris Lattner74734132002-08-17 22:01:27 +00001509 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1510 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +00001511 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001512 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1513 PARSE_ERROR( "Function not a pointer to function type! Ty = " +
Misha Brukman12c29d12003-09-22 23:38:23 +00001514 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001515 // FIXME: what should Ty be if handler continues?
1516 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001517
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001518 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001519 const FunctionType* FTy =
1520 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001521
Reid Spencer060d25d2004-06-29 23:29:38 +00001522 // Insert the place hodler
1523 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
1524 "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001525 insertValue(Func, FnSignature, ModuleValues);
Chris Lattner00950542001-06-06 20:29:01 +00001526
Reid Spencer060d25d2004-06-29 23:29:38 +00001527 // Save this for later so we know type of lazily instantiated functions
Chris Lattner29b789b2003-11-19 17:27:18 +00001528 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001529
Reid Spencer060d25d2004-06-29 23:29:38 +00001530 HANDLE(FunctionDeclaration(Func));
1531
1532 // Get Next function signature
1533 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001534 }
1535
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001536 if (hasInconsistentModuleGlobalInfo)
Reid Spencer060d25d2004-06-29 23:29:38 +00001537 align32();
Chris Lattner74734132002-08-17 22:01:27 +00001538
1539 // Now that the function signature list is set up, reverse it so that we can
1540 // remove elements efficiently from the back of the vector.
1541 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001542
1543 // This is for future proofing... in the future extra fields may be added that
1544 // we don't understand, so we transparently ignore them.
1545 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001546 At = BlockEnd;
1547
1548 HANDLE(ModuleGlobalsEnd());
Chris Lattner00950542001-06-06 20:29:01 +00001549}
1550
Reid Spencer060d25d2004-06-29 23:29:38 +00001551void BytecodeReader::ParseVersionInfo() {
1552 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001553
1554 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001555 Module::Endianness Endianness;
1556 Module::PointerSize PointerSize;
1557 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1558 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1559
1560 bool hasNoEndianness = Version & 4;
1561 bool hasNoPointerSize = Version & 8;
1562
1563 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001564
1565 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001566 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001567 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001568 hasRestrictedGEPTypes = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001569
1570 switch (RevisionNum) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001571 case 0: // LLVM 1.0, 1.1 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001572 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001573 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001574 hasExplicitPrimitiveZeros = true;
1575 // FALL THROUGH
Chris Lattnerc08912f2004-01-14 16:44:44 +00001576 case 1: // LLVM 1.2 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001577 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001578
1579 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1580 // included the size for the alignment at the end, where the rest of the
1581 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001582
1583 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1584 // structures and longs for sequential types.
1585 hasRestrictedGEPTypes = true;
1586
1587 // FALL THROUGH
1588 case 2: // LLVM 1.3 release version
Chris Lattnerc08912f2004-01-14 16:44:44 +00001589 break;
1590
Chris Lattner036b8aa2003-03-06 17:55:45 +00001591 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001592 PARSE_ERROR("Unknown bytecode version number: " << RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001593 }
1594
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001595 if (hasNoEndianness) Endianness = Module::AnyEndianness;
1596 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00001597
Reid Spencer060d25d2004-06-29 23:29:38 +00001598 HANDLE(VersionInfo(RevisionNum, Endianness, PointerSize ));
Chris Lattner036b8aa2003-03-06 17:55:45 +00001599}
1600
Reid Spencer060d25d2004-06-29 23:29:38 +00001601void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001602 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001603
Reid Spencer060d25d2004-06-29 23:29:38 +00001604 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001605
1606 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001607 ParseVersionInfo();
1608 align32(); /// FIXME: Is this redundant? VI is first and 4 bytes!
Chris Lattner00950542001-06-06 20:29:01 +00001609
Reid Spencer060d25d2004-06-29 23:29:38 +00001610 bool SeenModuleGlobalInfo = false;
1611 bool SeenGlobalTypePlane = false;
1612 BufPtr MyEnd = BlockEnd;
1613 while (At < MyEnd) {
1614 BufPtr OldAt = At;
1615 read_block(Type, Size);
1616
Chris Lattner00950542001-06-06 20:29:01 +00001617 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001618
Chris Lattner52e20b02003-03-19 20:54:26 +00001619 case BytecodeFormat::GlobalTypePlane:
Reid Spencer060d25d2004-06-29 23:29:38 +00001620 if ( SeenGlobalTypePlane )
1621 PARSE_ERROR("Two GlobalTypePlane Blocks Encountered!");
1622
1623 ParseGlobalTypes();
1624 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001625 break;
1626
Reid Spencer060d25d2004-06-29 23:29:38 +00001627 case BytecodeFormat::ModuleGlobalInfo:
1628 if ( SeenModuleGlobalInfo )
1629 PARSE_ERROR("Two ModuleGlobalInfo Blocks Encountered!");
1630 ParseModuleGlobalInfo();
1631 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001632 break;
1633
Chris Lattner1d670cc2001-09-07 16:37:43 +00001634 case BytecodeFormat::ConstantPool:
Reid Spencer060d25d2004-06-29 23:29:38 +00001635 ParseConstantPool(ModuleValues, ModuleTypes);
Chris Lattner00950542001-06-06 20:29:01 +00001636 break;
1637
Reid Spencer060d25d2004-06-29 23:29:38 +00001638 case BytecodeFormat::Function:
1639 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001640 break;
Chris Lattner00950542001-06-06 20:29:01 +00001641
1642 case BytecodeFormat::SymbolTable:
Reid Spencer060d25d2004-06-29 23:29:38 +00001643 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001644 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001645
Chris Lattner00950542001-06-06 20:29:01 +00001646 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001647 At += Size;
1648 if (OldAt > At) {
1649 PARSE_ERROR("Unexpected Block of Type" << Type << "encountered!" );
1650 }
Chris Lattner00950542001-06-06 20:29:01 +00001651 break;
1652 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001653 BlockEnd = MyEnd;
1654 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001655 }
1656
Chris Lattner52e20b02003-03-19 20:54:26 +00001657 // After the module constant pool has been read, we can safely initialize
1658 // global variables...
1659 while (!GlobalInits.empty()) {
1660 GlobalVariable *GV = GlobalInits.back().first;
1661 unsigned Slot = GlobalInits.back().second;
1662 GlobalInits.pop_back();
1663
1664 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001665 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001666
1667 const llvm::PointerType* GVType = GV->getType();
1668 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001669 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00001670 if (GV->hasInitializer())
Reid Spencer060d25d2004-06-29 23:29:38 +00001671 PARSE_ERROR("Global *already* has an initializer?!");
1672 HANDLE(GlobalInitializer(GV,CV));
Chris Lattner93361992004-01-15 18:45:25 +00001673 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001674 } else
Reid Spencer060d25d2004-06-29 23:29:38 +00001675 PARSE_ERROR("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001676 }
1677
Reid Spencer060d25d2004-06-29 23:29:38 +00001678 /// Make sure we pulled them all out. If we didn't then there's a declaration
1679 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001680 if (!FunctionSignatureList.empty())
Reid Spencer060d25d2004-06-29 23:29:38 +00001681 PARSE_ERROR(
1682 "Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001683}
1684
Reid Spencer060d25d2004-06-29 23:29:38 +00001685void BytecodeReader::ParseBytecode(
1686 BufPtr Buf, unsigned Length,
1687 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001688
Reid Spencer060d25d2004-06-29 23:29:38 +00001689 try {
1690 At = MemStart = BlockStart = Buf;
1691 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001692
Reid Spencer060d25d2004-06-29 23:29:38 +00001693 // Create the module
1694 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00001695
Reid Spencer060d25d2004-06-29 23:29:38 +00001696 HANDLE(Start(TheModule, Length));
1697
1698 // Read and check signature...
1699 unsigned Sig = read_uint();
1700 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
1701 PARSE_ERROR("Invalid bytecode signature: " << Sig);
1702 }
1703
1704
1705 // Tell the handler we're starting a module
1706 HANDLE(ModuleBegin(ModuleID));
1707
1708 // Get the module block and size and verify
1709 unsigned Type, Size;
1710 read_block(Type, Size);
1711 if ( Type != BytecodeFormat::Module ) {
1712 PARSE_ERROR("Expected Module Block! At: " << unsigned(intptr_t(At))
1713 << ", Type:" << Type << ", Size:" << Size);
1714 }
1715 if ( At + Size != MemEnd ) {
1716 PARSE_ERROR("Invalid Top Level Block Length! At: "
1717 << unsigned(intptr_t(At)) << ", Type:" << Type << ", Size:" << Size);
1718 }
1719
1720 // Parse the module contents
1721 this->ParseModule();
1722
1723 // Tell the handler we're done
1724 HANDLE(ModuleEnd(ModuleID));
1725
1726 // Check for missing functions
1727 if ( hasFunctions() )
1728 PARSE_ERROR("Function expected, but bytecode stream ended!");
1729
1730 // Tell the handler we're
1731 HANDLE(Finish());
1732
1733 } catch (std::string& errstr ) {
1734 HANDLE(Error(errstr));
1735 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001736 delete TheModule;
1737 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00001738 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00001739 } catch (...) {
1740 std::string msg("Unknown Exception Occurred");
1741 HANDLE(Error(msg));
1742 freeState();
1743 delete TheModule;
1744 TheModule = 0;
1745 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001746 }
Chris Lattner00950542001-06-06 20:29:01 +00001747}
Reid Spencer060d25d2004-06-29 23:29:38 +00001748
1749//===----------------------------------------------------------------------===//
1750//=== Default Implementations of Handler Methods
1751//===----------------------------------------------------------------------===//
1752
1753BytecodeHandler::~BytecodeHandler() {}
1754void BytecodeHandler::handleError(const std::string& str ) { }
1755void BytecodeHandler::handleStart(Module*m, unsigned Length ) { }
1756void BytecodeHandler::handleFinish() { }
1757void BytecodeHandler::handleModuleBegin(const std::string& id) { }
1758void BytecodeHandler::handleModuleEnd(const std::string& id) { }
1759void BytecodeHandler::handleVersionInfo( unsigned char RevisionNum,
1760 Module::Endianness Endianness, Module::PointerSize PointerSize) { }
1761void BytecodeHandler::handleModuleGlobalsBegin() { }
1762void BytecodeHandler::handleGlobalVariable(
1763 const Type* ElemType, bool isConstant, GlobalValue::LinkageTypes,
1764 unsigned SlotNo, unsigned initSlot ) { }
1765void BytecodeHandler::handleType( const Type* Ty ) {}
1766void BytecodeHandler::handleFunctionDeclaration(
1767 Function* Func ) {}
1768void BytecodeHandler::handleGlobalInitializer(GlobalVariable*, Constant* ) {}
1769void BytecodeHandler::handleModuleGlobalsEnd() { }
1770void BytecodeHandler::handleCompactionTableBegin() { }
1771void BytecodeHandler::handleCompactionTablePlane(
1772 unsigned Ty, unsigned NumEntries) {}
1773void BytecodeHandler::handleCompactionTableType(
1774 unsigned i, unsigned TypSlot, const Type* ) {}
1775void BytecodeHandler::handleCompactionTableValue(
1776 unsigned i, unsigned TypSlot, unsigned ValSlot, const Type* ) {}
1777void BytecodeHandler::handleCompactionTableEnd() { }
1778void BytecodeHandler::handleSymbolTableBegin(Function*, SymbolTable*) { }
1779void BytecodeHandler::handleSymbolTablePlane( unsigned Ty, unsigned NumEntries,
1780 const Type* Typ) { }
1781void BytecodeHandler::handleSymbolTableType( unsigned i, unsigned slot,
1782 const std::string& name ) { }
1783void BytecodeHandler::handleSymbolTableValue( unsigned i, unsigned slot,
1784 const std::string& name ) { }
1785void BytecodeHandler::handleSymbolTableEnd() { }
1786void BytecodeHandler::handleFunctionBegin( Function* Func,
1787 unsigned Size ) {}
1788void BytecodeHandler::handleFunctionEnd( Function* Func) { }
1789void BytecodeHandler::handleBasicBlockBegin( unsigned blocknum) { }
1790bool BytecodeHandler::handleInstruction( unsigned Opcode, const Type* iType,
1791 std::vector<unsigned>& Operands, unsigned Size) {
1792 return Instruction::isTerminator(Opcode);
1793 }
1794void BytecodeHandler::handleBasicBlockEnd(unsigned blocknum) { }
1795void BytecodeHandler::handleGlobalConstantsBegin() { }
1796void BytecodeHandler::handleConstantExpression( unsigned Opcode,
1797 std::vector<Constant*> ArgVec, Constant* Val) { }
1798void BytecodeHandler::handleConstantValue( Constant * c ) { }
1799void BytecodeHandler::handleConstantArray( const ArrayType* AT,
1800 std::vector<Constant*>& Elements, unsigned TypeSlot, Constant* Val ) { }
1801void BytecodeHandler::handleConstantStruct( const StructType* ST,
1802 std::vector<Constant*>& ElementSlots, Constant* Val ) { }
1803void BytecodeHandler::handleConstantPointer(
1804 const PointerType* PT, unsigned TypeSlot, GlobalValue*, Constant* Val) { }
1805void BytecodeHandler::handleConstantString( const ConstantArray* CA ) {}
1806void BytecodeHandler::handleGlobalConstantsEnd() {}
1807void BytecodeHandler::handleAlignment(unsigned numBytes) {}
1808void BytecodeHandler::handleBlock(
1809 unsigned BType, const unsigned char* StartPtr, unsigned Size) {}
1810void BytecodeHandler::handleVBR32(unsigned Size ) {}
1811void BytecodeHandler::handleVBR64(unsigned Size ) {}
1812
1813// vim: sw=2