1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Reader.h
12 // Note that this library should be as fast as possible, reentrant, and
15 // TODO: Allow passing in an option to ignore the symbol table
17 //===----------------------------------------------------------------------===//
20 #include "llvm/Bytecode/BytecodeHandler.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/SymbolTable.h"
25 #include "llvm/Bytecode/Format.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/ADT/StringExtras.h"
34 /// @brief A class for maintaining the slot number definition
35 /// as a placeholder for the actual definition for forward constants defs.
36 class ConstantPlaceHolder : public ConstantExpr {
38 ConstantPlaceHolder(); // DO NOT IMPLEMENT
39 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
41 ConstantPlaceHolder(const Type *Ty, unsigned id)
42 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
44 unsigned getID() { return ID; }
49 // Provide some details on error
50 inline void BytecodeReader::error(std::string err) {
52 err += itostr(RevisionNum) ;
54 err += itostr(At-MemStart);
59 //===----------------------------------------------------------------------===//
60 // Bytecode Reading Methods
61 //===----------------------------------------------------------------------===//
63 /// Determine if the current block being read contains any more data.
64 inline bool BytecodeReader::moreInBlock() {
68 /// Throw an error if we've read past the end of the current block
69 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
71 error(std::string("Attempt to read past the end of ") + block_name + " block.");
74 /// Align the buffer position to a 32 bit boundary
75 inline void BytecodeReader::align32() {
78 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
80 if (Handler) Handler->handleAlignment(At - Save);
82 error("Ran out of data while aligning!");
86 /// Read a whole unsigned integer
87 inline unsigned BytecodeReader::read_uint() {
89 error("Ran out of data reading uint!");
91 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
94 /// Read a variable-bit-rate encoded unsigned integer
95 inline unsigned BytecodeReader::read_vbr_uint() {
102 error("Ran out of data reading vbr_uint!");
103 Result |= (unsigned)((*At++) & 0x7F) << Shift;
105 } while (At[-1] & 0x80);
106 if (Handler) Handler->handleVBR32(At-Save);
110 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
111 inline uint64_t BytecodeReader::read_vbr_uint64() {
118 error("Ran out of data reading vbr_uint64!");
119 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
121 } while (At[-1] & 0x80);
122 if (Handler) Handler->handleVBR64(At-Save);
126 /// Read a variable-bit-rate encoded signed 64-bit integer.
127 inline int64_t BytecodeReader::read_vbr_int64() {
128 uint64_t R = read_vbr_uint64();
131 return -(int64_t)(R >> 1);
132 else // There is no such thing as -0 with integers. "-0" really means
133 // 0x8000000000000000.
136 return (int64_t)(R >> 1);
139 /// Read a pascal-style string (length followed by text)
140 inline std::string BytecodeReader::read_str() {
141 unsigned Size = read_vbr_uint();
142 const unsigned char *OldAt = At;
144 if (At > BlockEnd) // Size invalid?
145 error("Ran out of data reading a string!");
146 return std::string((char*)OldAt, Size);
149 /// Read an arbitrary block of data
150 inline void BytecodeReader::read_data(void *Ptr, void *End) {
151 unsigned char *Start = (unsigned char *)Ptr;
152 unsigned Amount = (unsigned char *)End - Start;
153 if (At+Amount > BlockEnd)
154 error("Ran out of data!");
155 std::copy(At, At+Amount, Start);
159 /// Read a float value in little-endian order
160 inline void BytecodeReader::read_float(float& FloatVal) {
161 /// FIXME: This isn't optimal, it has size problems on some platforms
162 /// where FP is not IEEE.
167 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
168 At+=sizeof(uint32_t);
169 FloatVal = FloatUnion.f;
172 /// Read a double value in little-endian order
173 inline void BytecodeReader::read_double(double& DoubleVal) {
174 /// FIXME: This isn't optimal, it has size problems on some platforms
175 /// where FP is not IEEE.
180 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
181 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
182 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
183 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
184 At+=sizeof(uint64_t);
185 DoubleVal = DoubleUnion.d;
188 /// Read a block header and obtain its type and size
189 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
190 if ( hasLongBlockHeaders ) {
194 case BytecodeFormat::Reserved_DoNotUse :
195 error("Reserved_DoNotUse used as Module Type?");
196 Type = BytecodeFormat::ModuleBlockID; break;
197 case BytecodeFormat::Module:
198 Type = BytecodeFormat::ModuleBlockID; break;
199 case BytecodeFormat::Function:
200 Type = BytecodeFormat::FunctionBlockID; break;
201 case BytecodeFormat::ConstantPool:
202 Type = BytecodeFormat::ConstantPoolBlockID; break;
203 case BytecodeFormat::SymbolTable:
204 Type = BytecodeFormat::SymbolTableBlockID; break;
205 case BytecodeFormat::ModuleGlobalInfo:
206 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
207 case BytecodeFormat::GlobalTypePlane:
208 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
209 case BytecodeFormat::InstructionList:
210 Type = BytecodeFormat::InstructionListBlockID; break;
211 case BytecodeFormat::CompactionTable:
212 Type = BytecodeFormat::CompactionTableBlockID; break;
213 case BytecodeFormat::BasicBlock:
214 /// This block type isn't used after version 1.1. However, we have to
215 /// still allow the value in case this is an old bc format file.
216 /// We just let its value creep thru.
219 error("Invalid block id found: " + utostr(Type));
224 Type = Size & 0x1F; // mask low order five bits
225 Size >>= 5; // get rid of five low order bits, leaving high 27
228 if (At + Size > BlockEnd)
229 error("Attempt to size a block past end of memory");
230 BlockEnd = At + Size;
231 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
235 /// In LLVM 1.2 and before, Types were derived from Value and so they were
236 /// written as part of the type planes along with any other Value. In LLVM
237 /// 1.3 this changed so that Type does not derive from Value. Consequently,
238 /// the BytecodeReader's containers for Values can't contain Types because
239 /// there's no inheritance relationship. This means that the "Type Type"
240 /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
241 /// whenever a bytecode construct must have both types and values together,
242 /// the types are always read/written first and then the Values. Furthermore
243 /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
244 /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
245 /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
246 /// For LLVM 1.2 and before, this function will decrement the type id by
247 /// one to account for the missing Type::TypeTyID enumerator if the value is
248 /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
249 /// function returns true, otherwise false. This helps detect situations
250 /// where the pre 1.3 bytecode is indicating that what follows is a type.
251 /// @returns true iff type id corresponds to pre 1.3 "type type"
252 inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
253 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
254 if (TypeId == Type::LabelTyID) {
255 TypeId = Type::VoidTyID; // sanitize it
256 return true; // indicate we got TypeTyID in pre 1.3 bytecode
257 } else if (TypeId > Type::LabelTyID)
258 --TypeId; // shift all planes down because type type plane is missing
263 /// Reads a vbr uint to read in a type id and does the necessary
264 /// conversion on it by calling sanitizeTypeId.
265 /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
266 /// @see sanitizeTypeId
267 inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
268 TypeId = read_vbr_uint();
269 if ( !has32BitTypes )
270 if ( TypeId == 0x00FFFFFF )
271 TypeId = read_vbr_uint();
272 return sanitizeTypeId(TypeId);
275 //===----------------------------------------------------------------------===//
277 //===----------------------------------------------------------------------===//
279 /// Determine if a type id has an implicit null value
280 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
281 if (!hasExplicitPrimitiveZeros)
282 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
283 return TyID >= Type::FirstDerivedTyID;
286 /// Obtain a type given a typeid and account for things like compaction tables,
287 /// function level vs module level, and the offsetting for the primitive types.
288 const Type *BytecodeReader::getType(unsigned ID) {
289 if (ID < Type::FirstDerivedTyID)
290 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
291 return T; // Asked for a primitive type...
293 // Otherwise, derived types need offset...
294 ID -= Type::FirstDerivedTyID;
296 if (!CompactionTypes.empty()) {
297 if (ID >= CompactionTypes.size())
298 error("Type ID out of range for compaction table!");
299 return CompactionTypes[ID].first;
302 // Is it a module-level type?
303 if (ID < ModuleTypes.size())
304 return ModuleTypes[ID].get();
306 // Nope, is it a function-level type?
307 ID -= ModuleTypes.size();
308 if (ID < FunctionTypes.size())
309 return FunctionTypes[ID].get();
311 error("Illegal type reference!");
315 /// Get a sanitized type id. This just makes sure that the \p ID
316 /// is both sanitized and not the "type type" of pre-1.3 bytecode.
317 /// @see sanitizeTypeId
318 inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
319 if (sanitizeTypeId(ID))
320 error("Invalid type id encountered");
324 /// This method just saves some coding. It uses read_typeid to read
325 /// in a sanitized type id, errors that its not the type type, and
326 /// then calls getType to return the type value.
327 inline const Type* BytecodeReader::readSanitizedType() {
330 error("Invalid type id encountered");
334 /// Get the slot number associated with a type accounting for primitive
335 /// types, compaction tables, and function level vs module level.
336 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
337 if (Ty->isPrimitiveType())
338 return Ty->getTypeID();
340 // Scan the compaction table for the type if needed.
341 if (!CompactionTypes.empty()) {
342 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
343 if (CompactionTypes[i].first == Ty)
344 return Type::FirstDerivedTyID + i;
346 error("Couldn't find type specified in compaction table!");
349 // Check the function level types first...
350 TypeListTy::iterator I = find(FunctionTypes.begin(), FunctionTypes.end(), Ty);
352 if (I != FunctionTypes.end())
353 return Type::FirstDerivedTyID + ModuleTypes.size() +
354 (&*I - &FunctionTypes[0]);
356 // Check the module level types now...
357 I = find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
358 if (I == ModuleTypes.end())
359 error("Didn't find type in ModuleTypes.");
360 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
363 /// This is just like getType, but when a compaction table is in use, it is
364 /// ignored. It also ignores function level types.
366 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
367 if (Slot < Type::FirstDerivedTyID) {
368 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
370 error("Not a primitive type ID?");
373 Slot -= Type::FirstDerivedTyID;
374 if (Slot >= ModuleTypes.size())
375 error("Illegal compaction table type reference!");
376 return ModuleTypes[Slot];
379 /// This is just like getTypeSlot, but when a compaction table is in use, it
380 /// is ignored. It also ignores function level types.
381 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
382 if (Ty->isPrimitiveType())
383 return Ty->getTypeID();
384 TypeListTy::iterator I = find(ModuleTypes.begin(),
385 ModuleTypes.end(), Ty);
386 if (I == ModuleTypes.end())
387 error("Didn't find type in ModuleTypes.");
388 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
391 /// Retrieve a value of a given type and slot number, possibly creating
392 /// it if it doesn't already exist.
393 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
394 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
397 // If there is a compaction table active, it defines the low-level numbers.
398 // If not, the module values define the low-level numbers.
399 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
400 if (Num < CompactionValues[type].size())
401 return CompactionValues[type][Num];
402 Num -= CompactionValues[type].size();
404 // By default, the global type id is the type id passed in
405 unsigned GlobalTyID = type;
407 // If the type plane was compactified, figure out the global type ID by
408 // adding the derived type ids and the distance.
409 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
410 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
412 if (hasImplicitNull(GlobalTyID)) {
414 return Constant::getNullValue(getType(type));
418 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
419 if (Num < ModuleValues[GlobalTyID]->size())
420 return ModuleValues[GlobalTyID]->getOperand(Num);
421 Num -= ModuleValues[GlobalTyID]->size();
425 if (FunctionValues.size() > type &&
426 FunctionValues[type] &&
427 Num < FunctionValues[type]->size())
428 return FunctionValues[type]->getOperand(Num);
430 if (!Create) return 0; // Do not create a placeholder?
432 // Did we already create a place holder?
433 std::pair<unsigned,unsigned> KeyValue(type, oNum);
434 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
435 if (I != ForwardReferences.end() && I->first == KeyValue)
436 return I->second; // We have already created this placeholder
438 // If the type exists (it should)
439 if (const Type* Ty = getType(type)) {
440 // Create the place holder
441 Value *Val = new Argument(Ty);
442 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
445 throw "Can't create placeholder for value of type slot #" + utostr(type);
448 /// This is just like getValue, but when a compaction table is in use, it
449 /// is ignored. Also, no forward references or other fancy features are
451 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
453 return Constant::getNullValue(getType(TyID));
455 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
456 TyID -= Type::FirstDerivedTyID;
457 if (TyID >= CompactionTypes.size())
458 error("Type ID out of range for compaction table!");
459 TyID = CompactionTypes[TyID].second;
464 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
465 SlotNo >= ModuleValues[TyID]->size()) {
466 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
467 error("Corrupt compaction table entry!"
468 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
469 + utostr(ModuleValues.size()));
471 error("Corrupt compaction table entry!"
472 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
473 + utostr(ModuleValues.size()) + ", "
474 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
476 + utostr(ModuleValues[TyID]->size()));
478 return ModuleValues[TyID]->getOperand(SlotNo);
481 /// Just like getValue, except that it returns a null pointer
482 /// only on error. It always returns a constant (meaning that if the value is
483 /// defined, but is not a constant, that is an error). If the specified
484 /// constant hasn't been parsed yet, a placeholder is defined and used.
485 /// Later, after the real value is parsed, the placeholder is eliminated.
486 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
487 if (Value *V = getValue(TypeSlot, Slot, false))
488 if (Constant *C = dyn_cast<Constant>(V))
489 return C; // If we already have the value parsed, just return it
491 error("Value for slot " + utostr(Slot) +
492 " is expected to be a constant!");
494 const Type *Ty = getType(TypeSlot);
495 std::pair<const Type*, unsigned> Key(Ty, Slot);
496 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
498 if (I != ConstantFwdRefs.end() && I->first == Key) {
501 // Create a placeholder for the constant reference and
502 // keep track of the fact that we have a forward ref to recycle it
503 Constant *C = new ConstantPlaceHolder(Ty, Slot);
505 // Keep track of the fact that we have a forward ref to recycle it
506 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
511 //===----------------------------------------------------------------------===//
512 // IR Construction Methods
513 //===----------------------------------------------------------------------===//
515 /// As values are created, they are inserted into the appropriate place
516 /// with this method. The ValueTable argument must be one of ModuleValues
517 /// or FunctionValues data members of this class.
518 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
519 ValueTable &ValueTab) {
520 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
521 !hasImplicitNull(type) &&
522 "Cannot read null values from bytecode!");
524 if (ValueTab.size() <= type)
525 ValueTab.resize(type+1);
527 if (!ValueTab[type]) ValueTab[type] = new ValueList();
529 ValueTab[type]->push_back(Val);
531 bool HasOffset = hasImplicitNull(type);
532 return ValueTab[type]->size()-1 + HasOffset;
535 /// Insert the arguments of a function as new values in the reader.
536 void BytecodeReader::insertArguments(Function* F) {
537 const FunctionType *FT = F->getFunctionType();
538 Function::aiterator AI = F->abegin();
539 for (FunctionType::param_iterator It = FT->param_begin();
540 It != FT->param_end(); ++It, ++AI)
541 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
544 //===----------------------------------------------------------------------===//
545 // Bytecode Parsing Methods
546 //===----------------------------------------------------------------------===//
548 /// This method parses a single instruction. The instruction is
549 /// inserted at the end of the \p BB provided. The arguments of
550 /// the instruction are provided in the \p Args vector.
551 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
555 // Clear instruction data
559 unsigned Op = read_uint();
561 // bits Instruction format: Common to all formats
562 // --------------------------
563 // 01-00: Opcode type, fixed to 1.
565 Opcode = (Op >> 2) & 63;
566 Oprnds.resize((Op >> 0) & 03);
568 // Extract the operands
569 switch (Oprnds.size()) {
571 // bits Instruction format:
572 // --------------------------
573 // 19-08: Resulting type plane
574 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
576 iType = (Op >> 8) & 4095;
577 Oprnds[0] = (Op >> 20) & 4095;
578 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
582 // bits Instruction format:
583 // --------------------------
584 // 15-08: Resulting type plane
588 iType = (Op >> 8) & 255;
589 Oprnds[0] = (Op >> 16) & 255;
590 Oprnds[1] = (Op >> 24) & 255;
593 // bits Instruction format:
594 // --------------------------
595 // 13-08: Resulting type plane
600 iType = (Op >> 8) & 63;
601 Oprnds[0] = (Op >> 14) & 63;
602 Oprnds[1] = (Op >> 20) & 63;
603 Oprnds[2] = (Op >> 26) & 63;
606 At -= 4; // Hrm, try this again...
607 Opcode = read_vbr_uint();
609 iType = read_vbr_uint();
611 unsigned NumOprnds = read_vbr_uint();
612 Oprnds.resize(NumOprnds);
615 error("Zero-argument instruction found; this is invalid.");
617 for (unsigned i = 0; i != NumOprnds; ++i)
618 Oprnds[i] = read_vbr_uint();
623 const Type *InstTy = getSanitizedType(iType);
625 // We have enough info to inform the handler now.
626 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
628 // Declare the resulting instruction we'll build.
629 Instruction *Result = 0;
631 // Handle binary operators
632 if (Opcode >= Instruction::BinaryOpsBegin &&
633 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
634 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
635 getValue(iType, Oprnds[0]),
636 getValue(iType, Oprnds[1]));
641 error("Illegal instruction read!");
643 case Instruction::VAArg:
644 Result = new VAArgInst(getValue(iType, Oprnds[0]),
645 getSanitizedType(Oprnds[1]));
647 case Instruction::VANext:
648 Result = new VANextInst(getValue(iType, Oprnds[0]),
649 getSanitizedType(Oprnds[1]));
651 case Instruction::Cast:
652 Result = new CastInst(getValue(iType, Oprnds[0]),
653 getSanitizedType(Oprnds[1]));
655 case Instruction::Select:
656 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
657 getValue(iType, Oprnds[1]),
658 getValue(iType, Oprnds[2]));
660 case Instruction::PHI: {
661 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
662 error("Invalid phi node encountered!");
664 PHINode *PN = new PHINode(InstTy);
665 PN->op_reserve(Oprnds.size());
666 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
667 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
672 case Instruction::Shl:
673 case Instruction::Shr:
674 Result = new ShiftInst((Instruction::OtherOps)Opcode,
675 getValue(iType, Oprnds[0]),
676 getValue(Type::UByteTyID, Oprnds[1]));
678 case Instruction::Ret:
679 if (Oprnds.size() == 0)
680 Result = new ReturnInst();
681 else if (Oprnds.size() == 1)
682 Result = new ReturnInst(getValue(iType, Oprnds[0]));
684 error("Unrecognized instruction!");
687 case Instruction::Br:
688 if (Oprnds.size() == 1)
689 Result = new BranchInst(getBasicBlock(Oprnds[0]));
690 else if (Oprnds.size() == 3)
691 Result = new BranchInst(getBasicBlock(Oprnds[0]),
692 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
694 error("Invalid number of operands for a 'br' instruction!");
696 case Instruction::Switch: {
697 if (Oprnds.size() & 1)
698 error("Switch statement with odd number of arguments!");
700 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
701 getBasicBlock(Oprnds[1]));
702 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
703 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
704 getBasicBlock(Oprnds[i+1]));
709 case Instruction::Call: {
710 if (Oprnds.size() == 0)
711 error("Invalid call instruction encountered!");
713 Value *F = getValue(iType, Oprnds[0]);
715 // Check to make sure we have a pointer to function type
716 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
717 if (PTy == 0) error("Call to non function pointer value!");
718 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
719 if (FTy == 0) error("Call to non function pointer value!");
721 std::vector<Value *> Params;
722 if (!FTy->isVarArg()) {
723 FunctionType::param_iterator It = FTy->param_begin();
725 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
726 if (It == FTy->param_end())
727 error("Invalid call instruction!");
728 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
730 if (It != FTy->param_end())
731 error("Invalid call instruction!");
733 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
735 unsigned FirstVariableOperand;
736 if (Oprnds.size() < FTy->getNumParams())
737 error("Call instruction missing operands!");
739 // Read all of the fixed arguments
740 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
741 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
743 FirstVariableOperand = FTy->getNumParams();
745 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
746 error("Invalid call instruction!");
748 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
750 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
753 Result = new CallInst(F, Params);
756 case Instruction::Invoke: {
757 if (Oprnds.size() < 3)
758 error("Invalid invoke instruction!");
759 Value *F = getValue(iType, Oprnds[0]);
761 // Check to make sure we have a pointer to function type
762 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
764 error("Invoke to non function pointer value!");
765 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
767 error("Invoke to non function pointer value!");
769 std::vector<Value *> Params;
770 BasicBlock *Normal, *Except;
772 if (!FTy->isVarArg()) {
773 Normal = getBasicBlock(Oprnds[1]);
774 Except = getBasicBlock(Oprnds[2]);
776 FunctionType::param_iterator It = FTy->param_begin();
777 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
778 if (It == FTy->param_end())
779 error("Invalid invoke instruction!");
780 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
782 if (It != FTy->param_end())
783 error("Invalid invoke instruction!");
785 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
787 Normal = getBasicBlock(Oprnds[0]);
788 Except = getBasicBlock(Oprnds[1]);
790 unsigned FirstVariableArgument = FTy->getNumParams()+2;
791 for (unsigned i = 2; i != FirstVariableArgument; ++i)
792 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
795 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
796 error("Invalid invoke instruction!");
798 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
799 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
802 Result = new InvokeInst(F, Normal, Except, Params);
805 case Instruction::Malloc:
806 if (Oprnds.size() > 2)
807 error("Invalid malloc instruction!");
808 if (!isa<PointerType>(InstTy))
809 error("Invalid malloc instruction!");
811 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
812 Oprnds.size() ? getValue(Type::UIntTyID,
816 case Instruction::Alloca:
817 if (Oprnds.size() > 2)
818 error("Invalid alloca instruction!");
819 if (!isa<PointerType>(InstTy))
820 error("Invalid alloca instruction!");
822 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
823 Oprnds.size() ? getValue(Type::UIntTyID,
826 case Instruction::Free:
827 if (!isa<PointerType>(InstTy))
828 error("Invalid free instruction!");
829 Result = new FreeInst(getValue(iType, Oprnds[0]));
831 case Instruction::GetElementPtr: {
832 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
833 error("Invalid getelementptr instruction!");
835 std::vector<Value*> Idx;
837 const Type *NextTy = InstTy;
838 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
839 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
841 error("Invalid getelementptr instruction!");
843 unsigned ValIdx = Oprnds[i];
845 if (!hasRestrictedGEPTypes) {
846 // Struct indices are always uints, sequential type indices can be any
847 // of the 32 or 64-bit integer types. The actual choice of type is
848 // encoded in the low two bits of the slot number.
849 if (isa<StructType>(TopTy))
850 IdxTy = Type::UIntTyID;
852 switch (ValIdx & 3) {
854 case 0: IdxTy = Type::UIntTyID; break;
855 case 1: IdxTy = Type::IntTyID; break;
856 case 2: IdxTy = Type::ULongTyID; break;
857 case 3: IdxTy = Type::LongTyID; break;
862 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
865 Idx.push_back(getValue(IdxTy, ValIdx));
867 // Convert ubyte struct indices into uint struct indices.
868 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
869 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
870 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
872 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
875 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
879 case 62: // volatile load
880 case Instruction::Load:
881 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
882 error("Invalid load instruction!");
883 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
886 case 63: // volatile store
887 case Instruction::Store: {
888 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
889 error("Invalid store instruction!");
891 Value *Ptr = getValue(iType, Oprnds[1]);
892 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
893 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
897 case Instruction::Unwind:
898 if (Oprnds.size() != 0)
899 error("Invalid unwind instruction!");
900 Result = new UnwindInst();
902 } // end switch(Opcode)
905 if (Result->getType() == InstTy)
908 TypeSlot = getTypeSlot(Result->getType());
910 insertValue(Result, TypeSlot, FunctionValues);
911 BB->getInstList().push_back(Result);
914 /// Get a particular numbered basic block, which might be a forward reference.
915 /// This works together with ParseBasicBlock to handle these forward references
916 /// in a clean manner. This function is used when constructing phi, br, switch,
917 /// and other instructions that reference basic blocks. Blocks are numbered
918 /// sequentially as they appear in the function.
919 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
920 // Make sure there is room in the table...
921 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
923 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
924 // has already created this block, or if the forward reference has already
926 if (ParsedBasicBlocks[ID])
927 return ParsedBasicBlocks[ID];
929 // Otherwise, the basic block has not yet been created. Do so and add it to
930 // the ParsedBasicBlocks list.
931 return ParsedBasicBlocks[ID] = new BasicBlock();
934 /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
935 /// This method reads in one of the basicblock packets. This method is not used
936 /// for bytecode files after LLVM 1.0
937 /// @returns The basic block constructed.
938 BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
939 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
943 if (ParsedBasicBlocks.size() == BlockNo)
944 ParsedBasicBlocks.push_back(BB = new BasicBlock());
945 else if (ParsedBasicBlocks[BlockNo] == 0)
946 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
948 BB = ParsedBasicBlocks[BlockNo];
950 std::vector<unsigned> Operands;
951 while (moreInBlock())
952 ParseInstruction(Operands, BB);
954 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
958 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
959 /// In post 1.0 bytecode files, we no longer emit basic block individually,
960 /// in order to avoid per-basic-block overhead.
961 /// @returns Rhe number of basic blocks encountered.
962 unsigned BytecodeReader::ParseInstructionList(Function* F) {
963 unsigned BlockNo = 0;
964 std::vector<unsigned> Args;
966 while (moreInBlock()) {
967 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
969 if (ParsedBasicBlocks.size() == BlockNo)
970 ParsedBasicBlocks.push_back(BB = new BasicBlock());
971 else if (ParsedBasicBlocks[BlockNo] == 0)
972 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
974 BB = ParsedBasicBlocks[BlockNo];
976 F->getBasicBlockList().push_back(BB);
978 // Read instructions into this basic block until we get to a terminator
979 while (moreInBlock() && !BB->getTerminator())
980 ParseInstruction(Args, BB);
982 if (!BB->getTerminator())
983 error("Non-terminated basic block found!");
985 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
991 /// Parse a symbol table. This works for both module level and function
992 /// level symbol tables. For function level symbol tables, the CurrentFunction
993 /// parameter must be non-zero and the ST parameter must correspond to
994 /// CurrentFunction's symbol table. For Module level symbol tables, the
995 /// CurrentFunction argument must be zero.
996 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
998 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1000 // Allow efficient basic block lookup by number.
1001 std::vector<BasicBlock*> BBMap;
1002 if (CurrentFunction)
1003 for (Function::iterator I = CurrentFunction->begin(),
1004 E = CurrentFunction->end(); I != E; ++I)
1007 /// In LLVM 1.3 we write types separately from values so
1008 /// The types are always first in the symbol table. This is
1009 /// because Type no longer derives from Value.
1010 if (!hasTypeDerivedFromValue) {
1011 // Symtab block header: [num entries]
1012 unsigned NumEntries = read_vbr_uint();
1013 for (unsigned i = 0; i < NumEntries; ++i) {
1014 // Symtab entry: [def slot #][name]
1015 unsigned slot = read_vbr_uint();
1016 std::string Name = read_str();
1017 const Type* T = getType(slot);
1018 ST->insert(Name, T);
1022 while (moreInBlock()) {
1023 // Symtab block header: [num entries][type id number]
1024 unsigned NumEntries = read_vbr_uint();
1026 bool isTypeType = read_typeid(Typ);
1027 const Type *Ty = getType(Typ);
1029 for (unsigned i = 0; i != NumEntries; ++i) {
1030 // Symtab entry: [def slot #][name]
1031 unsigned slot = read_vbr_uint();
1032 std::string Name = read_str();
1034 // if we're reading a pre 1.3 bytecode file and the type plane
1035 // is the "type type", handle it here
1037 const Type* T = getType(slot);
1039 error("Failed type look-up for name '" + Name + "'");
1040 ST->insert(Name, T);
1041 continue; // code below must be short circuited
1044 if (Typ == Type::LabelTyID) {
1045 if (slot < BBMap.size())
1048 V = getValue(Typ, slot, false); // Find mapping...
1051 error("Failed value look-up for name '" + Name + "'");
1052 V->setName(Name, ST);
1056 checkPastBlockEnd("Symbol Table");
1057 if (Handler) Handler->handleSymbolTableEnd();
1060 /// Read in the types portion of a compaction table.
1061 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1062 for (unsigned i = 0; i != NumEntries; ++i) {
1063 unsigned TypeSlot = 0;
1064 if (read_typeid(TypeSlot))
1065 error("Invalid type in compaction table: type type");
1066 const Type *Typ = getGlobalTableType(TypeSlot);
1067 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1068 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1072 /// Parse a compaction table.
1073 void BytecodeReader::ParseCompactionTable() {
1075 // Notify handler that we're beginning a compaction table.
1076 if (Handler) Handler->handleCompactionTableBegin();
1078 // In LLVM 1.3 Type no longer derives from Value. So,
1079 // we always write them first in the compaction table
1080 // because they can't occupy a "type plane" where the
1082 if (! hasTypeDerivedFromValue) {
1083 unsigned NumEntries = read_vbr_uint();
1084 ParseCompactionTypes(NumEntries);
1087 // Compaction tables live in separate blocks so we have to loop
1088 // until we've read the whole thing.
1089 while (moreInBlock()) {
1090 // Read the number of Value* entries in the compaction table
1091 unsigned NumEntries = read_vbr_uint();
1093 unsigned isTypeType = false;
1095 // Decode the type from value read in. Most compaction table
1096 // planes will have one or two entries in them. If that's the
1097 // case then the length is encoded in the bottom two bits and
1098 // the higher bits encode the type. This saves another VBR value.
1099 if ((NumEntries & 3) == 3) {
1100 // In this case, both low-order bits are set (value 3). This
1101 // is a signal that the typeid follows.
1103 isTypeType = read_typeid(Ty);
1105 // In this case, the low-order bits specify the number of entries
1106 // and the high order bits specify the type.
1107 Ty = NumEntries >> 2;
1108 isTypeType = sanitizeTypeId(Ty);
1112 // if we're reading a pre 1.3 bytecode file and the type plane
1113 // is the "type type", handle it here
1115 ParseCompactionTypes(NumEntries);
1117 // Make sure we have enough room for the plane.
1118 if (Ty >= CompactionValues.size())
1119 CompactionValues.resize(Ty+1);
1121 // Make sure the plane is empty or we have some kind of error.
1122 if (!CompactionValues[Ty].empty())
1123 error("Compaction table plane contains multiple entries!");
1125 // Notify handler about the plane.
1126 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1128 // Push the implicit zero.
1129 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1131 // Read in each of the entries, put them in the compaction table
1132 // and notify the handler that we have a new compaction table value.
1133 for (unsigned i = 0; i != NumEntries; ++i) {
1134 unsigned ValSlot = read_vbr_uint();
1135 Value *V = getGlobalTableValue(Ty, ValSlot);
1136 CompactionValues[Ty].push_back(V);
1137 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1141 // Notify handler that the compaction table is done.
1142 if (Handler) Handler->handleCompactionTableEnd();
1145 // Parse a single type. The typeid is read in first. If its a primitive type
1146 // then nothing else needs to be read, we know how to instantiate it. If its
1147 // a derived type, then additional data is read to fill out the type
1149 const Type *BytecodeReader::ParseType() {
1150 unsigned PrimType = 0;
1151 if (read_typeid(PrimType))
1152 error("Invalid type (type type) in type constants!");
1154 const Type *Result = 0;
1155 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1159 case Type::FunctionTyID: {
1160 const Type *RetType = readSanitizedType();
1162 unsigned NumParams = read_vbr_uint();
1164 std::vector<const Type*> Params;
1166 Params.push_back(readSanitizedType());
1168 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1169 if (isVarArg) Params.pop_back();
1171 Result = FunctionType::get(RetType, Params, isVarArg);
1174 case Type::ArrayTyID: {
1175 const Type *ElementType = readSanitizedType();
1176 unsigned NumElements = read_vbr_uint();
1177 Result = ArrayType::get(ElementType, NumElements);
1180 case Type::PackedTyID: {
1181 const Type *ElementType = readSanitizedType();
1182 unsigned NumElements = read_vbr_uint();
1183 Result = PackedType::get(ElementType, NumElements);
1186 case Type::StructTyID: {
1187 std::vector<const Type*> Elements;
1189 if (read_typeid(Typ))
1190 error("Invalid element type (type type) for structure!");
1192 while (Typ) { // List is terminated by void/0 typeid
1193 Elements.push_back(getType(Typ));
1194 if (read_typeid(Typ))
1195 error("Invalid element type (type type) for structure!");
1198 Result = StructType::get(Elements);
1201 case Type::PointerTyID: {
1202 Result = PointerType::get(readSanitizedType());
1206 case Type::OpaqueTyID: {
1207 Result = OpaqueType::get();
1212 error("Don't know how to deserialize primitive type " + utostr(PrimType));
1215 if (Handler) Handler->handleType(Result);
1219 // ParseTypes - We have to use this weird code to handle recursive
1220 // types. We know that recursive types will only reference the current slab of
1221 // values in the type plane, but they can forward reference types before they
1222 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1223 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1224 // this ugly problem, we pessimistically insert an opaque type for each type we
1225 // are about to read. This means that forward references will resolve to
1226 // something and when we reread the type later, we can replace the opaque type
1227 // with a new resolved concrete type.
1229 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1230 assert(Tab.size() == 0 && "should not have read type constants in before!");
1232 // Insert a bunch of opaque types to be resolved later...
1233 Tab.reserve(NumEntries);
1234 for (unsigned i = 0; i != NumEntries; ++i)
1235 Tab.push_back(OpaqueType::get());
1238 Handler->handleTypeList(NumEntries);
1240 // Loop through reading all of the types. Forward types will make use of the
1241 // opaque types just inserted.
1243 for (unsigned i = 0; i != NumEntries; ++i) {
1244 const Type* NewTy = ParseType();
1245 const Type* OldTy = Tab[i].get();
1247 error("Couldn't parse type!");
1249 // Don't directly push the new type on the Tab. Instead we want to replace
1250 // the opaque type we previously inserted with the new concrete value. This
1251 // approach helps with forward references to types. The refinement from the
1252 // abstract (opaque) type to the new type causes all uses of the abstract
1253 // type to use the concrete type (NewTy). This will also cause the opaque
1254 // type to be deleted.
1255 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1257 // This should have replaced the old opaque type with the new type in the
1258 // value table... or with a preexisting type that was already in the system.
1259 // Let's just make sure it did.
1260 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1264 /// Parse a single constant value
1265 Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
1266 // We must check for a ConstantExpr before switching by type because
1267 // a ConstantExpr can be of any type, and has no explicit value.
1269 // 0 if not expr; numArgs if is expr
1270 unsigned isExprNumArgs = read_vbr_uint();
1272 if (isExprNumArgs) {
1273 // FIXME: Encoding of constant exprs could be much more compact!
1274 std::vector<Constant*> ArgVec;
1275 ArgVec.reserve(isExprNumArgs);
1276 unsigned Opcode = read_vbr_uint();
1278 // Read the slot number and types of each of the arguments
1279 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1280 unsigned ArgValSlot = read_vbr_uint();
1281 unsigned ArgTypeSlot = 0;
1282 if (read_typeid(ArgTypeSlot))
1283 error("Invalid argument type (type type) for constant value");
1285 // Get the arg value from its slot if it exists, otherwise a placeholder
1286 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1289 // Construct a ConstantExpr of the appropriate kind
1290 if (isExprNumArgs == 1) { // All one-operand expressions
1291 if (Opcode != Instruction::Cast)
1292 error("Only Cast instruction has one argument for ConstantExpr");
1294 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1295 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1297 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1298 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1300 if (hasRestrictedGEPTypes) {
1301 const Type *BaseTy = ArgVec[0]->getType();
1302 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1303 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1304 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1305 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1306 if (isa<StructType>(*GTI)) {
1307 if (IdxList[i]->getType() != Type::UByteTy)
1308 error("Invalid index for getelementptr!");
1309 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1313 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1314 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1316 } else if (Opcode == Instruction::Select) {
1317 if (ArgVec.size() != 3)
1318 error("Select instruction must have three arguments.");
1319 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1321 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1323 } else { // All other 2-operand expressions
1324 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1325 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1330 // Ok, not an ConstantExpr. We now know how to read the given type...
1331 const Type *Ty = getType(TypeID);
1332 switch (Ty->getTypeID()) {
1333 case Type::BoolTyID: {
1334 unsigned Val = read_vbr_uint();
1335 if (Val != 0 && Val != 1)
1336 error("Invalid boolean value read.");
1337 Constant* Result = ConstantBool::get(Val == 1);
1338 if (Handler) Handler->handleConstantValue(Result);
1342 case Type::UByteTyID: // Unsigned integer types...
1343 case Type::UShortTyID:
1344 case Type::UIntTyID: {
1345 unsigned Val = read_vbr_uint();
1346 if (!ConstantUInt::isValueValidForType(Ty, Val))
1347 error("Invalid unsigned byte/short/int read.");
1348 Constant* Result = ConstantUInt::get(Ty, Val);
1349 if (Handler) Handler->handleConstantValue(Result);
1353 case Type::ULongTyID: {
1354 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1355 if (Handler) Handler->handleConstantValue(Result);
1359 case Type::SByteTyID: // Signed integer types...
1360 case Type::ShortTyID:
1361 case Type::IntTyID: {
1362 case Type::LongTyID:
1363 int64_t Val = read_vbr_int64();
1364 if (!ConstantSInt::isValueValidForType(Ty, Val))
1365 error("Invalid signed byte/short/int/long read.");
1366 Constant* Result = ConstantSInt::get(Ty, Val);
1367 if (Handler) Handler->handleConstantValue(Result);
1371 case Type::FloatTyID: {
1374 Constant* Result = ConstantFP::get(Ty, Val);
1375 if (Handler) Handler->handleConstantValue(Result);
1379 case Type::DoubleTyID: {
1382 Constant* Result = ConstantFP::get(Ty, Val);
1383 if (Handler) Handler->handleConstantValue(Result);
1387 case Type::ArrayTyID: {
1388 const ArrayType *AT = cast<ArrayType>(Ty);
1389 unsigned NumElements = AT->getNumElements();
1390 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1391 std::vector<Constant*> Elements;
1392 Elements.reserve(NumElements);
1393 while (NumElements--) // Read all of the elements of the constant.
1394 Elements.push_back(getConstantValue(TypeSlot,
1396 Constant* Result = ConstantArray::get(AT, Elements);
1397 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1401 case Type::StructTyID: {
1402 const StructType *ST = cast<StructType>(Ty);
1404 std::vector<Constant *> Elements;
1405 Elements.reserve(ST->getNumElements());
1406 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1407 Elements.push_back(getConstantValue(ST->getElementType(i),
1410 Constant* Result = ConstantStruct::get(ST, Elements);
1411 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1415 case Type::PackedTyID: {
1416 const PackedType *PT = cast<PackedType>(Ty);
1417 unsigned NumElements = PT->getNumElements();
1418 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1419 std::vector<Constant*> Elements;
1420 Elements.reserve(NumElements);
1421 while (NumElements--) // Read all of the elements of the constant.
1422 Elements.push_back(getConstantValue(TypeSlot,
1424 Constant* Result = ConstantPacked::get(PT, Elements);
1425 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1429 case Type::PointerTyID: { // ConstantPointerRef value...
1430 const PointerType *PT = cast<PointerType>(Ty);
1431 unsigned Slot = read_vbr_uint();
1433 // Check to see if we have already read this global variable...
1434 Value *Val = getValue(TypeID, Slot, false);
1436 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1437 if (!GV) error("GlobalValue not in ValueTable!");
1438 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1441 error("Forward references are not allowed here.");
1446 error("Don't know how to deserialize constant value of type '" +
1447 Ty->getDescription());
1453 /// Resolve references for constants. This function resolves the forward
1454 /// referenced constants in the ConstantFwdRefs map. It uses the
1455 /// replaceAllUsesWith method of Value class to substitute the placeholder
1456 /// instance with the actual instance.
1457 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
1458 ConstantRefsType::iterator I =
1459 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1460 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
1462 Value *PH = I->second; // Get the placeholder...
1463 PH->replaceAllUsesWith(NewV);
1464 delete PH; // Delete the old placeholder
1465 ConstantFwdRefs.erase(I); // Remove the map entry for it
1468 /// Parse the constant strings section.
1469 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1470 for (; NumEntries; --NumEntries) {
1472 if (read_typeid(Typ))
1473 error("Invalid type (type type) for string constant");
1474 const Type *Ty = getType(Typ);
1475 if (!isa<ArrayType>(Ty))
1476 error("String constant data invalid!");
1478 const ArrayType *ATy = cast<ArrayType>(Ty);
1479 if (ATy->getElementType() != Type::SByteTy &&
1480 ATy->getElementType() != Type::UByteTy)
1481 error("String constant data invalid!");
1483 // Read character data. The type tells us how long the string is.
1484 char Data[ATy->getNumElements()];
1485 read_data(Data, Data+ATy->getNumElements());
1487 std::vector<Constant*> Elements(ATy->getNumElements());
1488 if (ATy->getElementType() == Type::SByteTy)
1489 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1490 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1492 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1493 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
1495 // Create the constant, inserting it as needed.
1496 Constant *C = ConstantArray::get(ATy, Elements);
1497 unsigned Slot = insertValue(C, Typ, Tab);
1498 ResolveReferencesToConstant(C, Slot);
1499 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1503 /// Parse the constant pool.
1504 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1505 TypeListTy &TypeTab,
1507 if (Handler) Handler->handleGlobalConstantsBegin();
1509 /// In LLVM 1.3 Type does not derive from Value so the types
1510 /// do not occupy a plane. Consequently, we read the types
1511 /// first in the constant pool.
1512 if (isFunction && !hasTypeDerivedFromValue) {
1513 unsigned NumEntries = read_vbr_uint();
1514 ParseTypes(TypeTab, NumEntries);
1517 while (moreInBlock()) {
1518 unsigned NumEntries = read_vbr_uint();
1520 bool isTypeType = read_typeid(Typ);
1522 /// In LLVM 1.2 and before, Types were written to the
1523 /// bytecode file in the "Type Type" plane (#12).
1524 /// In 1.3 plane 12 is now the label plane. Handle this here.
1526 ParseTypes(TypeTab, NumEntries);
1527 } else if (Typ == Type::VoidTyID) {
1528 /// Use of Type::VoidTyID is a misnomer. It actually means
1529 /// that the following plane is constant strings
1530 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1531 ParseStringConstants(NumEntries, Tab);
1533 for (unsigned i = 0; i < NumEntries; ++i) {
1534 Constant *C = ParseConstantValue(Typ);
1535 assert(C && "ParseConstantValue returned NULL!");
1536 unsigned Slot = insertValue(C, Typ, Tab);
1538 // If we are reading a function constant table, make sure that we adjust
1539 // the slot number to be the real global constant number.
1541 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1543 Slot += ModuleValues[Typ]->size();
1544 ResolveReferencesToConstant(C, Slot);
1548 checkPastBlockEnd("Constant Pool");
1549 if (Handler) Handler->handleGlobalConstantsEnd();
1552 /// Parse the contents of a function. Note that this function can be
1553 /// called lazily by materializeFunction
1554 /// @see materializeFunction
1555 void BytecodeReader::ParseFunctionBody(Function* F) {
1557 unsigned FuncSize = BlockEnd - At;
1558 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1560 unsigned LinkageType = read_vbr_uint();
1561 switch (LinkageType) {
1562 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1563 case 1: Linkage = GlobalValue::WeakLinkage; break;
1564 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1565 case 3: Linkage = GlobalValue::InternalLinkage; break;
1566 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1568 error("Invalid linkage type for Function.");
1569 Linkage = GlobalValue::InternalLinkage;
1573 F->setLinkage(Linkage);
1574 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1576 // Keep track of how many basic blocks we have read in...
1577 unsigned BlockNum = 0;
1578 bool InsertedArguments = false;
1580 BufPtr MyEnd = BlockEnd;
1581 while (At < MyEnd) {
1582 unsigned Type, Size;
1584 read_block(Type, Size);
1587 case BytecodeFormat::ConstantPoolBlockID:
1588 if (!InsertedArguments) {
1589 // Insert arguments into the value table before we parse the first basic
1590 // block in the function, but after we potentially read in the
1591 // compaction table.
1593 InsertedArguments = true;
1596 ParseConstantPool(FunctionValues, FunctionTypes, true);
1599 case BytecodeFormat::CompactionTableBlockID:
1600 ParseCompactionTable();
1603 case BytecodeFormat::BasicBlock: {
1604 if (!InsertedArguments) {
1605 // Insert arguments into the value table before we parse the first basic
1606 // block in the function, but after we potentially read in the
1607 // compaction table.
1609 InsertedArguments = true;
1612 BasicBlock *BB = ParseBasicBlock(BlockNum++);
1613 F->getBasicBlockList().push_back(BB);
1617 case BytecodeFormat::InstructionListBlockID: {
1618 // Insert arguments into the value table before we parse the instruction
1619 // list for the function, but after we potentially read in the compaction
1621 if (!InsertedArguments) {
1623 InsertedArguments = true;
1627 error("Already parsed basic blocks!");
1628 BlockNum = ParseInstructionList(F);
1632 case BytecodeFormat::SymbolTableBlockID:
1633 ParseSymbolTable(F, &F->getSymbolTable());
1639 error("Wrapped around reading bytecode.");
1644 // Malformed bc file if read past end of block.
1648 // Make sure there were no references to non-existant basic blocks.
1649 if (BlockNum != ParsedBasicBlocks.size())
1650 error("Illegal basic block operand reference");
1652 ParsedBasicBlocks.clear();
1654 // Resolve forward references. Replace any uses of a forward reference value
1655 // with the real value.
1657 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1658 // number of operands. PHI nodes often have forward references, and can also
1659 // often have a very large number of operands.
1661 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1662 // should be simplified back to using it!
1664 std::map<Value*, Value*> ForwardRefMapping;
1665 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1666 I = ForwardReferences.begin(), E = ForwardReferences.end();
1668 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1671 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1672 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1673 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1674 if (Value* V = I->getOperand(i))
1675 if (Argument *A = dyn_cast<Argument>(V)) {
1676 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1677 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1680 while (!ForwardReferences.empty()) {
1681 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1682 ForwardReferences.begin();
1683 Value *PlaceHolder = I->second;
1684 ForwardReferences.erase(I);
1686 // Now that all the uses are gone, delete the placeholder...
1687 // If we couldn't find a def (error case), then leak a little
1688 // memory, because otherwise we can't remove all uses!
1692 // Clear out function-level types...
1693 FunctionTypes.clear();
1694 CompactionTypes.clear();
1695 CompactionValues.clear();
1696 freeTable(FunctionValues);
1698 if (Handler) Handler->handleFunctionEnd(F);
1701 /// This function parses LLVM functions lazily. It obtains the type of the
1702 /// function and records where the body of the function is in the bytecode
1703 /// buffer. The caller can then use the ParseNextFunction and
1704 /// ParseAllFunctionBodies to get handler events for the functions.
1705 void BytecodeReader::ParseFunctionLazily() {
1706 if (FunctionSignatureList.empty())
1707 error("FunctionSignatureList empty!");
1709 Function *Func = FunctionSignatureList.back();
1710 FunctionSignatureList.pop_back();
1712 // Save the information for future reading of the function
1713 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1715 // Pretend we've `parsed' this function
1719 /// The ParserFunction method lazily parses one function. Use this method to
1720 /// casue the parser to parse a specific function in the module. Note that
1721 /// this will remove the function from what is to be included by
1722 /// ParseAllFunctionBodies.
1723 /// @see ParseAllFunctionBodies
1724 /// @see ParseBytecode
1725 void BytecodeReader::ParseFunction(Function* Func) {
1726 // Find {start, end} pointers and slot in the map. If not there, we're done.
1727 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1729 // Make sure we found it
1730 if (Fi == LazyFunctionLoadMap.end()) {
1731 error("Unrecognized function of type " + Func->getType()->getDescription());
1735 BlockStart = At = Fi->second.Buf;
1736 BlockEnd = Fi->second.EndBuf;
1737 assert(Fi->first == Func && "Found wrong function?");
1739 LazyFunctionLoadMap.erase(Fi);
1741 this->ParseFunctionBody(Func);
1744 /// The ParseAllFunctionBodies method parses through all the previously
1745 /// unparsed functions in the bytecode file. If you want to completely parse
1746 /// a bytecode file, this method should be called after Parsebytecode because
1747 /// Parsebytecode only records the locations in the bytecode file of where
1748 /// the function definitions are located. This function uses that information
1749 /// to materialize the functions.
1750 /// @see ParseBytecode
1751 void BytecodeReader::ParseAllFunctionBodies() {
1752 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1753 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1756 Function* Func = Fi->first;
1757 BlockStart = At = Fi->second.Buf;
1758 BlockEnd = Fi->second.EndBuf;
1759 this->ParseFunctionBody(Func);
1764 /// Parse the global type list
1765 void BytecodeReader::ParseGlobalTypes() {
1766 // Read the number of types
1767 unsigned NumEntries = read_vbr_uint();
1769 // Ignore the type plane identifier for types if the bc file is pre 1.3
1770 if (hasTypeDerivedFromValue)
1773 ParseTypes(ModuleTypes, NumEntries);
1776 /// Parse the Global info (types, global vars, constants)
1777 void BytecodeReader::ParseModuleGlobalInfo() {
1779 if (Handler) Handler->handleModuleGlobalsBegin();
1781 // Read global variables...
1782 unsigned VarType = read_vbr_uint();
1783 while (VarType != Type::VoidTyID) { // List is terminated by Void
1784 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1785 // Linkage, bit4+ = slot#
1786 unsigned SlotNo = VarType >> 5;
1787 if (sanitizeTypeId(SlotNo))
1788 error("Invalid type (type type) for global var!");
1789 unsigned LinkageID = (VarType >> 2) & 7;
1790 bool isConstant = VarType & 1;
1791 bool hasInitializer = VarType & 2;
1792 GlobalValue::LinkageTypes Linkage;
1794 switch (LinkageID) {
1795 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1796 case 1: Linkage = GlobalValue::WeakLinkage; break;
1797 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1798 case 3: Linkage = GlobalValue::InternalLinkage; break;
1799 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1801 error("Unknown linkage type: " + utostr(LinkageID));
1802 Linkage = GlobalValue::InternalLinkage;
1806 const Type *Ty = getType(SlotNo);
1808 error("Global has no type! SlotNo=" + utostr(SlotNo));
1811 if (!isa<PointerType>(Ty)) {
1812 error("Global not a pointer type! Ty= " + Ty->getDescription());
1815 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1817 // Create the global variable...
1818 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1820 insertValue(GV, SlotNo, ModuleValues);
1822 unsigned initSlot = 0;
1823 if (hasInitializer) {
1824 initSlot = read_vbr_uint();
1825 GlobalInits.push_back(std::make_pair(GV, initSlot));
1828 // Notify handler about the global value.
1829 if (Handler) Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo, initSlot);
1832 VarType = read_vbr_uint();
1835 // Read the function objects for all of the functions that are coming
1836 unsigned FnSignature = 0;
1837 if (read_typeid(FnSignature))
1838 error("Invalid function type (type type) found");
1840 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1841 const Type *Ty = getType(FnSignature);
1842 if (!isa<PointerType>(Ty) ||
1843 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1844 error("Function not a pointer to function type! Ty = " +
1845 Ty->getDescription());
1846 // FIXME: what should Ty be if handler continues?
1849 // We create functions by passing the underlying FunctionType to create...
1850 const FunctionType* FTy =
1851 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1853 // Insert the place hodler
1854 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
1856 insertValue(Func, FnSignature, ModuleValues);
1858 // Save this for later so we know type of lazily instantiated functions
1859 FunctionSignatureList.push_back(Func);
1861 if (Handler) Handler->handleFunctionDeclaration(Func);
1863 // Get Next function signature
1864 if (read_typeid(FnSignature))
1865 error("Invalid function type (type type) found");
1868 // Now that the function signature list is set up, reverse it so that we can
1869 // remove elements efficiently from the back of the vector.
1870 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1872 // If this bytecode format has dependent library information in it ..
1873 if (!hasNoDependentLibraries) {
1874 // Read in the number of dependent library items that follow
1875 unsigned num_dep_libs = read_vbr_uint();
1876 std::string dep_lib;
1877 while( num_dep_libs-- ) {
1878 dep_lib = read_str();
1879 TheModule->addLibrary(dep_lib);
1881 Handler->handleDependentLibrary(dep_lib);
1885 // Read target triple and place into the module
1886 std::string triple = read_str();
1887 TheModule->setTargetTriple(triple);
1889 Handler->handleTargetTriple(triple);
1892 if (hasInconsistentModuleGlobalInfo)
1895 // This is for future proofing... in the future extra fields may be added that
1896 // we don't understand, so we transparently ignore them.
1900 if (Handler) Handler->handleModuleGlobalsEnd();
1903 /// Parse the version information and decode it by setting flags on the
1904 /// Reader that enable backward compatibility of the reader.
1905 void BytecodeReader::ParseVersionInfo() {
1906 unsigned Version = read_vbr_uint();
1908 // Unpack version number: low four bits are for flags, top bits = version
1909 Module::Endianness Endianness;
1910 Module::PointerSize PointerSize;
1911 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1912 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1914 bool hasNoEndianness = Version & 4;
1915 bool hasNoPointerSize = Version & 8;
1917 RevisionNum = Version >> 4;
1919 // Default values for the current bytecode version
1920 hasInconsistentModuleGlobalInfo = false;
1921 hasExplicitPrimitiveZeros = false;
1922 hasRestrictedGEPTypes = false;
1923 hasTypeDerivedFromValue = false;
1924 hasLongBlockHeaders = false;
1925 has32BitTypes = false;
1926 hasNoDependentLibraries = false;
1927 hasAlignment = false;
1928 hasInconsistentBBSlotNums = false;
1929 hasVBRByteTypes = false;
1930 hasUnnecessaryModuleBlockId = false;
1932 switch (RevisionNum) {
1933 case 0: // LLVM 1.0, 1.1 (Released)
1934 // Base LLVM 1.0 bytecode format.
1935 hasInconsistentModuleGlobalInfo = true;
1936 hasExplicitPrimitiveZeros = true;
1940 case 1: // LLVM 1.2 (Released)
1941 // LLVM 1.2 added explicit support for emitting strings efficiently.
1943 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1944 // included the size for the alignment at the end, where the rest of the
1947 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1948 // structures and longs for sequential types.
1949 hasRestrictedGEPTypes = true;
1951 // LLVM 1.2 and before had the Type class derive from Value class. This
1952 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1953 // written differently because Types can no longer be part of the
1954 // type planes for Values.
1955 hasTypeDerivedFromValue = true;
1959 case 2: // 1.2.5 (Not Released)
1961 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1962 // especially for small files where the 8 bytes per block is a large fraction
1963 // of the total block size. In LLVM 1.3, the block type and length are
1964 // compressed into a single 32-bit unsigned integer. 27 bits for length, 5
1965 // bits for block type.
1966 hasLongBlockHeaders = true;
1968 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
1969 // this has been reduced to vbr_uint24. It shouldn't make much difference
1970 // since we haven't run into a module with > 24 million types, but for safety
1971 // the 24-bit restriction has been enforced in 1.3 to free some bits in
1972 // various places and to ensure consistency.
1973 has32BitTypes = true;
1975 // LLVM 1.2 and earlier did not provide a target triple nor a list of
1976 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
1977 // features, for use in future versions of LLVM.
1978 hasNoDependentLibraries = true;
1982 case 3: // LLVM 1.3 (Released)
1983 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
1984 // boundaries and at the end of some strings. In extreme cases (e.g. lots
1985 // of GEP references to a constant array), this can increase the file size
1986 // by 30% or more. In version 1.4 alignment is done away with completely.
1987 hasAlignment = true;
1991 case 4: // 1.3.1 (Not Released)
1992 // In version 4, basic blocks have a minimum index of 0 whereas all the
1993 // other primitives have a minimum index of 1 (because 0 is the "null"
1994 // value. In version 5, we made this consistent.
1995 hasInconsistentBBSlotNums = true;
1997 // In version 4, the types SByte and UByte were encoded as vbr_uint so that
1998 // signed values > 63 and unsigned values >127 would be encoded as two
1999 // bytes. In version 5, they are encoded directly in a single byte.
2000 hasVBRByteTypes = true;
2002 // In version 4, modules begin with a "Module Block" which encodes a 4-byte
2003 // integer value 0x01 to identify the module block. This is unnecessary and
2004 // removed in version 5.
2005 hasUnnecessaryModuleBlockId = true;
2009 case 5: // LLVM 1.4 (Released)
2012 error("Unknown bytecode version number: " + itostr(RevisionNum));
2015 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2016 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2018 TheModule->setEndianness(Endianness);
2019 TheModule->setPointerSize(PointerSize);
2021 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2024 /// Parse a whole module.
2025 void BytecodeReader::ParseModule() {
2026 unsigned Type, Size;
2028 FunctionSignatureList.clear(); // Just in case...
2030 // Read into instance variables...
2034 bool SeenModuleGlobalInfo = false;
2035 bool SeenGlobalTypePlane = false;
2036 BufPtr MyEnd = BlockEnd;
2037 while (At < MyEnd) {
2039 read_block(Type, Size);
2043 case BytecodeFormat::GlobalTypePlaneBlockID:
2044 if (SeenGlobalTypePlane)
2045 error("Two GlobalTypePlane Blocks Encountered!");
2049 SeenGlobalTypePlane = true;
2052 case BytecodeFormat::ModuleGlobalInfoBlockID:
2053 if (SeenModuleGlobalInfo)
2054 error("Two ModuleGlobalInfo Blocks Encountered!");
2055 ParseModuleGlobalInfo();
2056 SeenModuleGlobalInfo = true;
2059 case BytecodeFormat::ConstantPoolBlockID:
2060 ParseConstantPool(ModuleValues, ModuleTypes,false);
2063 case BytecodeFormat::FunctionBlockID:
2064 ParseFunctionLazily();
2067 case BytecodeFormat::SymbolTableBlockID:
2068 ParseSymbolTable(0, &TheModule->getSymbolTable());
2074 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2082 // After the module constant pool has been read, we can safely initialize
2083 // global variables...
2084 while (!GlobalInits.empty()) {
2085 GlobalVariable *GV = GlobalInits.back().first;
2086 unsigned Slot = GlobalInits.back().second;
2087 GlobalInits.pop_back();
2089 // Look up the initializer value...
2090 // FIXME: Preserve this type ID!
2092 const llvm::PointerType* GVType = GV->getType();
2093 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2094 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2095 if (GV->hasInitializer())
2096 error("Global *already* has an initializer?!");
2097 if (Handler) Handler->handleGlobalInitializer(GV,CV);
2098 GV->setInitializer(CV);
2100 error("Cannot find initializer value.");
2103 /// Make sure we pulled them all out. If we didn't then there's a declaration
2104 /// but a missing body. That's not allowed.
2105 if (!FunctionSignatureList.empty())
2106 error("Function declared, but bytecode stream ended before definition");
2109 /// This function completely parses a bytecode buffer given by the \p Buf
2110 /// and \p Length parameters.
2111 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2112 const std::string &ModuleID) {
2115 At = MemStart = BlockStart = Buf;
2116 MemEnd = BlockEnd = Buf + Length;
2118 // Create the module
2119 TheModule = new Module(ModuleID);
2121 if (Handler) Handler->handleStart(TheModule, Length);
2123 // Read and check signature...
2124 unsigned Sig = read_uint();
2125 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2126 error("Invalid bytecode signature: " + utostr(Sig));
2129 // Tell the handler we're starting a module
2130 if (Handler) Handler->handleModuleBegin(ModuleID);
2132 // Get the module block and size and verify. This is handled specially
2133 // because the module block/size is always written in long format. Other
2134 // blocks are written in short format so the read_block method is used.
2135 unsigned Type, Size;
2138 if (Type != BytecodeFormat::ModuleBlockID) {
2139 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2142 if (At + Size != MemEnd) {
2143 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2144 + ", Size:" + utostr(Size));
2147 // Parse the module contents
2148 this->ParseModule();
2150 // Check for missing functions
2152 error("Function expected, but bytecode stream ended!");
2154 // Tell the handler we're done with the module
2156 Handler->handleModuleEnd(ModuleID);
2158 // Tell the handler we're finished the parse
2159 if (Handler) Handler->handleFinish();
2161 } catch (std::string& errstr) {
2162 if (Handler) Handler->handleError(errstr);
2168 std::string msg("Unknown Exception Occurred");
2169 if (Handler) Handler->handleError(msg);
2177 //===----------------------------------------------------------------------===//
2178 //=== Default Implementations of Handler Methods
2179 //===----------------------------------------------------------------------===//
2181 BytecodeHandler::~BytecodeHandler() {}