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 +
75 /// Align the buffer position to a 32 bit boundary
76 inline void BytecodeReader::align32() {
79 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
81 if (Handler) Handler->handleAlignment(At - Save);
83 error("Ran out of data while aligning!");
87 /// Read a whole unsigned integer
88 inline unsigned BytecodeReader::read_uint() {
90 error("Ran out of data reading uint!");
92 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
95 /// Read a variable-bit-rate encoded unsigned integer
96 inline unsigned BytecodeReader::read_vbr_uint() {
103 error("Ran out of data reading vbr_uint!");
104 Result |= (unsigned)((*At++) & 0x7F) << Shift;
106 } while (At[-1] & 0x80);
107 if (Handler) Handler->handleVBR32(At-Save);
111 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
112 inline uint64_t BytecodeReader::read_vbr_uint64() {
119 error("Ran out of data reading vbr_uint64!");
120 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
122 } while (At[-1] & 0x80);
123 if (Handler) Handler->handleVBR64(At-Save);
127 /// Read a variable-bit-rate encoded signed 64-bit integer.
128 inline int64_t BytecodeReader::read_vbr_int64() {
129 uint64_t R = read_vbr_uint64();
132 return -(int64_t)(R >> 1);
133 else // There is no such thing as -0 with integers. "-0" really means
134 // 0x8000000000000000.
137 return (int64_t)(R >> 1);
140 /// Read a pascal-style string (length followed by text)
141 inline std::string BytecodeReader::read_str() {
142 unsigned Size = read_vbr_uint();
143 const unsigned char *OldAt = At;
145 if (At > BlockEnd) // Size invalid?
146 error("Ran out of data reading a string!");
147 return std::string((char*)OldAt, Size);
150 /// Read an arbitrary block of data
151 inline void BytecodeReader::read_data(void *Ptr, void *End) {
152 unsigned char *Start = (unsigned char *)Ptr;
153 unsigned Amount = (unsigned char *)End - Start;
154 if (At+Amount > BlockEnd)
155 error("Ran out of data!");
156 std::copy(At, At+Amount, Start);
160 /// Read a float value in little-endian order
161 inline void BytecodeReader::read_float(float& FloatVal) {
162 /// FIXME: This isn't optimal, it has size problems on some platforms
163 /// where FP is not IEEE.
168 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
169 At+=sizeof(uint32_t);
170 FloatVal = FloatUnion.f;
173 /// Read a double value in little-endian order
174 inline void BytecodeReader::read_double(double& DoubleVal) {
175 /// FIXME: This isn't optimal, it has size problems on some platforms
176 /// where FP is not IEEE.
181 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
182 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
183 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
184 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
185 At+=sizeof(uint64_t);
186 DoubleVal = DoubleUnion.d;
189 /// Read a block header and obtain its type and size
190 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
191 if ( hasLongBlockHeaders ) {
195 case BytecodeFormat::Reserved_DoNotUse :
196 error("Reserved_DoNotUse used as Module Type?");
197 Type = BytecodeFormat::ModuleBlockID; break;
198 case BytecodeFormat::Module:
199 Type = BytecodeFormat::ModuleBlockID; break;
200 case BytecodeFormat::Function:
201 Type = BytecodeFormat::FunctionBlockID; break;
202 case BytecodeFormat::ConstantPool:
203 Type = BytecodeFormat::ConstantPoolBlockID; break;
204 case BytecodeFormat::SymbolTable:
205 Type = BytecodeFormat::SymbolTableBlockID; break;
206 case BytecodeFormat::ModuleGlobalInfo:
207 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
208 case BytecodeFormat::GlobalTypePlane:
209 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
210 case BytecodeFormat::InstructionList:
211 Type = BytecodeFormat::InstructionListBlockID; break;
212 case BytecodeFormat::CompactionTable:
213 Type = BytecodeFormat::CompactionTableBlockID; break;
214 case BytecodeFormat::BasicBlock:
215 /// This block type isn't used after version 1.1. However, we have to
216 /// still allow the value in case this is an old bc format file.
217 /// We just let its value creep thru.
220 error("Invalid block id found: " + utostr(Type));
225 Type = Size & 0x1F; // mask low order five bits
226 Size >>= 5; // get rid of five low order bits, leaving high 27
229 if (At + Size > BlockEnd)
230 error("Attempt to size a block past end of memory");
231 BlockEnd = At + Size;
232 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
236 /// In LLVM 1.2 and before, Types were derived from Value and so they were
237 /// written as part of the type planes along with any other Value. In LLVM
238 /// 1.3 this changed so that Type does not derive from Value. Consequently,
239 /// the BytecodeReader's containers for Values can't contain Types because
240 /// there's no inheritance relationship. This means that the "Type Type"
241 /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
242 /// whenever a bytecode construct must have both types and values together,
243 /// the types are always read/written first and then the Values. Furthermore
244 /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
245 /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
246 /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
247 /// For LLVM 1.2 and before, this function will decrement the type id by
248 /// one to account for the missing Type::TypeTyID enumerator if the value is
249 /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
250 /// function returns true, otherwise false. This helps detect situations
251 /// where the pre 1.3 bytecode is indicating that what follows is a type.
252 /// @returns true iff type id corresponds to pre 1.3 "type type"
253 inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
254 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
255 if (TypeId == Type::LabelTyID) {
256 TypeId = Type::VoidTyID; // sanitize it
257 return true; // indicate we got TypeTyID in pre 1.3 bytecode
258 } else if (TypeId > Type::LabelTyID)
259 --TypeId; // shift all planes down because type type plane is missing
264 /// Reads a vbr uint to read in a type id and does the necessary
265 /// conversion on it by calling sanitizeTypeId.
266 /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
267 /// @see sanitizeTypeId
268 inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
269 TypeId = read_vbr_uint();
270 if ( !has32BitTypes )
271 if ( TypeId == 0x00FFFFFF )
272 TypeId = read_vbr_uint();
273 return sanitizeTypeId(TypeId);
276 //===----------------------------------------------------------------------===//
278 //===----------------------------------------------------------------------===//
280 /// Determine if a type id has an implicit null value
281 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
282 if (!hasExplicitPrimitiveZeros)
283 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
284 return TyID >= Type::FirstDerivedTyID;
287 /// Obtain a type given a typeid and account for things like compaction tables,
288 /// function level vs module level, and the offsetting for the primitive types.
289 const Type *BytecodeReader::getType(unsigned ID) {
290 if (ID < Type::FirstDerivedTyID)
291 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
292 return T; // Asked for a primitive type...
294 // Otherwise, derived types need offset...
295 ID -= Type::FirstDerivedTyID;
297 if (!CompactionTypes.empty()) {
298 if (ID >= CompactionTypes.size())
299 error("Type ID out of range for compaction table!");
300 return CompactionTypes[ID].first;
303 // Is it a module-level type?
304 if (ID < ModuleTypes.size())
305 return ModuleTypes[ID].get();
307 // Nope, is it a function-level type?
308 ID -= ModuleTypes.size();
309 if (ID < FunctionTypes.size())
310 return FunctionTypes[ID].get();
312 error("Illegal type reference!");
316 /// Get a sanitized type id. This just makes sure that the \p ID
317 /// is both sanitized and not the "type type" of pre-1.3 bytecode.
318 /// @see sanitizeTypeId
319 inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
320 if (sanitizeTypeId(ID))
321 error("Invalid type id encountered");
325 /// This method just saves some coding. It uses read_typeid to read
326 /// in a sanitized type id, errors that its not the type type, and
327 /// then calls getType to return the type value.
328 inline const Type* BytecodeReader::readSanitizedType() {
331 error("Invalid type id encountered");
335 /// Get the slot number associated with a type accounting for primitive
336 /// types, compaction tables, and function level vs module level.
337 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
338 if (Ty->isPrimitiveType())
339 return Ty->getTypeID();
341 // Scan the compaction table for the type if needed.
342 if (!CompactionTypes.empty()) {
343 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
344 if (CompactionTypes[i].first == Ty)
345 return Type::FirstDerivedTyID + i;
347 error("Couldn't find type specified in compaction table!");
350 // Check the function level types first...
351 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
352 FunctionTypes.end(), Ty);
354 if (I != FunctionTypes.end())
355 return Type::FirstDerivedTyID + ModuleTypes.size() +
356 (&*I - &FunctionTypes[0]);
358 // Check the module level types now...
359 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
360 if (I == ModuleTypes.end())
361 error("Didn't find type in ModuleTypes.");
362 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
365 /// This is just like getType, but when a compaction table is in use, it is
366 /// ignored. It also ignores function level types.
368 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
369 if (Slot < Type::FirstDerivedTyID) {
370 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
372 error("Not a primitive type ID?");
375 Slot -= Type::FirstDerivedTyID;
376 if (Slot >= ModuleTypes.size())
377 error("Illegal compaction table type reference!");
378 return ModuleTypes[Slot];
381 /// This is just like getTypeSlot, but when a compaction table is in use, it
382 /// is ignored. It also ignores function level types.
383 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
384 if (Ty->isPrimitiveType())
385 return Ty->getTypeID();
386 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
387 ModuleTypes.end(), Ty);
388 if (I == ModuleTypes.end())
389 error("Didn't find type in ModuleTypes.");
390 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
393 /// Retrieve a value of a given type and slot number, possibly creating
394 /// it if it doesn't already exist.
395 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
396 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
399 // If there is a compaction table active, it defines the low-level numbers.
400 // If not, the module values define the low-level numbers.
401 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
402 if (Num < CompactionValues[type].size())
403 return CompactionValues[type][Num];
404 Num -= CompactionValues[type].size();
406 // By default, the global type id is the type id passed in
407 unsigned GlobalTyID = type;
409 // If the type plane was compactified, figure out the global type ID by
410 // adding the derived type ids and the distance.
411 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
412 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
414 if (hasImplicitNull(GlobalTyID)) {
416 return Constant::getNullValue(getType(type));
420 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
421 if (Num < ModuleValues[GlobalTyID]->size())
422 return ModuleValues[GlobalTyID]->getOperand(Num);
423 Num -= ModuleValues[GlobalTyID]->size();
427 if (FunctionValues.size() > type &&
428 FunctionValues[type] &&
429 Num < FunctionValues[type]->size())
430 return FunctionValues[type]->getOperand(Num);
432 if (!Create) return 0; // Do not create a placeholder?
434 // Did we already create a place holder?
435 std::pair<unsigned,unsigned> KeyValue(type, oNum);
436 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
437 if (I != ForwardReferences.end() && I->first == KeyValue)
438 return I->second; // We have already created this placeholder
440 // If the type exists (it should)
441 if (const Type* Ty = getType(type)) {
442 // Create the place holder
443 Value *Val = new Argument(Ty);
444 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
447 throw "Can't create placeholder for value of type slot #" + utostr(type);
450 /// This is just like getValue, but when a compaction table is in use, it
451 /// is ignored. Also, no forward references or other fancy features are
453 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
455 return Constant::getNullValue(getType(TyID));
457 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
458 TyID -= Type::FirstDerivedTyID;
459 if (TyID >= CompactionTypes.size())
460 error("Type ID out of range for compaction table!");
461 TyID = CompactionTypes[TyID].second;
466 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
467 SlotNo >= ModuleValues[TyID]->size()) {
468 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
469 error("Corrupt compaction table entry!"
470 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
471 + utostr(ModuleValues.size()));
473 error("Corrupt compaction table entry!"
474 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
475 + utostr(ModuleValues.size()) + ", "
476 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
478 + utostr(ModuleValues[TyID]->size()));
480 return ModuleValues[TyID]->getOperand(SlotNo);
483 /// Just like getValue, except that it returns a null pointer
484 /// only on error. It always returns a constant (meaning that if the value is
485 /// defined, but is not a constant, that is an error). If the specified
486 /// constant hasn't been parsed yet, a placeholder is defined and used.
487 /// Later, after the real value is parsed, the placeholder is eliminated.
488 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
489 if (Value *V = getValue(TypeSlot, Slot, false))
490 if (Constant *C = dyn_cast<Constant>(V))
491 return C; // If we already have the value parsed, just return it
493 error("Value for slot " + utostr(Slot) +
494 " is expected to be a constant!");
496 const Type *Ty = getType(TypeSlot);
497 std::pair<const Type*, unsigned> Key(Ty, Slot);
498 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
500 if (I != ConstantFwdRefs.end() && I->first == Key) {
503 // Create a placeholder for the constant reference and
504 // keep track of the fact that we have a forward ref to recycle it
505 Constant *C = new ConstantPlaceHolder(Ty, Slot);
507 // Keep track of the fact that we have a forward ref to recycle it
508 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
513 //===----------------------------------------------------------------------===//
514 // IR Construction Methods
515 //===----------------------------------------------------------------------===//
517 /// As values are created, they are inserted into the appropriate place
518 /// with this method. The ValueTable argument must be one of ModuleValues
519 /// or FunctionValues data members of this class.
520 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
521 ValueTable &ValueTab) {
522 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
523 !hasImplicitNull(type) &&
524 "Cannot read null values from bytecode!");
526 if (ValueTab.size() <= type)
527 ValueTab.resize(type+1);
529 if (!ValueTab[type]) ValueTab[type] = new ValueList();
531 ValueTab[type]->push_back(Val);
533 bool HasOffset = hasImplicitNull(type);
534 return ValueTab[type]->size()-1 + HasOffset;
537 /// Insert the arguments of a function as new values in the reader.
538 void BytecodeReader::insertArguments(Function* F) {
539 const FunctionType *FT = F->getFunctionType();
540 Function::aiterator AI = F->abegin();
541 for (FunctionType::param_iterator It = FT->param_begin();
542 It != FT->param_end(); ++It, ++AI)
543 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
546 //===----------------------------------------------------------------------===//
547 // Bytecode Parsing Methods
548 //===----------------------------------------------------------------------===//
550 /// This method parses a single instruction. The instruction is
551 /// inserted at the end of the \p BB provided. The arguments of
552 /// the instruction are provided in the \p Oprnds vector.
553 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
557 // Clear instruction data
561 unsigned Op = read_uint();
563 // bits Instruction format: Common to all formats
564 // --------------------------
565 // 01-00: Opcode type, fixed to 1.
567 Opcode = (Op >> 2) & 63;
568 Oprnds.resize((Op >> 0) & 03);
570 // Extract the operands
571 switch (Oprnds.size()) {
573 // bits Instruction format:
574 // --------------------------
575 // 19-08: Resulting type plane
576 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
578 iType = (Op >> 8) & 4095;
579 Oprnds[0] = (Op >> 20) & 4095;
580 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
584 // bits Instruction format:
585 // --------------------------
586 // 15-08: Resulting type plane
590 iType = (Op >> 8) & 255;
591 Oprnds[0] = (Op >> 16) & 255;
592 Oprnds[1] = (Op >> 24) & 255;
595 // bits Instruction format:
596 // --------------------------
597 // 13-08: Resulting type plane
602 iType = (Op >> 8) & 63;
603 Oprnds[0] = (Op >> 14) & 63;
604 Oprnds[1] = (Op >> 20) & 63;
605 Oprnds[2] = (Op >> 26) & 63;
608 At -= 4; // Hrm, try this again...
609 Opcode = read_vbr_uint();
611 iType = read_vbr_uint();
613 unsigned NumOprnds = read_vbr_uint();
614 Oprnds.resize(NumOprnds);
617 error("Zero-argument instruction found; this is invalid.");
619 for (unsigned i = 0; i != NumOprnds; ++i)
620 Oprnds[i] = read_vbr_uint();
625 const Type *InstTy = getSanitizedType(iType);
627 // We have enough info to inform the handler now.
628 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
630 // Declare the resulting instruction we'll build.
631 Instruction *Result = 0;
633 // If this is a bytecode format that did not include the unreachable
634 // instruction, bump up all opcodes numbers to make space.
635 if (hasNoUnreachableInst) {
636 if (Opcode >= Instruction::Unreachable &&
642 // Handle binary operators
643 if (Opcode >= Instruction::BinaryOpsBegin &&
644 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
645 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
646 getValue(iType, Oprnds[0]),
647 getValue(iType, Oprnds[1]));
652 error("Illegal instruction read!");
654 case Instruction::VAArg:
655 Result = new VAArgInst(getValue(iType, Oprnds[0]),
656 getSanitizedType(Oprnds[1]));
658 case Instruction::VANext:
659 Result = new VANextInst(getValue(iType, Oprnds[0]),
660 getSanitizedType(Oprnds[1]));
662 case Instruction::Cast:
663 Result = new CastInst(getValue(iType, Oprnds[0]),
664 getSanitizedType(Oprnds[1]));
666 case Instruction::Select:
667 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
668 getValue(iType, Oprnds[1]),
669 getValue(iType, Oprnds[2]));
671 case Instruction::PHI: {
672 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
673 error("Invalid phi node encountered!");
675 PHINode *PN = new PHINode(InstTy);
676 PN->op_reserve(Oprnds.size());
677 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
678 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
683 case Instruction::Shl:
684 case Instruction::Shr:
685 Result = new ShiftInst((Instruction::OtherOps)Opcode,
686 getValue(iType, Oprnds[0]),
687 getValue(Type::UByteTyID, Oprnds[1]));
689 case Instruction::Ret:
690 if (Oprnds.size() == 0)
691 Result = new ReturnInst();
692 else if (Oprnds.size() == 1)
693 Result = new ReturnInst(getValue(iType, Oprnds[0]));
695 error("Unrecognized instruction!");
698 case Instruction::Br:
699 if (Oprnds.size() == 1)
700 Result = new BranchInst(getBasicBlock(Oprnds[0]));
701 else if (Oprnds.size() == 3)
702 Result = new BranchInst(getBasicBlock(Oprnds[0]),
703 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
705 error("Invalid number of operands for a 'br' instruction!");
707 case Instruction::Switch: {
708 if (Oprnds.size() & 1)
709 error("Switch statement with odd number of arguments!");
711 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
712 getBasicBlock(Oprnds[1]));
713 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
714 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
715 getBasicBlock(Oprnds[i+1]));
720 case Instruction::Call: {
721 if (Oprnds.size() == 0)
722 error("Invalid call instruction encountered!");
724 Value *F = getValue(iType, Oprnds[0]);
726 // Check to make sure we have a pointer to function type
727 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
728 if (PTy == 0) error("Call to non function pointer value!");
729 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
730 if (FTy == 0) error("Call to non function pointer value!");
732 std::vector<Value *> Params;
733 if (!FTy->isVarArg()) {
734 FunctionType::param_iterator It = FTy->param_begin();
736 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
737 if (It == FTy->param_end())
738 error("Invalid call instruction!");
739 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
741 if (It != FTy->param_end())
742 error("Invalid call instruction!");
744 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
746 unsigned FirstVariableOperand;
747 if (Oprnds.size() < FTy->getNumParams())
748 error("Call instruction missing operands!");
750 // Read all of the fixed arguments
751 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
752 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
754 FirstVariableOperand = FTy->getNumParams();
756 if ((Oprnds.size()-FirstVariableOperand) & 1)
757 error("Invalid call instruction!"); // Must be pairs of type/value
759 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
761 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
764 Result = new CallInst(F, Params);
767 case Instruction::Invoke: {
768 if (Oprnds.size() < 3)
769 error("Invalid invoke instruction!");
770 Value *F = getValue(iType, Oprnds[0]);
772 // Check to make sure we have a pointer to function type
773 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
775 error("Invoke to non function pointer value!");
776 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
778 error("Invoke to non function pointer value!");
780 std::vector<Value *> Params;
781 BasicBlock *Normal, *Except;
783 if (!FTy->isVarArg()) {
784 Normal = getBasicBlock(Oprnds[1]);
785 Except = getBasicBlock(Oprnds[2]);
787 FunctionType::param_iterator It = FTy->param_begin();
788 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
789 if (It == FTy->param_end())
790 error("Invalid invoke instruction!");
791 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
793 if (It != FTy->param_end())
794 error("Invalid invoke instruction!");
796 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
798 Normal = getBasicBlock(Oprnds[0]);
799 Except = getBasicBlock(Oprnds[1]);
801 unsigned FirstVariableArgument = FTy->getNumParams()+2;
802 for (unsigned i = 2; i != FirstVariableArgument; ++i)
803 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
806 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
807 error("Invalid invoke instruction!");
809 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
810 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
813 Result = new InvokeInst(F, Normal, Except, Params);
816 case Instruction::Malloc:
817 if (Oprnds.size() > 2)
818 error("Invalid malloc instruction!");
819 if (!isa<PointerType>(InstTy))
820 error("Invalid malloc instruction!");
822 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
823 Oprnds.size() ? getValue(Type::UIntTyID,
827 case Instruction::Alloca:
828 if (Oprnds.size() > 2)
829 error("Invalid alloca instruction!");
830 if (!isa<PointerType>(InstTy))
831 error("Invalid alloca instruction!");
833 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
834 Oprnds.size() ? getValue(Type::UIntTyID,
837 case Instruction::Free:
838 if (!isa<PointerType>(InstTy))
839 error("Invalid free instruction!");
840 Result = new FreeInst(getValue(iType, Oprnds[0]));
842 case Instruction::GetElementPtr: {
843 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
844 error("Invalid getelementptr instruction!");
846 std::vector<Value*> Idx;
848 const Type *NextTy = InstTy;
849 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
850 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
852 error("Invalid getelementptr instruction!");
854 unsigned ValIdx = Oprnds[i];
856 if (!hasRestrictedGEPTypes) {
857 // Struct indices are always uints, sequential type indices can be any
858 // of the 32 or 64-bit integer types. The actual choice of type is
859 // encoded in the low two bits of the slot number.
860 if (isa<StructType>(TopTy))
861 IdxTy = Type::UIntTyID;
863 switch (ValIdx & 3) {
865 case 0: IdxTy = Type::UIntTyID; break;
866 case 1: IdxTy = Type::IntTyID; break;
867 case 2: IdxTy = Type::ULongTyID; break;
868 case 3: IdxTy = Type::LongTyID; break;
873 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
876 Idx.push_back(getValue(IdxTy, ValIdx));
878 // Convert ubyte struct indices into uint struct indices.
879 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
880 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
881 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
883 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
886 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
890 case 62: // volatile load
891 case Instruction::Load:
892 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
893 error("Invalid load instruction!");
894 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
897 case 63: // volatile store
898 case Instruction::Store: {
899 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
900 error("Invalid store instruction!");
902 Value *Ptr = getValue(iType, Oprnds[1]);
903 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
904 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
908 case Instruction::Unwind:
909 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
910 Result = new UnwindInst();
912 case Instruction::Unreachable:
913 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
914 Result = new UnreachableInst();
916 } // end switch(Opcode)
919 if (Result->getType() == InstTy)
922 TypeSlot = getTypeSlot(Result->getType());
924 insertValue(Result, TypeSlot, FunctionValues);
925 BB->getInstList().push_back(Result);
928 /// Get a particular numbered basic block, which might be a forward reference.
929 /// This works together with ParseBasicBlock to handle these forward references
930 /// in a clean manner. This function is used when constructing phi, br, switch,
931 /// and other instructions that reference basic blocks. Blocks are numbered
932 /// sequentially as they appear in the function.
933 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
934 // Make sure there is room in the table...
935 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
937 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
938 // has already created this block, or if the forward reference has already
940 if (ParsedBasicBlocks[ID])
941 return ParsedBasicBlocks[ID];
943 // Otherwise, the basic block has not yet been created. Do so and add it to
944 // the ParsedBasicBlocks list.
945 return ParsedBasicBlocks[ID] = new BasicBlock();
948 /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
949 /// This method reads in one of the basicblock packets. This method is not used
950 /// for bytecode files after LLVM 1.0
951 /// @returns The basic block constructed.
952 BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
953 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
957 if (ParsedBasicBlocks.size() == BlockNo)
958 ParsedBasicBlocks.push_back(BB = new BasicBlock());
959 else if (ParsedBasicBlocks[BlockNo] == 0)
960 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
962 BB = ParsedBasicBlocks[BlockNo];
964 std::vector<unsigned> Operands;
965 while (moreInBlock())
966 ParseInstruction(Operands, BB);
968 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
972 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
973 /// In post 1.0 bytecode files, we no longer emit basic block individually,
974 /// in order to avoid per-basic-block overhead.
975 /// @returns Rhe number of basic blocks encountered.
976 unsigned BytecodeReader::ParseInstructionList(Function* F) {
977 unsigned BlockNo = 0;
978 std::vector<unsigned> Args;
980 while (moreInBlock()) {
981 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
983 if (ParsedBasicBlocks.size() == BlockNo)
984 ParsedBasicBlocks.push_back(BB = new BasicBlock());
985 else if (ParsedBasicBlocks[BlockNo] == 0)
986 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
988 BB = ParsedBasicBlocks[BlockNo];
990 F->getBasicBlockList().push_back(BB);
992 // Read instructions into this basic block until we get to a terminator
993 while (moreInBlock() && !BB->getTerminator())
994 ParseInstruction(Args, BB);
996 if (!BB->getTerminator())
997 error("Non-terminated basic block found!");
999 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1005 /// Parse a symbol table. This works for both module level and function
1006 /// level symbol tables. For function level symbol tables, the CurrentFunction
1007 /// parameter must be non-zero and the ST parameter must correspond to
1008 /// CurrentFunction's symbol table. For Module level symbol tables, the
1009 /// CurrentFunction argument must be zero.
1010 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
1012 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1014 // Allow efficient basic block lookup by number.
1015 std::vector<BasicBlock*> BBMap;
1016 if (CurrentFunction)
1017 for (Function::iterator I = CurrentFunction->begin(),
1018 E = CurrentFunction->end(); I != E; ++I)
1021 /// In LLVM 1.3 we write types separately from values so
1022 /// The types are always first in the symbol table. This is
1023 /// because Type no longer derives from Value.
1024 if (!hasTypeDerivedFromValue) {
1025 // Symtab block header: [num entries]
1026 unsigned NumEntries = read_vbr_uint();
1027 for (unsigned i = 0; i < NumEntries; ++i) {
1028 // Symtab entry: [def slot #][name]
1029 unsigned slot = read_vbr_uint();
1030 std::string Name = read_str();
1031 const Type* T = getType(slot);
1032 ST->insert(Name, T);
1036 while (moreInBlock()) {
1037 // Symtab block header: [num entries][type id number]
1038 unsigned NumEntries = read_vbr_uint();
1040 bool isTypeType = read_typeid(Typ);
1041 const Type *Ty = getType(Typ);
1043 for (unsigned i = 0; i != NumEntries; ++i) {
1044 // Symtab entry: [def slot #][name]
1045 unsigned slot = read_vbr_uint();
1046 std::string Name = read_str();
1048 // if we're reading a pre 1.3 bytecode file and the type plane
1049 // is the "type type", handle it here
1051 const Type* T = getType(slot);
1053 error("Failed type look-up for name '" + Name + "'");
1054 ST->insert(Name, T);
1055 continue; // code below must be short circuited
1058 if (Typ == Type::LabelTyID) {
1059 if (slot < BBMap.size())
1062 V = getValue(Typ, slot, false); // Find mapping...
1065 error("Failed value look-up for name '" + Name + "'");
1066 V->setName(Name, ST);
1070 checkPastBlockEnd("Symbol Table");
1071 if (Handler) Handler->handleSymbolTableEnd();
1074 /// Read in the types portion of a compaction table.
1075 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1076 for (unsigned i = 0; i != NumEntries; ++i) {
1077 unsigned TypeSlot = 0;
1078 if (read_typeid(TypeSlot))
1079 error("Invalid type in compaction table: type type");
1080 const Type *Typ = getGlobalTableType(TypeSlot);
1081 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1082 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1086 /// Parse a compaction table.
1087 void BytecodeReader::ParseCompactionTable() {
1089 // Notify handler that we're beginning a compaction table.
1090 if (Handler) Handler->handleCompactionTableBegin();
1092 // In LLVM 1.3 Type no longer derives from Value. So,
1093 // we always write them first in the compaction table
1094 // because they can't occupy a "type plane" where the
1096 if (! hasTypeDerivedFromValue) {
1097 unsigned NumEntries = read_vbr_uint();
1098 ParseCompactionTypes(NumEntries);
1101 // Compaction tables live in separate blocks so we have to loop
1102 // until we've read the whole thing.
1103 while (moreInBlock()) {
1104 // Read the number of Value* entries in the compaction table
1105 unsigned NumEntries = read_vbr_uint();
1107 unsigned isTypeType = false;
1109 // Decode the type from value read in. Most compaction table
1110 // planes will have one or two entries in them. If that's the
1111 // case then the length is encoded in the bottom two bits and
1112 // the higher bits encode the type. This saves another VBR value.
1113 if ((NumEntries & 3) == 3) {
1114 // In this case, both low-order bits are set (value 3). This
1115 // is a signal that the typeid follows.
1117 isTypeType = read_typeid(Ty);
1119 // In this case, the low-order bits specify the number of entries
1120 // and the high order bits specify the type.
1121 Ty = NumEntries >> 2;
1122 isTypeType = sanitizeTypeId(Ty);
1126 // if we're reading a pre 1.3 bytecode file and the type plane
1127 // is the "type type", handle it here
1129 ParseCompactionTypes(NumEntries);
1131 // Make sure we have enough room for the plane.
1132 if (Ty >= CompactionValues.size())
1133 CompactionValues.resize(Ty+1);
1135 // Make sure the plane is empty or we have some kind of error.
1136 if (!CompactionValues[Ty].empty())
1137 error("Compaction table plane contains multiple entries!");
1139 // Notify handler about the plane.
1140 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1142 // Push the implicit zero.
1143 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1145 // Read in each of the entries, put them in the compaction table
1146 // and notify the handler that we have a new compaction table value.
1147 for (unsigned i = 0; i != NumEntries; ++i) {
1148 unsigned ValSlot = read_vbr_uint();
1149 Value *V = getGlobalTableValue(Ty, ValSlot);
1150 CompactionValues[Ty].push_back(V);
1151 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1155 // Notify handler that the compaction table is done.
1156 if (Handler) Handler->handleCompactionTableEnd();
1159 // Parse a single type. The typeid is read in first. If its a primitive type
1160 // then nothing else needs to be read, we know how to instantiate it. If its
1161 // a derived type, then additional data is read to fill out the type
1163 const Type *BytecodeReader::ParseType() {
1164 unsigned PrimType = 0;
1165 if (read_typeid(PrimType))
1166 error("Invalid type (type type) in type constants!");
1168 const Type *Result = 0;
1169 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1173 case Type::FunctionTyID: {
1174 const Type *RetType = readSanitizedType();
1176 unsigned NumParams = read_vbr_uint();
1178 std::vector<const Type*> Params;
1180 Params.push_back(readSanitizedType());
1182 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1183 if (isVarArg) Params.pop_back();
1185 Result = FunctionType::get(RetType, Params, isVarArg);
1188 case Type::ArrayTyID: {
1189 const Type *ElementType = readSanitizedType();
1190 unsigned NumElements = read_vbr_uint();
1191 Result = ArrayType::get(ElementType, NumElements);
1194 case Type::PackedTyID: {
1195 const Type *ElementType = readSanitizedType();
1196 unsigned NumElements = read_vbr_uint();
1197 Result = PackedType::get(ElementType, NumElements);
1200 case Type::StructTyID: {
1201 std::vector<const Type*> Elements;
1203 if (read_typeid(Typ))
1204 error("Invalid element type (type type) for structure!");
1206 while (Typ) { // List is terminated by void/0 typeid
1207 Elements.push_back(getType(Typ));
1208 if (read_typeid(Typ))
1209 error("Invalid element type (type type) for structure!");
1212 Result = StructType::get(Elements);
1215 case Type::PointerTyID: {
1216 Result = PointerType::get(readSanitizedType());
1220 case Type::OpaqueTyID: {
1221 Result = OpaqueType::get();
1226 error("Don't know how to deserialize primitive type " + utostr(PrimType));
1229 if (Handler) Handler->handleType(Result);
1233 // ParseTypes - We have to use this weird code to handle recursive
1234 // types. We know that recursive types will only reference the current slab of
1235 // values in the type plane, but they can forward reference types before they
1236 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1237 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1238 // this ugly problem, we pessimistically insert an opaque type for each type we
1239 // are about to read. This means that forward references will resolve to
1240 // something and when we reread the type later, we can replace the opaque type
1241 // with a new resolved concrete type.
1243 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1244 assert(Tab.size() == 0 && "should not have read type constants in before!");
1246 // Insert a bunch of opaque types to be resolved later...
1247 Tab.reserve(NumEntries);
1248 for (unsigned i = 0; i != NumEntries; ++i)
1249 Tab.push_back(OpaqueType::get());
1252 Handler->handleTypeList(NumEntries);
1254 // Loop through reading all of the types. Forward types will make use of the
1255 // opaque types just inserted.
1257 for (unsigned i = 0; i != NumEntries; ++i) {
1258 const Type* NewTy = ParseType();
1259 const Type* OldTy = Tab[i].get();
1261 error("Couldn't parse type!");
1263 // Don't directly push the new type on the Tab. Instead we want to replace
1264 // the opaque type we previously inserted with the new concrete value. This
1265 // approach helps with forward references to types. The refinement from the
1266 // abstract (opaque) type to the new type causes all uses of the abstract
1267 // type to use the concrete type (NewTy). This will also cause the opaque
1268 // type to be deleted.
1269 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1271 // This should have replaced the old opaque type with the new type in the
1272 // value table... or with a preexisting type that was already in the system.
1273 // Let's just make sure it did.
1274 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1278 /// Parse a single constant value
1279 Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
1280 // We must check for a ConstantExpr before switching by type because
1281 // a ConstantExpr can be of any type, and has no explicit value.
1283 // 0 if not expr; numArgs if is expr
1284 unsigned isExprNumArgs = read_vbr_uint();
1286 if (isExprNumArgs) {
1287 // 'undef' is encoded with 'exprnumargs' == 1.
1288 if (!hasNoUndefValue)
1289 if (--isExprNumArgs == 0)
1290 return UndefValue::get(getType(TypeID));
1292 // FIXME: Encoding of constant exprs could be much more compact!
1293 std::vector<Constant*> ArgVec;
1294 ArgVec.reserve(isExprNumArgs);
1295 unsigned Opcode = read_vbr_uint();
1297 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1298 if (hasNoUnreachableInst) Opcode++;
1300 // Read the slot number and types of each of the arguments
1301 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1302 unsigned ArgValSlot = read_vbr_uint();
1303 unsigned ArgTypeSlot = 0;
1304 if (read_typeid(ArgTypeSlot))
1305 error("Invalid argument type (type type) for constant value");
1307 // Get the arg value from its slot if it exists, otherwise a placeholder
1308 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1311 // Construct a ConstantExpr of the appropriate kind
1312 if (isExprNumArgs == 1) { // All one-operand expressions
1313 if (Opcode != Instruction::Cast)
1314 error("Only Cast instruction has one argument for ConstantExpr");
1316 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1317 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1319 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1320 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1322 if (hasRestrictedGEPTypes) {
1323 const Type *BaseTy = ArgVec[0]->getType();
1324 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1325 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1326 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1327 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1328 if (isa<StructType>(*GTI)) {
1329 if (IdxList[i]->getType() != Type::UByteTy)
1330 error("Invalid index for getelementptr!");
1331 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1335 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1336 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1338 } else if (Opcode == Instruction::Select) {
1339 if (ArgVec.size() != 3)
1340 error("Select instruction must have three arguments.");
1341 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1343 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1345 } else { // All other 2-operand expressions
1346 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1347 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1352 // Ok, not an ConstantExpr. We now know how to read the given type...
1353 const Type *Ty = getType(TypeID);
1354 switch (Ty->getTypeID()) {
1355 case Type::BoolTyID: {
1356 unsigned Val = read_vbr_uint();
1357 if (Val != 0 && Val != 1)
1358 error("Invalid boolean value read.");
1359 Constant* Result = ConstantBool::get(Val == 1);
1360 if (Handler) Handler->handleConstantValue(Result);
1364 case Type::UByteTyID: // Unsigned integer types...
1365 case Type::UShortTyID:
1366 case Type::UIntTyID: {
1367 unsigned Val = read_vbr_uint();
1368 if (!ConstantUInt::isValueValidForType(Ty, Val))
1369 error("Invalid unsigned byte/short/int read.");
1370 Constant* Result = ConstantUInt::get(Ty, Val);
1371 if (Handler) Handler->handleConstantValue(Result);
1375 case Type::ULongTyID: {
1376 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1377 if (Handler) Handler->handleConstantValue(Result);
1381 case Type::SByteTyID: // Signed integer types...
1382 case Type::ShortTyID:
1383 case Type::IntTyID: {
1384 case Type::LongTyID:
1385 int64_t Val = read_vbr_int64();
1386 if (!ConstantSInt::isValueValidForType(Ty, Val))
1387 error("Invalid signed byte/short/int/long read.");
1388 Constant* Result = ConstantSInt::get(Ty, Val);
1389 if (Handler) Handler->handleConstantValue(Result);
1393 case Type::FloatTyID: {
1396 Constant* Result = ConstantFP::get(Ty, Val);
1397 if (Handler) Handler->handleConstantValue(Result);
1401 case Type::DoubleTyID: {
1404 Constant* Result = ConstantFP::get(Ty, Val);
1405 if (Handler) Handler->handleConstantValue(Result);
1409 case Type::ArrayTyID: {
1410 const ArrayType *AT = cast<ArrayType>(Ty);
1411 unsigned NumElements = AT->getNumElements();
1412 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1413 std::vector<Constant*> Elements;
1414 Elements.reserve(NumElements);
1415 while (NumElements--) // Read all of the elements of the constant.
1416 Elements.push_back(getConstantValue(TypeSlot,
1418 Constant* Result = ConstantArray::get(AT, Elements);
1419 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1423 case Type::StructTyID: {
1424 const StructType *ST = cast<StructType>(Ty);
1426 std::vector<Constant *> Elements;
1427 Elements.reserve(ST->getNumElements());
1428 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1429 Elements.push_back(getConstantValue(ST->getElementType(i),
1432 Constant* Result = ConstantStruct::get(ST, Elements);
1433 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1437 case Type::PackedTyID: {
1438 const PackedType *PT = cast<PackedType>(Ty);
1439 unsigned NumElements = PT->getNumElements();
1440 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1441 std::vector<Constant*> Elements;
1442 Elements.reserve(NumElements);
1443 while (NumElements--) // Read all of the elements of the constant.
1444 Elements.push_back(getConstantValue(TypeSlot,
1446 Constant* Result = ConstantPacked::get(PT, Elements);
1447 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1451 case Type::PointerTyID: { // ConstantPointerRef value...
1452 const PointerType *PT = cast<PointerType>(Ty);
1453 unsigned Slot = read_vbr_uint();
1455 // Check to see if we have already read this global variable...
1456 Value *Val = getValue(TypeID, Slot, false);
1458 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1459 if (!GV) error("GlobalValue not in ValueTable!");
1460 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1463 error("Forward references are not allowed here.");
1468 error("Don't know how to deserialize constant value of type '" +
1469 Ty->getDescription());
1475 /// Resolve references for constants. This function resolves the forward
1476 /// referenced constants in the ConstantFwdRefs map. It uses the
1477 /// replaceAllUsesWith method of Value class to substitute the placeholder
1478 /// instance with the actual instance.
1479 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
1480 ConstantRefsType::iterator I =
1481 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1482 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
1484 Value *PH = I->second; // Get the placeholder...
1485 PH->replaceAllUsesWith(NewV);
1486 delete PH; // Delete the old placeholder
1487 ConstantFwdRefs.erase(I); // Remove the map entry for it
1490 /// Parse the constant strings section.
1491 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1492 for (; NumEntries; --NumEntries) {
1494 if (read_typeid(Typ))
1495 error("Invalid type (type type) for string constant");
1496 const Type *Ty = getType(Typ);
1497 if (!isa<ArrayType>(Ty))
1498 error("String constant data invalid!");
1500 const ArrayType *ATy = cast<ArrayType>(Ty);
1501 if (ATy->getElementType() != Type::SByteTy &&
1502 ATy->getElementType() != Type::UByteTy)
1503 error("String constant data invalid!");
1505 // Read character data. The type tells us how long the string is.
1506 char Data[ATy->getNumElements()];
1507 read_data(Data, Data+ATy->getNumElements());
1509 std::vector<Constant*> Elements(ATy->getNumElements());
1510 if (ATy->getElementType() == Type::SByteTy)
1511 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1512 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1514 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1515 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
1517 // Create the constant, inserting it as needed.
1518 Constant *C = ConstantArray::get(ATy, Elements);
1519 unsigned Slot = insertValue(C, Typ, Tab);
1520 ResolveReferencesToConstant(C, Slot);
1521 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1525 /// Parse the constant pool.
1526 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1527 TypeListTy &TypeTab,
1529 if (Handler) Handler->handleGlobalConstantsBegin();
1531 /// In LLVM 1.3 Type does not derive from Value so the types
1532 /// do not occupy a plane. Consequently, we read the types
1533 /// first in the constant pool.
1534 if (isFunction && !hasTypeDerivedFromValue) {
1535 unsigned NumEntries = read_vbr_uint();
1536 ParseTypes(TypeTab, NumEntries);
1539 while (moreInBlock()) {
1540 unsigned NumEntries = read_vbr_uint();
1542 bool isTypeType = read_typeid(Typ);
1544 /// In LLVM 1.2 and before, Types were written to the
1545 /// bytecode file in the "Type Type" plane (#12).
1546 /// In 1.3 plane 12 is now the label plane. Handle this here.
1548 ParseTypes(TypeTab, NumEntries);
1549 } else if (Typ == Type::VoidTyID) {
1550 /// Use of Type::VoidTyID is a misnomer. It actually means
1551 /// that the following plane is constant strings
1552 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1553 ParseStringConstants(NumEntries, Tab);
1555 for (unsigned i = 0; i < NumEntries; ++i) {
1556 Constant *C = ParseConstantValue(Typ);
1557 assert(C && "ParseConstantValue returned NULL!");
1558 unsigned Slot = insertValue(C, Typ, Tab);
1560 // If we are reading a function constant table, make sure that we adjust
1561 // the slot number to be the real global constant number.
1563 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1565 Slot += ModuleValues[Typ]->size();
1566 ResolveReferencesToConstant(C, Slot);
1570 checkPastBlockEnd("Constant Pool");
1571 if (Handler) Handler->handleGlobalConstantsEnd();
1574 /// Parse the contents of a function. Note that this function can be
1575 /// called lazily by materializeFunction
1576 /// @see materializeFunction
1577 void BytecodeReader::ParseFunctionBody(Function* F) {
1579 unsigned FuncSize = BlockEnd - At;
1580 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1582 unsigned LinkageType = read_vbr_uint();
1583 switch (LinkageType) {
1584 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1585 case 1: Linkage = GlobalValue::WeakLinkage; break;
1586 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1587 case 3: Linkage = GlobalValue::InternalLinkage; break;
1588 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1590 error("Invalid linkage type for Function.");
1591 Linkage = GlobalValue::InternalLinkage;
1595 F->setLinkage(Linkage);
1596 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1598 // Keep track of how many basic blocks we have read in...
1599 unsigned BlockNum = 0;
1600 bool InsertedArguments = false;
1602 BufPtr MyEnd = BlockEnd;
1603 while (At < MyEnd) {
1604 unsigned Type, Size;
1606 read_block(Type, Size);
1609 case BytecodeFormat::ConstantPoolBlockID:
1610 if (!InsertedArguments) {
1611 // Insert arguments into the value table before we parse the first basic
1612 // block in the function, but after we potentially read in the
1613 // compaction table.
1615 InsertedArguments = true;
1618 ParseConstantPool(FunctionValues, FunctionTypes, true);
1621 case BytecodeFormat::CompactionTableBlockID:
1622 ParseCompactionTable();
1625 case BytecodeFormat::BasicBlock: {
1626 if (!InsertedArguments) {
1627 // Insert arguments into the value table before we parse the first basic
1628 // block in the function, but after we potentially read in the
1629 // compaction table.
1631 InsertedArguments = true;
1634 BasicBlock *BB = ParseBasicBlock(BlockNum++);
1635 F->getBasicBlockList().push_back(BB);
1639 case BytecodeFormat::InstructionListBlockID: {
1640 // Insert arguments into the value table before we parse the instruction
1641 // list for the function, but after we potentially read in the compaction
1643 if (!InsertedArguments) {
1645 InsertedArguments = true;
1649 error("Already parsed basic blocks!");
1650 BlockNum = ParseInstructionList(F);
1654 case BytecodeFormat::SymbolTableBlockID:
1655 ParseSymbolTable(F, &F->getSymbolTable());
1661 error("Wrapped around reading bytecode.");
1666 // Malformed bc file if read past end of block.
1670 // Make sure there were no references to non-existant basic blocks.
1671 if (BlockNum != ParsedBasicBlocks.size())
1672 error("Illegal basic block operand reference");
1674 ParsedBasicBlocks.clear();
1676 // Resolve forward references. Replace any uses of a forward reference value
1677 // with the real value.
1679 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1680 // number of operands. PHI nodes often have forward references, and can also
1681 // often have a very large number of operands.
1683 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1684 // should be simplified back to using it!
1686 std::map<Value*, Value*> ForwardRefMapping;
1687 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1688 I = ForwardReferences.begin(), E = ForwardReferences.end();
1690 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1693 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1694 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1695 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1696 if (Value* V = I->getOperand(i))
1697 if (Argument *A = dyn_cast<Argument>(V)) {
1698 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1699 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1702 while (!ForwardReferences.empty()) {
1703 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1704 ForwardReferences.begin();
1705 Value *PlaceHolder = I->second;
1706 ForwardReferences.erase(I);
1708 // Now that all the uses are gone, delete the placeholder...
1709 // If we couldn't find a def (error case), then leak a little
1710 // memory, because otherwise we can't remove all uses!
1714 // Clear out function-level types...
1715 FunctionTypes.clear();
1716 CompactionTypes.clear();
1717 CompactionValues.clear();
1718 freeTable(FunctionValues);
1720 if (Handler) Handler->handleFunctionEnd(F);
1723 /// This function parses LLVM functions lazily. It obtains the type of the
1724 /// function and records where the body of the function is in the bytecode
1725 /// buffer. The caller can then use the ParseNextFunction and
1726 /// ParseAllFunctionBodies to get handler events for the functions.
1727 void BytecodeReader::ParseFunctionLazily() {
1728 if (FunctionSignatureList.empty())
1729 error("FunctionSignatureList empty!");
1731 Function *Func = FunctionSignatureList.back();
1732 FunctionSignatureList.pop_back();
1734 // Save the information for future reading of the function
1735 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1737 // Pretend we've `parsed' this function
1741 /// The ParserFunction method lazily parses one function. Use this method to
1742 /// casue the parser to parse a specific function in the module. Note that
1743 /// this will remove the function from what is to be included by
1744 /// ParseAllFunctionBodies.
1745 /// @see ParseAllFunctionBodies
1746 /// @see ParseBytecode
1747 void BytecodeReader::ParseFunction(Function* Func) {
1748 // Find {start, end} pointers and slot in the map. If not there, we're done.
1749 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1751 // Make sure we found it
1752 if (Fi == LazyFunctionLoadMap.end()) {
1753 error("Unrecognized function of type " + Func->getType()->getDescription());
1757 BlockStart = At = Fi->second.Buf;
1758 BlockEnd = Fi->second.EndBuf;
1759 assert(Fi->first == Func && "Found wrong function?");
1761 LazyFunctionLoadMap.erase(Fi);
1763 this->ParseFunctionBody(Func);
1766 /// The ParseAllFunctionBodies method parses through all the previously
1767 /// unparsed functions in the bytecode file. If you want to completely parse
1768 /// a bytecode file, this method should be called after Parsebytecode because
1769 /// Parsebytecode only records the locations in the bytecode file of where
1770 /// the function definitions are located. This function uses that information
1771 /// to materialize the functions.
1772 /// @see ParseBytecode
1773 void BytecodeReader::ParseAllFunctionBodies() {
1774 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1775 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1778 Function* Func = Fi->first;
1779 BlockStart = At = Fi->second.Buf;
1780 BlockEnd = Fi->second.EndBuf;
1781 this->ParseFunctionBody(Func);
1786 /// Parse the global type list
1787 void BytecodeReader::ParseGlobalTypes() {
1788 // Read the number of types
1789 unsigned NumEntries = read_vbr_uint();
1791 // Ignore the type plane identifier for types if the bc file is pre 1.3
1792 if (hasTypeDerivedFromValue)
1795 ParseTypes(ModuleTypes, NumEntries);
1798 /// Parse the Global info (types, global vars, constants)
1799 void BytecodeReader::ParseModuleGlobalInfo() {
1801 if (Handler) Handler->handleModuleGlobalsBegin();
1803 // Read global variables...
1804 unsigned VarType = read_vbr_uint();
1805 while (VarType != Type::VoidTyID) { // List is terminated by Void
1806 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1807 // Linkage, bit4+ = slot#
1808 unsigned SlotNo = VarType >> 5;
1809 if (sanitizeTypeId(SlotNo))
1810 error("Invalid type (type type) for global var!");
1811 unsigned LinkageID = (VarType >> 2) & 7;
1812 bool isConstant = VarType & 1;
1813 bool hasInitializer = VarType & 2;
1814 GlobalValue::LinkageTypes Linkage;
1816 switch (LinkageID) {
1817 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1818 case 1: Linkage = GlobalValue::WeakLinkage; break;
1819 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1820 case 3: Linkage = GlobalValue::InternalLinkage; break;
1821 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1823 error("Unknown linkage type: " + utostr(LinkageID));
1824 Linkage = GlobalValue::InternalLinkage;
1828 const Type *Ty = getType(SlotNo);
1830 error("Global has no type! SlotNo=" + utostr(SlotNo));
1833 if (!isa<PointerType>(Ty)) {
1834 error("Global not a pointer type! Ty= " + Ty->getDescription());
1837 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1839 // Create the global variable...
1840 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1842 insertValue(GV, SlotNo, ModuleValues);
1844 unsigned initSlot = 0;
1845 if (hasInitializer) {
1846 initSlot = read_vbr_uint();
1847 GlobalInits.push_back(std::make_pair(GV, initSlot));
1850 // Notify handler about the global value.
1852 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1855 VarType = read_vbr_uint();
1858 // Read the function objects for all of the functions that are coming
1859 unsigned FnSignature = read_vbr_uint();
1861 if (hasNoFlagsForFunctions)
1862 FnSignature = (FnSignature << 5) + 1;
1864 // List is terminated by VoidTy.
1865 while ((FnSignature >> 5) != Type::VoidTyID) {
1866 const Type *Ty = getType(FnSignature >> 5);
1867 if (!isa<PointerType>(Ty) ||
1868 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1869 error("Function not a pointer to function type! Ty = " +
1870 Ty->getDescription());
1873 // We create functions by passing the underlying FunctionType to create...
1874 const FunctionType* FTy =
1875 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1878 // Insert the place hodler
1879 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
1881 insertValue(Func, FnSignature >> 5, ModuleValues);
1883 // Flags are not used yet.
1884 //unsigned Flags = FnSignature & 31;
1886 // Save this for later so we know type of lazily instantiated functions
1887 FunctionSignatureList.push_back(Func);
1889 if (Handler) Handler->handleFunctionDeclaration(Func);
1891 // Get the next function signature.
1892 FnSignature = read_vbr_uint();
1893 if (hasNoFlagsForFunctions)
1894 FnSignature = (FnSignature << 5) + 1;
1897 // Now that the function signature list is set up, reverse it so that we can
1898 // remove elements efficiently from the back of the vector.
1899 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1901 // If this bytecode format has dependent library information in it ..
1902 if (!hasNoDependentLibraries) {
1903 // Read in the number of dependent library items that follow
1904 unsigned num_dep_libs = read_vbr_uint();
1905 std::string dep_lib;
1906 while( num_dep_libs-- ) {
1907 dep_lib = read_str();
1908 TheModule->addLibrary(dep_lib);
1910 Handler->handleDependentLibrary(dep_lib);
1914 // Read target triple and place into the module
1915 std::string triple = read_str();
1916 TheModule->setTargetTriple(triple);
1918 Handler->handleTargetTriple(triple);
1921 if (hasInconsistentModuleGlobalInfo)
1924 // This is for future proofing... in the future extra fields may be added that
1925 // we don't understand, so we transparently ignore them.
1929 if (Handler) Handler->handleModuleGlobalsEnd();
1932 /// Parse the version information and decode it by setting flags on the
1933 /// Reader that enable backward compatibility of the reader.
1934 void BytecodeReader::ParseVersionInfo() {
1935 unsigned Version = read_vbr_uint();
1937 // Unpack version number: low four bits are for flags, top bits = version
1938 Module::Endianness Endianness;
1939 Module::PointerSize PointerSize;
1940 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1941 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1943 bool hasNoEndianness = Version & 4;
1944 bool hasNoPointerSize = Version & 8;
1946 RevisionNum = Version >> 4;
1948 // Default values for the current bytecode version
1949 hasInconsistentModuleGlobalInfo = false;
1950 hasExplicitPrimitiveZeros = false;
1951 hasRestrictedGEPTypes = false;
1952 hasTypeDerivedFromValue = false;
1953 hasLongBlockHeaders = false;
1954 has32BitTypes = false;
1955 hasNoDependentLibraries = false;
1956 hasAlignment = false;
1957 hasInconsistentBBSlotNums = false;
1958 hasVBRByteTypes = false;
1959 hasUnnecessaryModuleBlockId = false;
1960 hasNoUndefValue = false;
1961 hasNoFlagsForFunctions = false;
1962 hasNoUnreachableInst = false;
1964 switch (RevisionNum) {
1965 case 0: // LLVM 1.0, 1.1 (Released)
1966 // Base LLVM 1.0 bytecode format.
1967 hasInconsistentModuleGlobalInfo = true;
1968 hasExplicitPrimitiveZeros = true;
1972 case 1: // LLVM 1.2 (Released)
1973 // LLVM 1.2 added explicit support for emitting strings efficiently.
1975 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1976 // included the size for the alignment at the end, where the rest of the
1979 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1980 // structures and longs for sequential types.
1981 hasRestrictedGEPTypes = true;
1983 // LLVM 1.2 and before had the Type class derive from Value class. This
1984 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1985 // written differently because Types can no longer be part of the
1986 // type planes for Values.
1987 hasTypeDerivedFromValue = true;
1991 case 2: // 1.2.5 (Not Released)
1993 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1994 // especially for small files where the 8 bytes per block is a large
1995 // fraction of the total block size. In LLVM 1.3, the block type and length
1996 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
1997 // 5 bits for block type.
1998 hasLongBlockHeaders = true;
2000 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
2001 // this has been reduced to vbr_uint24. It shouldn't make much difference
2002 // since we haven't run into a module with > 24 million types, but for
2003 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2004 // in various places and to ensure consistency.
2005 has32BitTypes = true;
2007 // LLVM 1.2 and earlier did not provide a target triple nor a list of
2008 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2009 // features, for use in future versions of LLVM.
2010 hasNoDependentLibraries = true;
2014 case 3: // LLVM 1.3 (Released)
2015 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2016 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2017 // of GEP references to a constant array), this can increase the file size
2018 // by 30% or more. In version 1.4 alignment is done away with completely.
2019 hasAlignment = true;
2023 case 4: // 1.3.1 (Not Released)
2024 // In version 4, we did not support the 'undef' constant.
2025 hasNoUndefValue = true;
2027 // In version 4 and above, we did not include space for flags for functions
2028 // in the module info block.
2029 hasNoFlagsForFunctions = true;
2031 // In version 4 and above, we did not include the 'unreachable' instruction
2032 // in the opcode numbering in the bytecode file.
2033 hasNoUnreachableInst = true;
2038 case 5: // 1.x.x (Not Released)
2040 // FIXME: NONE of this is implemented yet!
2042 // In version 5, basic blocks have a minimum index of 0 whereas all the
2043 // other primitives have a minimum index of 1 (because 0 is the "null"
2044 // value. In version 5, we made this consistent.
2045 hasInconsistentBBSlotNums = true;
2047 // In version 5, the types SByte and UByte were encoded as vbr_uint so that
2048 // signed values > 63 and unsigned values >127 would be encoded as two
2049 // bytes. In version 5, they are encoded directly in a single byte.
2050 hasVBRByteTypes = true;
2052 // In version 5, modules begin with a "Module Block" which encodes a 4-byte
2053 // integer value 0x01 to identify the module block. This is unnecessary and
2054 // removed in version 5.
2055 hasUnnecessaryModuleBlockId = true;
2058 error("Unknown bytecode version number: " + itostr(RevisionNum));
2061 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2062 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2064 TheModule->setEndianness(Endianness);
2065 TheModule->setPointerSize(PointerSize);
2067 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2070 /// Parse a whole module.
2071 void BytecodeReader::ParseModule() {
2072 unsigned Type, Size;
2074 FunctionSignatureList.clear(); // Just in case...
2076 // Read into instance variables...
2080 bool SeenModuleGlobalInfo = false;
2081 bool SeenGlobalTypePlane = false;
2082 BufPtr MyEnd = BlockEnd;
2083 while (At < MyEnd) {
2085 read_block(Type, Size);
2089 case BytecodeFormat::GlobalTypePlaneBlockID:
2090 if (SeenGlobalTypePlane)
2091 error("Two GlobalTypePlane Blocks Encountered!");
2095 SeenGlobalTypePlane = true;
2098 case BytecodeFormat::ModuleGlobalInfoBlockID:
2099 if (SeenModuleGlobalInfo)
2100 error("Two ModuleGlobalInfo Blocks Encountered!");
2101 ParseModuleGlobalInfo();
2102 SeenModuleGlobalInfo = true;
2105 case BytecodeFormat::ConstantPoolBlockID:
2106 ParseConstantPool(ModuleValues, ModuleTypes,false);
2109 case BytecodeFormat::FunctionBlockID:
2110 ParseFunctionLazily();
2113 case BytecodeFormat::SymbolTableBlockID:
2114 ParseSymbolTable(0, &TheModule->getSymbolTable());
2120 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2128 // After the module constant pool has been read, we can safely initialize
2129 // global variables...
2130 while (!GlobalInits.empty()) {
2131 GlobalVariable *GV = GlobalInits.back().first;
2132 unsigned Slot = GlobalInits.back().second;
2133 GlobalInits.pop_back();
2135 // Look up the initializer value...
2136 // FIXME: Preserve this type ID!
2138 const llvm::PointerType* GVType = GV->getType();
2139 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2140 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2141 if (GV->hasInitializer())
2142 error("Global *already* has an initializer?!");
2143 if (Handler) Handler->handleGlobalInitializer(GV,CV);
2144 GV->setInitializer(CV);
2146 error("Cannot find initializer value.");
2149 /// Make sure we pulled them all out. If we didn't then there's a declaration
2150 /// but a missing body. That's not allowed.
2151 if (!FunctionSignatureList.empty())
2152 error("Function declared, but bytecode stream ended before definition");
2155 /// This function completely parses a bytecode buffer given by the \p Buf
2156 /// and \p Length parameters.
2157 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2158 const std::string &ModuleID) {
2161 At = MemStart = BlockStart = Buf;
2162 MemEnd = BlockEnd = Buf + Length;
2164 // Create the module
2165 TheModule = new Module(ModuleID);
2167 if (Handler) Handler->handleStart(TheModule, Length);
2169 // Read and check signature...
2170 unsigned Sig = read_uint();
2171 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2172 error("Invalid bytecode signature: " + utostr(Sig));
2175 // Tell the handler we're starting a module
2176 if (Handler) Handler->handleModuleBegin(ModuleID);
2178 // Get the module block and size and verify. This is handled specially
2179 // because the module block/size is always written in long format. Other
2180 // blocks are written in short format so the read_block method is used.
2181 unsigned Type, Size;
2184 if (Type != BytecodeFormat::ModuleBlockID) {
2185 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2189 // It looks like the darwin ranlib program is broken, and adds trailing
2190 // garbage to the end of some bytecode files. This hack allows the bc
2191 // reader to ignore trailing garbage on bytecode files.
2192 if (At + Size < MemEnd)
2193 MemEnd = BlockEnd = At+Size;
2195 if (At + Size != MemEnd)
2196 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2197 + ", Size:" + utostr(Size));
2199 // Parse the module contents
2200 this->ParseModule();
2202 // Check for missing functions
2204 error("Function expected, but bytecode stream ended!");
2206 // Tell the handler we're done with the module
2208 Handler->handleModuleEnd(ModuleID);
2210 // Tell the handler we're finished the parse
2211 if (Handler) Handler->handleFinish();
2213 } catch (std::string& errstr) {
2214 if (Handler) Handler->handleError(errstr);
2220 std::string msg("Unknown Exception Occurred");
2221 if (Handler) Handler->handleError(msg);
2229 //===----------------------------------------------------------------------===//
2230 //=== Default Implementations of Handler Methods
2231 //===----------------------------------------------------------------------===//
2233 BytecodeHandler::~BytecodeHandler() {}