1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/OperandTraits.h"
30 void BitcodeReader::FreeState() {
34 std::vector<PATypeHolder>().swap(TypeList);
38 std::vector<AttrListPtr>().swap(MAttributes);
39 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
45 //===----------------------------------------------------------------------===//
46 // Helper functions to implement forward reference resolution, etc.
47 //===----------------------------------------------------------------------===//
49 /// ConvertToString - Convert a string from a record into an std::string, return
51 template<typename StrTy>
52 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
54 if (Idx > Record.size())
57 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
62 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
64 default: // Map unknown/new linkages to external
65 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakAnyLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceAnyLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
73 case 8: return GlobalValue::CommonLinkage;
74 case 9: return GlobalValue::PrivateLinkage;
75 case 10: return GlobalValue::WeakODRLinkage;
76 case 11: return GlobalValue::LinkOnceODRLinkage;
77 case 12: return GlobalValue::AvailableExternallyLinkage;
78 case 13: return GlobalValue::LinkerPrivateLinkage;
79 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
80 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
84 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
86 default: // Map unknown visibilities to default.
87 case 0: return GlobalValue::DefaultVisibility;
88 case 1: return GlobalValue::HiddenVisibility;
89 case 2: return GlobalValue::ProtectedVisibility;
93 static int GetDecodedCastOpcode(unsigned Val) {
96 case bitc::CAST_TRUNC : return Instruction::Trunc;
97 case bitc::CAST_ZEXT : return Instruction::ZExt;
98 case bitc::CAST_SEXT : return Instruction::SExt;
99 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
100 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
101 case bitc::CAST_UITOFP : return Instruction::UIToFP;
102 case bitc::CAST_SITOFP : return Instruction::SIToFP;
103 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104 case bitc::CAST_FPEXT : return Instruction::FPExt;
105 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107 case bitc::CAST_BITCAST : return Instruction::BitCast;
110 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
113 case bitc::BINOP_ADD:
114 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
115 case bitc::BINOP_SUB:
116 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
117 case bitc::BINOP_MUL:
118 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
119 case bitc::BINOP_UDIV: return Instruction::UDiv;
120 case bitc::BINOP_SDIV:
121 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
122 case bitc::BINOP_UREM: return Instruction::URem;
123 case bitc::BINOP_SREM:
124 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
125 case bitc::BINOP_SHL: return Instruction::Shl;
126 case bitc::BINOP_LSHR: return Instruction::LShr;
127 case bitc::BINOP_ASHR: return Instruction::AShr;
128 case bitc::BINOP_AND: return Instruction::And;
129 case bitc::BINOP_OR: return Instruction::Or;
130 case bitc::BINOP_XOR: return Instruction::Xor;
136 /// @brief A class for maintaining the slot number definition
137 /// as a placeholder for the actual definition for forward constants defs.
138 class ConstantPlaceHolder : public ConstantExpr {
139 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
141 // allocate space for exactly one operand
142 void *operator new(size_t s) {
143 return User::operator new(s, 1);
145 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
146 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
147 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
150 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
151 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
152 static bool classof(const Value *V) {
153 return isa<ConstantExpr>(V) &&
154 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
158 /// Provide fast operand accessors
159 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
163 // FIXME: can we inherit this from ConstantExpr?
165 struct OperandTraits<ConstantPlaceHolder> :
166 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
171 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
180 WeakVH &OldV = ValuePtrs[Idx];
186 // Handle constants and non-constants (e.g. instrs) differently for
188 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
189 ResolveConstants.push_back(std::make_pair(PHC, Idx));
192 // If there was a forward reference to this value, replace it.
193 Value *PrevVal = OldV;
194 OldV->replaceAllUsesWith(V);
200 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
205 if (Value *V = ValuePtrs[Idx]) {
206 assert(Ty == V->getType() && "Type mismatch in constant table!");
207 return cast<Constant>(V);
210 // Create and return a placeholder, which will later be RAUW'd.
211 Constant *C = new ConstantPlaceHolder(Ty, Context);
216 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
220 if (Value *V = ValuePtrs[Idx]) {
221 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
225 // No type specified, must be invalid reference.
226 if (Ty == 0) return 0;
228 // Create and return a placeholder, which will later be RAUW'd.
229 Value *V = new Argument(Ty);
234 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
235 /// resolves any forward references. The idea behind this is that we sometimes
236 /// get constants (such as large arrays) which reference *many* forward ref
237 /// constants. Replacing each of these causes a lot of thrashing when
238 /// building/reuniquing the constant. Instead of doing this, we look at all the
239 /// uses and rewrite all the place holders at once for any constant that uses
241 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
242 // Sort the values by-pointer so that they are efficient to look up with a
244 std::sort(ResolveConstants.begin(), ResolveConstants.end());
246 SmallVector<Constant*, 64> NewOps;
248 while (!ResolveConstants.empty()) {
249 Value *RealVal = operator[](ResolveConstants.back().second);
250 Constant *Placeholder = ResolveConstants.back().first;
251 ResolveConstants.pop_back();
253 // Loop over all users of the placeholder, updating them to reference the
254 // new value. If they reference more than one placeholder, update them all
256 while (!Placeholder->use_empty()) {
257 Value::use_iterator UI = Placeholder->use_begin();
260 // If the using object isn't uniqued, just update the operands. This
261 // handles instructions and initializers for global variables.
262 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
263 UI.getUse().set(RealVal);
267 // Otherwise, we have a constant that uses the placeholder. Replace that
268 // constant with a new constant that has *all* placeholder uses updated.
269 Constant *UserC = cast<Constant>(U);
270 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
273 if (!isa<ConstantPlaceHolder>(*I)) {
274 // Not a placeholder reference.
276 } else if (*I == Placeholder) {
277 // Common case is that it just references this one placeholder.
280 // Otherwise, look up the placeholder in ResolveConstants.
281 ResolveConstantsTy::iterator It =
282 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
283 std::pair<Constant*, unsigned>(cast<Constant>(*I),
285 assert(It != ResolveConstants.end() && It->first == *I);
286 NewOp = operator[](It->second);
289 NewOps.push_back(cast<Constant>(NewOp));
292 // Make the new constant.
294 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
295 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
296 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
297 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
298 } else if (isa<ConstantVector>(UserC)) {
299 NewC = ConstantVector::get(NewOps);
301 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
302 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
305 UserC->replaceAllUsesWith(NewC);
306 UserC->destroyConstant();
310 // Update all ValueHandles, they should be the only users at this point.
311 Placeholder->replaceAllUsesWith(RealVal);
316 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
325 WeakVH &OldV = MDValuePtrs[Idx];
331 // If there was a forward reference to this value, replace it.
332 MDNode *PrevVal = cast<MDNode>(OldV);
333 OldV->replaceAllUsesWith(V);
334 MDNode::deleteTemporary(PrevVal);
335 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
337 MDValuePtrs[Idx] = V;
340 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
344 if (Value *V = MDValuePtrs[Idx]) {
345 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
349 // Create and return a placeholder, which will later be RAUW'd.
350 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
351 MDValuePtrs[Idx] = V;
355 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
356 // If the TypeID is in range, return it.
357 if (ID < TypeList.size())
358 return TypeList[ID].get();
359 if (!isTypeTable) return 0;
361 // The type table allows forward references. Push as many Opaque types as
362 // needed to get up to ID.
363 while (TypeList.size() <= ID)
364 TypeList.push_back(OpaqueType::get(Context));
365 return TypeList.back().get();
368 //===----------------------------------------------------------------------===//
369 // Functions for parsing blocks from the bitcode file
370 //===----------------------------------------------------------------------===//
372 bool BitcodeReader::ParseAttributeBlock() {
373 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
374 return Error("Malformed block record");
376 if (!MAttributes.empty())
377 return Error("Multiple PARAMATTR blocks found!");
379 SmallVector<uint64_t, 64> Record;
381 SmallVector<AttributeWithIndex, 8> Attrs;
383 // Read all the records.
385 unsigned Code = Stream.ReadCode();
386 if (Code == bitc::END_BLOCK) {
387 if (Stream.ReadBlockEnd())
388 return Error("Error at end of PARAMATTR block");
392 if (Code == bitc::ENTER_SUBBLOCK) {
393 // No known subblocks, always skip them.
394 Stream.ReadSubBlockID();
395 if (Stream.SkipBlock())
396 return Error("Malformed block record");
400 if (Code == bitc::DEFINE_ABBREV) {
401 Stream.ReadAbbrevRecord();
407 switch (Stream.ReadRecord(Code, Record)) {
408 default: // Default behavior: ignore.
410 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
411 if (Record.size() & 1)
412 return Error("Invalid ENTRY record");
414 // FIXME : Remove this autoupgrade code in LLVM 3.0.
415 // If Function attributes are using index 0 then transfer them
416 // to index ~0. Index 0 is used for return value attributes but used to be
417 // used for function attributes.
418 Attributes RetAttribute = Attribute::None;
419 Attributes FnAttribute = Attribute::None;
420 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
421 // FIXME: remove in LLVM 3.0
422 // The alignment is stored as a 16-bit raw value from bits 31--16.
423 // We shift the bits above 31 down by 11 bits.
425 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
426 if (Alignment && !isPowerOf2_32(Alignment))
427 return Error("Alignment is not a power of two.");
429 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
431 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
432 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
433 Record[i+1] = ReconstitutedAttr;
436 RetAttribute = Record[i+1];
437 else if (Record[i] == ~0U)
438 FnAttribute = Record[i+1];
441 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
442 Attribute::ReadOnly|Attribute::ReadNone);
444 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
445 (RetAttribute & OldRetAttrs) != 0) {
446 if (FnAttribute == Attribute::None) { // add a slot so they get added.
447 Record.push_back(~0U);
451 FnAttribute |= RetAttribute & OldRetAttrs;
452 RetAttribute &= ~OldRetAttrs;
455 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
456 if (Record[i] == 0) {
457 if (RetAttribute != Attribute::None)
458 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
459 } else if (Record[i] == ~0U) {
460 if (FnAttribute != Attribute::None)
461 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
462 } else if (Record[i+1] != Attribute::None)
463 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
466 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
475 bool BitcodeReader::ParseTypeTable() {
476 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
477 return Error("Malformed block record");
479 if (!TypeList.empty())
480 return Error("Multiple TYPE_BLOCKs found!");
482 SmallVector<uint64_t, 64> Record;
483 unsigned NumRecords = 0;
485 // Read all the records for this type table.
487 unsigned Code = Stream.ReadCode();
488 if (Code == bitc::END_BLOCK) {
489 if (NumRecords != TypeList.size())
490 return Error("Invalid type forward reference in TYPE_BLOCK");
491 if (Stream.ReadBlockEnd())
492 return Error("Error at end of type table block");
496 if (Code == bitc::ENTER_SUBBLOCK) {
497 // No known subblocks, always skip them.
498 Stream.ReadSubBlockID();
499 if (Stream.SkipBlock())
500 return Error("Malformed block record");
504 if (Code == bitc::DEFINE_ABBREV) {
505 Stream.ReadAbbrevRecord();
511 const Type *ResultTy = 0;
512 switch (Stream.ReadRecord(Code, Record)) {
513 default: // Default behavior: unknown type.
516 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
517 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
518 // type list. This allows us to reserve space.
519 if (Record.size() < 1)
520 return Error("Invalid TYPE_CODE_NUMENTRY record");
521 TypeList.reserve(Record[0]);
523 case bitc::TYPE_CODE_VOID: // VOID
524 ResultTy = Type::getVoidTy(Context);
526 case bitc::TYPE_CODE_FLOAT: // FLOAT
527 ResultTy = Type::getFloatTy(Context);
529 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
530 ResultTy = Type::getDoubleTy(Context);
532 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
533 ResultTy = Type::getX86_FP80Ty(Context);
535 case bitc::TYPE_CODE_FP128: // FP128
536 ResultTy = Type::getFP128Ty(Context);
538 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
539 ResultTy = Type::getPPC_FP128Ty(Context);
541 case bitc::TYPE_CODE_LABEL: // LABEL
542 ResultTy = Type::getLabelTy(Context);
544 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
547 case bitc::TYPE_CODE_METADATA: // METADATA
548 ResultTy = Type::getMetadataTy(Context);
550 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
551 ResultTy = Type::getX86_MMXTy(Context);
553 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
554 if (Record.size() < 1)
555 return Error("Invalid Integer type record");
557 ResultTy = IntegerType::get(Context, Record[0]);
559 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
560 // [pointee type, address space]
561 if (Record.size() < 1)
562 return Error("Invalid POINTER type record");
563 unsigned AddressSpace = 0;
564 if (Record.size() == 2)
565 AddressSpace = Record[1];
566 ResultTy = PointerType::get(getTypeByID(Record[0], true),
570 case bitc::TYPE_CODE_FUNCTION: {
571 // FIXME: attrid is dead, remove it in LLVM 3.0
572 // FUNCTION: [vararg, attrid, retty, paramty x N]
573 if (Record.size() < 3)
574 return Error("Invalid FUNCTION type record");
575 std::vector<const Type*> ArgTys;
576 for (unsigned i = 3, e = Record.size(); i != e; ++i)
577 ArgTys.push_back(getTypeByID(Record[i], true));
579 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
583 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
584 if (Record.size() < 1)
585 return Error("Invalid STRUCT type record");
586 std::vector<const Type*> EltTys;
587 for (unsigned i = 1, e = Record.size(); i != e; ++i)
588 EltTys.push_back(getTypeByID(Record[i], true));
589 ResultTy = StructType::get(Context, EltTys, Record[0]);
592 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
593 if (Record.size() < 2)
594 return Error("Invalid ARRAY type record");
595 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
597 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
598 if (Record.size() < 2)
599 return Error("Invalid VECTOR type record");
600 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
604 if (NumRecords == TypeList.size()) {
605 // If this is a new type slot, just append it.
606 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
608 } else if (ResultTy == 0) {
609 // Otherwise, this was forward referenced, so an opaque type was created,
610 // but the result type is actually just an opaque. Leave the one we
611 // created previously.
614 // Otherwise, this was forward referenced, so an opaque type was created.
615 // Resolve the opaque type to the real type now.
616 assert(NumRecords < TypeList.size() && "Typelist imbalance");
617 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
619 // Don't directly push the new type on the Tab. Instead we want to replace
620 // the opaque type we previously inserted with the new concrete value. The
621 // refinement from the abstract (opaque) type to the new type causes all
622 // uses of the abstract type to use the concrete type (NewTy). This will
623 // also cause the opaque type to be deleted.
624 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
626 // This should have replaced the old opaque type with the new type in the
627 // value table... or with a preexisting type that was already in the
628 // system. Let's just make sure it did.
629 assert(TypeList[NumRecords-1].get() != OldTy &&
630 "refineAbstractType didn't work!");
636 bool BitcodeReader::ParseTypeSymbolTable() {
637 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
638 return Error("Malformed block record");
640 SmallVector<uint64_t, 64> Record;
642 // Read all the records for this type table.
643 std::string TypeName;
645 unsigned Code = Stream.ReadCode();
646 if (Code == bitc::END_BLOCK) {
647 if (Stream.ReadBlockEnd())
648 return Error("Error at end of type symbol table block");
652 if (Code == bitc::ENTER_SUBBLOCK) {
653 // No known subblocks, always skip them.
654 Stream.ReadSubBlockID();
655 if (Stream.SkipBlock())
656 return Error("Malformed block record");
660 if (Code == bitc::DEFINE_ABBREV) {
661 Stream.ReadAbbrevRecord();
667 switch (Stream.ReadRecord(Code, Record)) {
668 default: // Default behavior: unknown type.
670 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
671 if (ConvertToString(Record, 1, TypeName))
672 return Error("Invalid TST_ENTRY record");
673 unsigned TypeID = Record[0];
674 if (TypeID >= TypeList.size())
675 return Error("Invalid Type ID in TST_ENTRY record");
677 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
684 bool BitcodeReader::ParseValueSymbolTable() {
685 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
686 return Error("Malformed block record");
688 SmallVector<uint64_t, 64> Record;
690 // Read all the records for this value table.
691 SmallString<128> ValueName;
693 unsigned Code = Stream.ReadCode();
694 if (Code == bitc::END_BLOCK) {
695 if (Stream.ReadBlockEnd())
696 return Error("Error at end of value symbol table block");
699 if (Code == bitc::ENTER_SUBBLOCK) {
700 // No known subblocks, always skip them.
701 Stream.ReadSubBlockID();
702 if (Stream.SkipBlock())
703 return Error("Malformed block record");
707 if (Code == bitc::DEFINE_ABBREV) {
708 Stream.ReadAbbrevRecord();
714 switch (Stream.ReadRecord(Code, Record)) {
715 default: // Default behavior: unknown type.
717 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
718 if (ConvertToString(Record, 1, ValueName))
719 return Error("Invalid VST_ENTRY record");
720 unsigned ValueID = Record[0];
721 if (ValueID >= ValueList.size())
722 return Error("Invalid Value ID in VST_ENTRY record");
723 Value *V = ValueList[ValueID];
725 V->setName(StringRef(ValueName.data(), ValueName.size()));
729 case bitc::VST_CODE_BBENTRY: {
730 if (ConvertToString(Record, 1, ValueName))
731 return Error("Invalid VST_BBENTRY record");
732 BasicBlock *BB = getBasicBlock(Record[0]);
734 return Error("Invalid BB ID in VST_BBENTRY record");
736 BB->setName(StringRef(ValueName.data(), ValueName.size()));
744 bool BitcodeReader::ParseMetadata() {
745 unsigned NextMDValueNo = MDValueList.size();
747 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
748 return Error("Malformed block record");
750 SmallVector<uint64_t, 64> Record;
752 // Read all the records.
754 unsigned Code = Stream.ReadCode();
755 if (Code == bitc::END_BLOCK) {
756 if (Stream.ReadBlockEnd())
757 return Error("Error at end of PARAMATTR block");
761 if (Code == bitc::ENTER_SUBBLOCK) {
762 // No known subblocks, always skip them.
763 Stream.ReadSubBlockID();
764 if (Stream.SkipBlock())
765 return Error("Malformed block record");
769 if (Code == bitc::DEFINE_ABBREV) {
770 Stream.ReadAbbrevRecord();
774 bool IsFunctionLocal = false;
777 Code = Stream.ReadRecord(Code, Record);
779 default: // Default behavior: ignore.
781 case bitc::METADATA_NAME: {
782 // Read named of the named metadata.
783 unsigned NameLength = Record.size();
785 Name.resize(NameLength);
786 for (unsigned i = 0; i != NameLength; ++i)
789 Code = Stream.ReadCode();
791 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
792 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
793 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
795 // Read named metadata elements.
796 unsigned Size = Record.size();
797 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
798 for (unsigned i = 0; i != Size; ++i) {
799 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
801 return Error("Malformed metadata record");
806 case bitc::METADATA_FN_NODE:
807 IsFunctionLocal = true;
809 case bitc::METADATA_NODE: {
810 if (Record.size() % 2 == 1)
811 return Error("Invalid METADATA_NODE record");
813 unsigned Size = Record.size();
814 SmallVector<Value*, 8> Elts;
815 for (unsigned i = 0; i != Size; i += 2) {
816 const Type *Ty = getTypeByID(Record[i]);
817 if (!Ty) return Error("Invalid METADATA_NODE record");
818 if (Ty->isMetadataTy())
819 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
820 else if (!Ty->isVoidTy())
821 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
823 Elts.push_back(NULL);
825 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
826 IsFunctionLocal = false;
827 MDValueList.AssignValue(V, NextMDValueNo++);
830 case bitc::METADATA_STRING: {
831 unsigned MDStringLength = Record.size();
832 SmallString<8> String;
833 String.resize(MDStringLength);
834 for (unsigned i = 0; i != MDStringLength; ++i)
835 String[i] = Record[i];
836 Value *V = MDString::get(Context,
837 StringRef(String.data(), String.size()));
838 MDValueList.AssignValue(V, NextMDValueNo++);
841 case bitc::METADATA_KIND: {
842 unsigned RecordLength = Record.size();
843 if (Record.empty() || RecordLength < 2)
844 return Error("Invalid METADATA_KIND record");
846 Name.resize(RecordLength-1);
847 unsigned Kind = Record[0];
848 for (unsigned i = 1; i != RecordLength; ++i)
849 Name[i-1] = Record[i];
851 unsigned NewKind = TheModule->getMDKindID(Name.str());
852 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
853 return Error("Conflicting METADATA_KIND records");
860 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
861 /// the LSB for dense VBR encoding.
862 static uint64_t DecodeSignRotatedValue(uint64_t V) {
867 // There is no such thing as -0 with integers. "-0" really means MININT.
871 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
872 /// values and aliases that we can.
873 bool BitcodeReader::ResolveGlobalAndAliasInits() {
874 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
875 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
877 GlobalInitWorklist.swap(GlobalInits);
878 AliasInitWorklist.swap(AliasInits);
880 while (!GlobalInitWorklist.empty()) {
881 unsigned ValID = GlobalInitWorklist.back().second;
882 if (ValID >= ValueList.size()) {
883 // Not ready to resolve this yet, it requires something later in the file.
884 GlobalInits.push_back(GlobalInitWorklist.back());
886 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
887 GlobalInitWorklist.back().first->setInitializer(C);
889 return Error("Global variable initializer is not a constant!");
891 GlobalInitWorklist.pop_back();
894 while (!AliasInitWorklist.empty()) {
895 unsigned ValID = AliasInitWorklist.back().second;
896 if (ValID >= ValueList.size()) {
897 AliasInits.push_back(AliasInitWorklist.back());
899 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
900 AliasInitWorklist.back().first->setAliasee(C);
902 return Error("Alias initializer is not a constant!");
904 AliasInitWorklist.pop_back();
909 bool BitcodeReader::ParseConstants() {
910 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
911 return Error("Malformed block record");
913 SmallVector<uint64_t, 64> Record;
915 // Read all the records for this value table.
916 const Type *CurTy = Type::getInt32Ty(Context);
917 unsigned NextCstNo = ValueList.size();
919 unsigned Code = Stream.ReadCode();
920 if (Code == bitc::END_BLOCK)
923 if (Code == bitc::ENTER_SUBBLOCK) {
924 // No known subblocks, always skip them.
925 Stream.ReadSubBlockID();
926 if (Stream.SkipBlock())
927 return Error("Malformed block record");
931 if (Code == bitc::DEFINE_ABBREV) {
932 Stream.ReadAbbrevRecord();
939 unsigned BitCode = Stream.ReadRecord(Code, Record);
941 default: // Default behavior: unknown constant
942 case bitc::CST_CODE_UNDEF: // UNDEF
943 V = UndefValue::get(CurTy);
945 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
947 return Error("Malformed CST_SETTYPE record");
948 if (Record[0] >= TypeList.size())
949 return Error("Invalid Type ID in CST_SETTYPE record");
950 CurTy = TypeList[Record[0]];
951 continue; // Skip the ValueList manipulation.
952 case bitc::CST_CODE_NULL: // NULL
953 V = Constant::getNullValue(CurTy);
955 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
956 if (!CurTy->isIntegerTy() || Record.empty())
957 return Error("Invalid CST_INTEGER record");
958 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
960 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
961 if (!CurTy->isIntegerTy() || Record.empty())
962 return Error("Invalid WIDE_INTEGER record");
964 unsigned NumWords = Record.size();
965 SmallVector<uint64_t, 8> Words;
966 Words.resize(NumWords);
967 for (unsigned i = 0; i != NumWords; ++i)
968 Words[i] = DecodeSignRotatedValue(Record[i]);
969 V = ConstantInt::get(Context,
970 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
971 NumWords, &Words[0]));
974 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
976 return Error("Invalid FLOAT record");
977 if (CurTy->isFloatTy())
978 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
979 else if (CurTy->isDoubleTy())
980 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
981 else if (CurTy->isX86_FP80Ty()) {
982 // Bits are not stored the same way as a normal i80 APInt, compensate.
983 uint64_t Rearrange[2];
984 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
985 Rearrange[1] = Record[0] >> 48;
986 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
987 } else if (CurTy->isFP128Ty())
988 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
989 else if (CurTy->isPPC_FP128Ty())
990 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
992 V = UndefValue::get(CurTy);
996 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
998 return Error("Invalid CST_AGGREGATE record");
1000 unsigned Size = Record.size();
1001 std::vector<Constant*> Elts;
1003 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
1004 for (unsigned i = 0; i != Size; ++i)
1005 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1006 STy->getElementType(i)));
1007 V = ConstantStruct::get(STy, Elts);
1008 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1009 const Type *EltTy = ATy->getElementType();
1010 for (unsigned i = 0; i != Size; ++i)
1011 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1012 V = ConstantArray::get(ATy, Elts);
1013 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1014 const Type *EltTy = VTy->getElementType();
1015 for (unsigned i = 0; i != Size; ++i)
1016 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1017 V = ConstantVector::get(Elts);
1019 V = UndefValue::get(CurTy);
1023 case bitc::CST_CODE_STRING: { // STRING: [values]
1025 return Error("Invalid CST_AGGREGATE record");
1027 const ArrayType *ATy = cast<ArrayType>(CurTy);
1028 const Type *EltTy = ATy->getElementType();
1030 unsigned Size = Record.size();
1031 std::vector<Constant*> Elts;
1032 for (unsigned i = 0; i != Size; ++i)
1033 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1034 V = ConstantArray::get(ATy, Elts);
1037 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1039 return Error("Invalid CST_AGGREGATE record");
1041 const ArrayType *ATy = cast<ArrayType>(CurTy);
1042 const Type *EltTy = ATy->getElementType();
1044 unsigned Size = Record.size();
1045 std::vector<Constant*> Elts;
1046 for (unsigned i = 0; i != Size; ++i)
1047 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1048 Elts.push_back(Constant::getNullValue(EltTy));
1049 V = ConstantArray::get(ATy, Elts);
1052 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1053 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1054 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1056 V = UndefValue::get(CurTy); // Unknown binop.
1058 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1059 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1061 if (Record.size() >= 4) {
1062 if (Opc == Instruction::Add ||
1063 Opc == Instruction::Sub ||
1064 Opc == Instruction::Mul ||
1065 Opc == Instruction::Shl) {
1066 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1067 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1068 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1069 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1070 } else if (Opc == Instruction::SDiv ||
1071 Opc == Instruction::UDiv ||
1072 Opc == Instruction::LShr ||
1073 Opc == Instruction::AShr) {
1074 if (Record[3] & (1 << bitc::PEO_EXACT))
1075 Flags |= SDivOperator::IsExact;
1078 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1082 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1083 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1084 int Opc = GetDecodedCastOpcode(Record[0]);
1086 V = UndefValue::get(CurTy); // Unknown cast.
1088 const Type *OpTy = getTypeByID(Record[1]);
1089 if (!OpTy) return Error("Invalid CE_CAST record");
1090 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1091 V = ConstantExpr::getCast(Opc, Op, CurTy);
1095 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1096 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1097 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1098 SmallVector<Constant*, 16> Elts;
1099 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1100 const Type *ElTy = getTypeByID(Record[i]);
1101 if (!ElTy) return Error("Invalid CE_GEP record");
1102 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1104 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1105 V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
1108 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1112 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1113 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1114 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1115 Type::getInt1Ty(Context)),
1116 ValueList.getConstantFwdRef(Record[1],CurTy),
1117 ValueList.getConstantFwdRef(Record[2],CurTy));
1119 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1120 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1121 const VectorType *OpTy =
1122 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1123 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1124 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1125 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1126 V = ConstantExpr::getExtractElement(Op0, Op1);
1129 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1130 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1131 if (Record.size() < 3 || OpTy == 0)
1132 return Error("Invalid CE_INSERTELT record");
1133 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1134 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1135 OpTy->getElementType());
1136 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1137 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1140 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1141 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1142 if (Record.size() < 3 || OpTy == 0)
1143 return Error("Invalid CE_SHUFFLEVEC record");
1144 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1145 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1146 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1147 OpTy->getNumElements());
1148 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1149 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1152 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1153 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1154 const VectorType *OpTy =
1155 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1156 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1157 return Error("Invalid CE_SHUFVEC_EX record");
1158 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1159 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1160 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1161 RTy->getNumElements());
1162 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1163 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1166 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1167 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1168 const Type *OpTy = getTypeByID(Record[0]);
1169 if (OpTy == 0) return Error("Invalid CE_CMP record");
1170 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1171 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1173 if (OpTy->isFPOrFPVectorTy())
1174 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1176 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1179 case bitc::CST_CODE_INLINEASM: {
1180 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1181 std::string AsmStr, ConstrStr;
1182 bool HasSideEffects = Record[0] & 1;
1183 bool IsAlignStack = Record[0] >> 1;
1184 unsigned AsmStrSize = Record[1];
1185 if (2+AsmStrSize >= Record.size())
1186 return Error("Invalid INLINEASM record");
1187 unsigned ConstStrSize = Record[2+AsmStrSize];
1188 if (3+AsmStrSize+ConstStrSize > Record.size())
1189 return Error("Invalid INLINEASM record");
1191 for (unsigned i = 0; i != AsmStrSize; ++i)
1192 AsmStr += (char)Record[2+i];
1193 for (unsigned i = 0; i != ConstStrSize; ++i)
1194 ConstrStr += (char)Record[3+AsmStrSize+i];
1195 const PointerType *PTy = cast<PointerType>(CurTy);
1196 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1197 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1200 case bitc::CST_CODE_BLOCKADDRESS:{
1201 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1202 const Type *FnTy = getTypeByID(Record[0]);
1203 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1205 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1206 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1208 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1209 Type::getInt8Ty(Context),
1210 false, GlobalValue::InternalLinkage,
1212 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1218 ValueList.AssignValue(V, NextCstNo);
1222 if (NextCstNo != ValueList.size())
1223 return Error("Invalid constant reference!");
1225 if (Stream.ReadBlockEnd())
1226 return Error("Error at end of constants block");
1228 // Once all the constants have been read, go through and resolve forward
1230 ValueList.ResolveConstantForwardRefs();
1234 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1235 /// remember where it is and then skip it. This lets us lazily deserialize the
1237 bool BitcodeReader::RememberAndSkipFunctionBody() {
1238 // Get the function we are talking about.
1239 if (FunctionsWithBodies.empty())
1240 return Error("Insufficient function protos");
1242 Function *Fn = FunctionsWithBodies.back();
1243 FunctionsWithBodies.pop_back();
1245 // Save the current stream state.
1246 uint64_t CurBit = Stream.GetCurrentBitNo();
1247 DeferredFunctionInfo[Fn] = CurBit;
1249 // Skip over the function block for now.
1250 if (Stream.SkipBlock())
1251 return Error("Malformed block record");
1255 bool BitcodeReader::ParseModule() {
1256 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1257 return Error("Malformed block record");
1259 SmallVector<uint64_t, 64> Record;
1260 std::vector<std::string> SectionTable;
1261 std::vector<std::string> GCTable;
1263 // Read all the records for this module.
1264 while (!Stream.AtEndOfStream()) {
1265 unsigned Code = Stream.ReadCode();
1266 if (Code == bitc::END_BLOCK) {
1267 if (Stream.ReadBlockEnd())
1268 return Error("Error at end of module block");
1270 // Patch the initializers for globals and aliases up.
1271 ResolveGlobalAndAliasInits();
1272 if (!GlobalInits.empty() || !AliasInits.empty())
1273 return Error("Malformed global initializer set");
1274 if (!FunctionsWithBodies.empty())
1275 return Error("Too few function bodies found");
1277 // Look for intrinsic functions which need to be upgraded at some point
1278 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1281 if (UpgradeIntrinsicFunction(FI, NewFn))
1282 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1285 // Look for global variables which need to be renamed.
1286 for (Module::global_iterator
1287 GI = TheModule->global_begin(), GE = TheModule->global_end();
1289 UpgradeGlobalVariable(GI);
1291 // Force deallocation of memory for these vectors to favor the client that
1292 // want lazy deserialization.
1293 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1294 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1295 std::vector<Function*>().swap(FunctionsWithBodies);
1299 if (Code == bitc::ENTER_SUBBLOCK) {
1300 switch (Stream.ReadSubBlockID()) {
1301 default: // Skip unknown content.
1302 if (Stream.SkipBlock())
1303 return Error("Malformed block record");
1305 case bitc::BLOCKINFO_BLOCK_ID:
1306 if (Stream.ReadBlockInfoBlock())
1307 return Error("Malformed BlockInfoBlock");
1309 case bitc::PARAMATTR_BLOCK_ID:
1310 if (ParseAttributeBlock())
1313 case bitc::TYPE_BLOCK_ID:
1314 if (ParseTypeTable())
1317 case bitc::TYPE_SYMTAB_BLOCK_ID:
1318 if (ParseTypeSymbolTable())
1321 case bitc::VALUE_SYMTAB_BLOCK_ID:
1322 if (ParseValueSymbolTable())
1325 case bitc::CONSTANTS_BLOCK_ID:
1326 if (ParseConstants() || ResolveGlobalAndAliasInits())
1329 case bitc::METADATA_BLOCK_ID:
1330 if (ParseMetadata())
1333 case bitc::FUNCTION_BLOCK_ID:
1334 // If this is the first function body we've seen, reverse the
1335 // FunctionsWithBodies list.
1336 if (!HasReversedFunctionsWithBodies) {
1337 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1338 HasReversedFunctionsWithBodies = true;
1341 if (RememberAndSkipFunctionBody())
1348 if (Code == bitc::DEFINE_ABBREV) {
1349 Stream.ReadAbbrevRecord();
1354 switch (Stream.ReadRecord(Code, Record)) {
1355 default: break; // Default behavior, ignore unknown content.
1356 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1357 if (Record.size() < 1)
1358 return Error("Malformed MODULE_CODE_VERSION");
1359 // Only version #0 is supported so far.
1361 return Error("Unknown bitstream version!");
1363 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1365 if (ConvertToString(Record, 0, S))
1366 return Error("Invalid MODULE_CODE_TRIPLE record");
1367 TheModule->setTargetTriple(S);
1370 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1372 if (ConvertToString(Record, 0, S))
1373 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1374 TheModule->setDataLayout(S);
1377 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1379 if (ConvertToString(Record, 0, S))
1380 return Error("Invalid MODULE_CODE_ASM record");
1381 TheModule->setModuleInlineAsm(S);
1384 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1386 if (ConvertToString(Record, 0, S))
1387 return Error("Invalid MODULE_CODE_DEPLIB record");
1388 TheModule->addLibrary(S);
1391 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1393 if (ConvertToString(Record, 0, S))
1394 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1395 SectionTable.push_back(S);
1398 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1400 if (ConvertToString(Record, 0, S))
1401 return Error("Invalid MODULE_CODE_GCNAME record");
1402 GCTable.push_back(S);
1405 // GLOBALVAR: [pointer type, isconst, initid,
1406 // linkage, alignment, section, visibility, threadlocal,
1408 case bitc::MODULE_CODE_GLOBALVAR: {
1409 if (Record.size() < 6)
1410 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1411 const Type *Ty = getTypeByID(Record[0]);
1412 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1413 if (!Ty->isPointerTy())
1414 return Error("Global not a pointer type!");
1415 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1416 Ty = cast<PointerType>(Ty)->getElementType();
1418 bool isConstant = Record[1];
1419 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1420 unsigned Alignment = (1 << Record[4]) >> 1;
1421 std::string Section;
1423 if (Record[5]-1 >= SectionTable.size())
1424 return Error("Invalid section ID");
1425 Section = SectionTable[Record[5]-1];
1427 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1428 if (Record.size() > 6)
1429 Visibility = GetDecodedVisibility(Record[6]);
1430 bool isThreadLocal = false;
1431 if (Record.size() > 7)
1432 isThreadLocal = Record[7];
1434 bool UnnamedAddr = false;
1435 if (Record.size() > 8)
1436 UnnamedAddr = Record[8];
1438 GlobalVariable *NewGV =
1439 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1440 isThreadLocal, AddressSpace);
1441 NewGV->setAlignment(Alignment);
1442 if (!Section.empty())
1443 NewGV->setSection(Section);
1444 NewGV->setVisibility(Visibility);
1445 NewGV->setThreadLocal(isThreadLocal);
1446 NewGV->setUnnamedAddr(UnnamedAddr);
1448 ValueList.push_back(NewGV);
1450 // Remember which value to use for the global initializer.
1451 if (unsigned InitID = Record[2])
1452 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1455 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1456 // alignment, section, visibility, gc, unnamed_addr]
1457 case bitc::MODULE_CODE_FUNCTION: {
1458 if (Record.size() < 8)
1459 return Error("Invalid MODULE_CODE_FUNCTION record");
1460 const Type *Ty = getTypeByID(Record[0]);
1461 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1462 if (!Ty->isPointerTy())
1463 return Error("Function not a pointer type!");
1464 const FunctionType *FTy =
1465 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1467 return Error("Function not a pointer to function type!");
1469 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1472 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1473 bool isProto = Record[2];
1474 Func->setLinkage(GetDecodedLinkage(Record[3]));
1475 Func->setAttributes(getAttributes(Record[4]));
1477 Func->setAlignment((1 << Record[5]) >> 1);
1479 if (Record[6]-1 >= SectionTable.size())
1480 return Error("Invalid section ID");
1481 Func->setSection(SectionTable[Record[6]-1]);
1483 Func->setVisibility(GetDecodedVisibility(Record[7]));
1484 if (Record.size() > 8 && Record[8]) {
1485 if (Record[8]-1 > GCTable.size())
1486 return Error("Invalid GC ID");
1487 Func->setGC(GCTable[Record[8]-1].c_str());
1489 bool UnnamedAddr = false;
1490 if (Record.size() > 9)
1491 UnnamedAddr = Record[9];
1492 Func->setUnnamedAddr(UnnamedAddr);
1493 ValueList.push_back(Func);
1495 // If this is a function with a body, remember the prototype we are
1496 // creating now, so that we can match up the body with them later.
1498 FunctionsWithBodies.push_back(Func);
1501 // ALIAS: [alias type, aliasee val#, linkage]
1502 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1503 case bitc::MODULE_CODE_ALIAS: {
1504 if (Record.size() < 3)
1505 return Error("Invalid MODULE_ALIAS record");
1506 const Type *Ty = getTypeByID(Record[0]);
1507 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1508 if (!Ty->isPointerTy())
1509 return Error("Function not a pointer type!");
1511 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1513 // Old bitcode files didn't have visibility field.
1514 if (Record.size() > 3)
1515 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1516 ValueList.push_back(NewGA);
1517 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1520 /// MODULE_CODE_PURGEVALS: [numvals]
1521 case bitc::MODULE_CODE_PURGEVALS:
1522 // Trim down the value list to the specified size.
1523 if (Record.size() < 1 || Record[0] > ValueList.size())
1524 return Error("Invalid MODULE_PURGEVALS record");
1525 ValueList.shrinkTo(Record[0]);
1531 return Error("Premature end of bitstream");
1534 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1537 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1538 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1540 if (Buffer->getBufferSize() & 3) {
1541 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1542 return Error("Invalid bitcode signature");
1544 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1547 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1548 // The magic number is 0x0B17C0DE stored in little endian.
1549 if (isBitcodeWrapper(BufPtr, BufEnd))
1550 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1551 return Error("Invalid bitcode wrapper header");
1553 StreamFile.init(BufPtr, BufEnd);
1554 Stream.init(StreamFile);
1556 // Sniff for the signature.
1557 if (Stream.Read(8) != 'B' ||
1558 Stream.Read(8) != 'C' ||
1559 Stream.Read(4) != 0x0 ||
1560 Stream.Read(4) != 0xC ||
1561 Stream.Read(4) != 0xE ||
1562 Stream.Read(4) != 0xD)
1563 return Error("Invalid bitcode signature");
1565 // We expect a number of well-defined blocks, though we don't necessarily
1566 // need to understand them all.
1567 while (!Stream.AtEndOfStream()) {
1568 unsigned Code = Stream.ReadCode();
1570 if (Code != bitc::ENTER_SUBBLOCK) {
1572 // The ranlib in xcode 4 will align archive members by appending newlines to the
1573 // end of them. If this file size is a multiple of 4 but not 8, we have to read and
1574 // ignore these final 4 bytes :-(
1575 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1576 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1577 Stream.AtEndOfStream())
1580 return Error("Invalid record at top-level");
1583 unsigned BlockID = Stream.ReadSubBlockID();
1585 // We only know the MODULE subblock ID.
1587 case bitc::BLOCKINFO_BLOCK_ID:
1588 if (Stream.ReadBlockInfoBlock())
1589 return Error("Malformed BlockInfoBlock");
1591 case bitc::MODULE_BLOCK_ID:
1592 // Reject multiple MODULE_BLOCK's in a single bitstream.
1594 return Error("Multiple MODULE_BLOCKs in same stream");
1600 if (Stream.SkipBlock())
1601 return Error("Malformed block record");
1609 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1610 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1611 return Error("Malformed block record");
1613 SmallVector<uint64_t, 64> Record;
1615 // Read all the records for this module.
1616 while (!Stream.AtEndOfStream()) {
1617 unsigned Code = Stream.ReadCode();
1618 if (Code == bitc::END_BLOCK) {
1619 if (Stream.ReadBlockEnd())
1620 return Error("Error at end of module block");
1625 if (Code == bitc::ENTER_SUBBLOCK) {
1626 switch (Stream.ReadSubBlockID()) {
1627 default: // Skip unknown content.
1628 if (Stream.SkipBlock())
1629 return Error("Malformed block record");
1635 if (Code == bitc::DEFINE_ABBREV) {
1636 Stream.ReadAbbrevRecord();
1641 switch (Stream.ReadRecord(Code, Record)) {
1642 default: break; // Default behavior, ignore unknown content.
1643 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1644 if (Record.size() < 1)
1645 return Error("Malformed MODULE_CODE_VERSION");
1646 // Only version #0 is supported so far.
1648 return Error("Unknown bitstream version!");
1650 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1652 if (ConvertToString(Record, 0, S))
1653 return Error("Invalid MODULE_CODE_TRIPLE record");
1661 return Error("Premature end of bitstream");
1664 bool BitcodeReader::ParseTriple(std::string &Triple) {
1665 if (Buffer->getBufferSize() & 3)
1666 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1668 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1669 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1671 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1672 // The magic number is 0x0B17C0DE stored in little endian.
1673 if (isBitcodeWrapper(BufPtr, BufEnd))
1674 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1675 return Error("Invalid bitcode wrapper header");
1677 StreamFile.init(BufPtr, BufEnd);
1678 Stream.init(StreamFile);
1680 // Sniff for the signature.
1681 if (Stream.Read(8) != 'B' ||
1682 Stream.Read(8) != 'C' ||
1683 Stream.Read(4) != 0x0 ||
1684 Stream.Read(4) != 0xC ||
1685 Stream.Read(4) != 0xE ||
1686 Stream.Read(4) != 0xD)
1687 return Error("Invalid bitcode signature");
1689 // We expect a number of well-defined blocks, though we don't necessarily
1690 // need to understand them all.
1691 while (!Stream.AtEndOfStream()) {
1692 unsigned Code = Stream.ReadCode();
1694 if (Code != bitc::ENTER_SUBBLOCK)
1695 return Error("Invalid record at top-level");
1697 unsigned BlockID = Stream.ReadSubBlockID();
1699 // We only know the MODULE subblock ID.
1701 case bitc::MODULE_BLOCK_ID:
1702 if (ParseModuleTriple(Triple))
1706 if (Stream.SkipBlock())
1707 return Error("Malformed block record");
1715 /// ParseMetadataAttachment - Parse metadata attachments.
1716 bool BitcodeReader::ParseMetadataAttachment() {
1717 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1718 return Error("Malformed block record");
1720 SmallVector<uint64_t, 64> Record;
1722 unsigned Code = Stream.ReadCode();
1723 if (Code == bitc::END_BLOCK) {
1724 if (Stream.ReadBlockEnd())
1725 return Error("Error at end of PARAMATTR block");
1728 if (Code == bitc::DEFINE_ABBREV) {
1729 Stream.ReadAbbrevRecord();
1732 // Read a metadata attachment record.
1734 switch (Stream.ReadRecord(Code, Record)) {
1735 default: // Default behavior: ignore.
1737 case bitc::METADATA_ATTACHMENT: {
1738 unsigned RecordLength = Record.size();
1739 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1740 return Error ("Invalid METADATA_ATTACHMENT reader!");
1741 Instruction *Inst = InstructionList[Record[0]];
1742 for (unsigned i = 1; i != RecordLength; i = i+2) {
1743 unsigned Kind = Record[i];
1744 DenseMap<unsigned, unsigned>::iterator I =
1745 MDKindMap.find(Kind);
1746 if (I == MDKindMap.end())
1747 return Error("Invalid metadata kind ID");
1748 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1749 Inst->setMetadata(I->second, cast<MDNode>(Node));
1758 /// ParseFunctionBody - Lazily parse the specified function body block.
1759 bool BitcodeReader::ParseFunctionBody(Function *F) {
1760 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1761 return Error("Malformed block record");
1763 InstructionList.clear();
1764 unsigned ModuleValueListSize = ValueList.size();
1765 unsigned ModuleMDValueListSize = MDValueList.size();
1767 // Add all the function arguments to the value table.
1768 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1769 ValueList.push_back(I);
1771 unsigned NextValueNo = ValueList.size();
1772 BasicBlock *CurBB = 0;
1773 unsigned CurBBNo = 0;
1777 // Read all the records.
1778 SmallVector<uint64_t, 64> Record;
1780 unsigned Code = Stream.ReadCode();
1781 if (Code == bitc::END_BLOCK) {
1782 if (Stream.ReadBlockEnd())
1783 return Error("Error at end of function block");
1787 if (Code == bitc::ENTER_SUBBLOCK) {
1788 switch (Stream.ReadSubBlockID()) {
1789 default: // Skip unknown content.
1790 if (Stream.SkipBlock())
1791 return Error("Malformed block record");
1793 case bitc::CONSTANTS_BLOCK_ID:
1794 if (ParseConstants()) return true;
1795 NextValueNo = ValueList.size();
1797 case bitc::VALUE_SYMTAB_BLOCK_ID:
1798 if (ParseValueSymbolTable()) return true;
1800 case bitc::METADATA_ATTACHMENT_ID:
1801 if (ParseMetadataAttachment()) return true;
1803 case bitc::METADATA_BLOCK_ID:
1804 if (ParseMetadata()) return true;
1810 if (Code == bitc::DEFINE_ABBREV) {
1811 Stream.ReadAbbrevRecord();
1818 unsigned BitCode = Stream.ReadRecord(Code, Record);
1820 default: // Default behavior: reject
1821 return Error("Unknown instruction");
1822 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1823 if (Record.size() < 1 || Record[0] == 0)
1824 return Error("Invalid DECLAREBLOCKS record");
1825 // Create all the basic blocks for the function.
1826 FunctionBBs.resize(Record[0]);
1827 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1828 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1829 CurBB = FunctionBBs[0];
1832 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1833 // This record indicates that the last instruction is at the same
1834 // location as the previous instruction with a location.
1837 // Get the last instruction emitted.
1838 if (CurBB && !CurBB->empty())
1840 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1841 !FunctionBBs[CurBBNo-1]->empty())
1842 I = &FunctionBBs[CurBBNo-1]->back();
1844 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1845 I->setDebugLoc(LastLoc);
1849 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
1850 I = 0; // Get the last instruction emitted.
1851 if (CurBB && !CurBB->empty())
1853 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1854 !FunctionBBs[CurBBNo-1]->empty())
1855 I = &FunctionBBs[CurBBNo-1]->back();
1856 if (I == 0 || Record.size() < 4)
1857 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1859 unsigned Line = Record[0], Col = Record[1];
1860 unsigned ScopeID = Record[2], IAID = Record[3];
1862 MDNode *Scope = 0, *IA = 0;
1863 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1864 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1865 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1866 I->setDebugLoc(LastLoc);
1871 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1874 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1875 getValue(Record, OpNum, LHS->getType(), RHS) ||
1876 OpNum+1 > Record.size())
1877 return Error("Invalid BINOP record");
1879 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1880 if (Opc == -1) return Error("Invalid BINOP record");
1881 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1882 InstructionList.push_back(I);
1883 if (OpNum < Record.size()) {
1884 if (Opc == Instruction::Add ||
1885 Opc == Instruction::Sub ||
1886 Opc == Instruction::Mul ||
1887 Opc == Instruction::Shl) {
1888 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1889 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1890 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1891 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1892 } else if (Opc == Instruction::SDiv ||
1893 Opc == Instruction::UDiv ||
1894 Opc == Instruction::LShr ||
1895 Opc == Instruction::AShr) {
1896 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
1897 cast<BinaryOperator>(I)->setIsExact(true);
1902 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1905 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1906 OpNum+2 != Record.size())
1907 return Error("Invalid CAST record");
1909 const Type *ResTy = getTypeByID(Record[OpNum]);
1910 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1911 if (Opc == -1 || ResTy == 0)
1912 return Error("Invalid CAST record");
1913 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1914 InstructionList.push_back(I);
1917 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1918 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1921 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1922 return Error("Invalid GEP record");
1924 SmallVector<Value*, 16> GEPIdx;
1925 while (OpNum != Record.size()) {
1927 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1928 return Error("Invalid GEP record");
1929 GEPIdx.push_back(Op);
1932 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1933 InstructionList.push_back(I);
1934 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1935 cast<GetElementPtrInst>(I)->setIsInBounds(true);
1939 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1940 // EXTRACTVAL: [opty, opval, n x indices]
1943 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1944 return Error("Invalid EXTRACTVAL record");
1946 SmallVector<unsigned, 4> EXTRACTVALIdx;
1947 for (unsigned RecSize = Record.size();
1948 OpNum != RecSize; ++OpNum) {
1949 uint64_t Index = Record[OpNum];
1950 if ((unsigned)Index != Index)
1951 return Error("Invalid EXTRACTVAL index");
1952 EXTRACTVALIdx.push_back((unsigned)Index);
1955 I = ExtractValueInst::Create(Agg,
1956 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1957 InstructionList.push_back(I);
1961 case bitc::FUNC_CODE_INST_INSERTVAL: {
1962 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1965 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1966 return Error("Invalid INSERTVAL record");
1968 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1969 return Error("Invalid INSERTVAL record");
1971 SmallVector<unsigned, 4> INSERTVALIdx;
1972 for (unsigned RecSize = Record.size();
1973 OpNum != RecSize; ++OpNum) {
1974 uint64_t Index = Record[OpNum];
1975 if ((unsigned)Index != Index)
1976 return Error("Invalid INSERTVAL index");
1977 INSERTVALIdx.push_back((unsigned)Index);
1980 I = InsertValueInst::Create(Agg, Val,
1981 INSERTVALIdx.begin(), INSERTVALIdx.end());
1982 InstructionList.push_back(I);
1986 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1987 // obsolete form of select
1988 // handles select i1 ... in old bitcode
1990 Value *TrueVal, *FalseVal, *Cond;
1991 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1992 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1993 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
1994 return Error("Invalid SELECT record");
1996 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1997 InstructionList.push_back(I);
2001 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2002 // new form of select
2003 // handles select i1 or select [N x i1]
2005 Value *TrueVal, *FalseVal, *Cond;
2006 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2007 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2008 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2009 return Error("Invalid SELECT record");
2011 // select condition can be either i1 or [N x i1]
2012 if (const VectorType* vector_type =
2013 dyn_cast<const VectorType>(Cond->getType())) {
2015 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2016 return Error("Invalid SELECT condition type");
2019 if (Cond->getType() != Type::getInt1Ty(Context))
2020 return Error("Invalid SELECT condition type");
2023 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2024 InstructionList.push_back(I);
2028 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2031 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2032 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2033 return Error("Invalid EXTRACTELT record");
2034 I = ExtractElementInst::Create(Vec, Idx);
2035 InstructionList.push_back(I);
2039 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2041 Value *Vec, *Elt, *Idx;
2042 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2043 getValue(Record, OpNum,
2044 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2045 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2046 return Error("Invalid INSERTELT record");
2047 I = InsertElementInst::Create(Vec, Elt, Idx);
2048 InstructionList.push_back(I);
2052 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2054 Value *Vec1, *Vec2, *Mask;
2055 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2056 getValue(Record, OpNum, Vec1->getType(), Vec2))
2057 return Error("Invalid SHUFFLEVEC record");
2059 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2060 return Error("Invalid SHUFFLEVEC record");
2061 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2062 InstructionList.push_back(I);
2066 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2067 // Old form of ICmp/FCmp returning bool
2068 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2069 // both legal on vectors but had different behaviour.
2070 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2071 // FCmp/ICmp returning bool or vector of bool
2075 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2076 getValue(Record, OpNum, LHS->getType(), RHS) ||
2077 OpNum+1 != Record.size())
2078 return Error("Invalid CMP record");
2080 if (LHS->getType()->isFPOrFPVectorTy())
2081 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2083 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2084 InstructionList.push_back(I);
2088 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2090 unsigned Size = Record.size();
2092 I = ReturnInst::Create(Context);
2093 InstructionList.push_back(I);
2099 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2100 return Error("Invalid RET record");
2101 if (OpNum != Record.size())
2102 return Error("Invalid RET record");
2104 I = ReturnInst::Create(Context, Op);
2105 InstructionList.push_back(I);
2108 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2109 if (Record.size() != 1 && Record.size() != 3)
2110 return Error("Invalid BR record");
2111 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2113 return Error("Invalid BR record");
2115 if (Record.size() == 1) {
2116 I = BranchInst::Create(TrueDest);
2117 InstructionList.push_back(I);
2120 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2121 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2122 if (FalseDest == 0 || Cond == 0)
2123 return Error("Invalid BR record");
2124 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2125 InstructionList.push_back(I);
2129 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2130 if (Record.size() < 3 || (Record.size() & 1) == 0)
2131 return Error("Invalid SWITCH record");
2132 const Type *OpTy = getTypeByID(Record[0]);
2133 Value *Cond = getFnValueByID(Record[1], OpTy);
2134 BasicBlock *Default = getBasicBlock(Record[2]);
2135 if (OpTy == 0 || Cond == 0 || Default == 0)
2136 return Error("Invalid SWITCH record");
2137 unsigned NumCases = (Record.size()-3)/2;
2138 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2139 InstructionList.push_back(SI);
2140 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2141 ConstantInt *CaseVal =
2142 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2143 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2144 if (CaseVal == 0 || DestBB == 0) {
2146 return Error("Invalid SWITCH record!");
2148 SI->addCase(CaseVal, DestBB);
2153 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2154 if (Record.size() < 2)
2155 return Error("Invalid INDIRECTBR record");
2156 const Type *OpTy = getTypeByID(Record[0]);
2157 Value *Address = getFnValueByID(Record[1], OpTy);
2158 if (OpTy == 0 || Address == 0)
2159 return Error("Invalid INDIRECTBR record");
2160 unsigned NumDests = Record.size()-2;
2161 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2162 InstructionList.push_back(IBI);
2163 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2164 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2165 IBI->addDestination(DestBB);
2168 return Error("Invalid INDIRECTBR record!");
2175 case bitc::FUNC_CODE_INST_INVOKE: {
2176 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2177 if (Record.size() < 4) return Error("Invalid INVOKE record");
2178 AttrListPtr PAL = getAttributes(Record[0]);
2179 unsigned CCInfo = Record[1];
2180 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2181 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2185 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2186 return Error("Invalid INVOKE record");
2188 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2189 const FunctionType *FTy = !CalleeTy ? 0 :
2190 dyn_cast<FunctionType>(CalleeTy->getElementType());
2192 // Check that the right number of fixed parameters are here.
2193 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2194 Record.size() < OpNum+FTy->getNumParams())
2195 return Error("Invalid INVOKE record");
2197 SmallVector<Value*, 16> Ops;
2198 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2199 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2200 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2203 if (!FTy->isVarArg()) {
2204 if (Record.size() != OpNum)
2205 return Error("Invalid INVOKE record");
2207 // Read type/value pairs for varargs params.
2208 while (OpNum != Record.size()) {
2210 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2211 return Error("Invalid INVOKE record");
2216 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
2217 Ops.begin(), Ops.end());
2218 InstructionList.push_back(I);
2219 cast<InvokeInst>(I)->setCallingConv(
2220 static_cast<CallingConv::ID>(CCInfo));
2221 cast<InvokeInst>(I)->setAttributes(PAL);
2224 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2225 I = new UnwindInst(Context);
2226 InstructionList.push_back(I);
2228 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2229 I = new UnreachableInst(Context);
2230 InstructionList.push_back(I);
2232 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2233 if (Record.size() < 1 || ((Record.size()-1)&1))
2234 return Error("Invalid PHI record");
2235 const Type *Ty = getTypeByID(Record[0]);
2236 if (!Ty) return Error("Invalid PHI record");
2238 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2239 InstructionList.push_back(PN);
2241 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2242 Value *V = getFnValueByID(Record[1+i], Ty);
2243 BasicBlock *BB = getBasicBlock(Record[2+i]);
2244 if (!V || !BB) return Error("Invalid PHI record");
2245 PN->addIncoming(V, BB);
2251 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2252 if (Record.size() != 4)
2253 return Error("Invalid ALLOCA record");
2254 const PointerType *Ty =
2255 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2256 const Type *OpTy = getTypeByID(Record[1]);
2257 Value *Size = getFnValueByID(Record[2], OpTy);
2258 unsigned Align = Record[3];
2259 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2260 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2261 InstructionList.push_back(I);
2264 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2267 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2268 OpNum+2 != Record.size())
2269 return Error("Invalid LOAD record");
2271 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2272 InstructionList.push_back(I);
2275 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2278 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2279 getValue(Record, OpNum,
2280 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2281 OpNum+2 != Record.size())
2282 return Error("Invalid STORE record");
2284 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2285 InstructionList.push_back(I);
2288 case bitc::FUNC_CODE_INST_CALL: {
2289 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2290 if (Record.size() < 3)
2291 return Error("Invalid CALL record");
2293 AttrListPtr PAL = getAttributes(Record[0]);
2294 unsigned CCInfo = Record[1];
2298 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2299 return Error("Invalid CALL record");
2301 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2302 const FunctionType *FTy = 0;
2303 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2304 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2305 return Error("Invalid CALL record");
2307 SmallVector<Value*, 16> Args;
2308 // Read the fixed params.
2309 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2310 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2311 Args.push_back(getBasicBlock(Record[OpNum]));
2313 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2314 if (Args.back() == 0) return Error("Invalid CALL record");
2317 // Read type/value pairs for varargs params.
2318 if (!FTy->isVarArg()) {
2319 if (OpNum != Record.size())
2320 return Error("Invalid CALL record");
2322 while (OpNum != Record.size()) {
2324 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2325 return Error("Invalid CALL record");
2330 I = CallInst::Create(Callee, Args.begin(), Args.end());
2331 InstructionList.push_back(I);
2332 cast<CallInst>(I)->setCallingConv(
2333 static_cast<CallingConv::ID>(CCInfo>>1));
2334 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2335 cast<CallInst>(I)->setAttributes(PAL);
2338 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2339 if (Record.size() < 3)
2340 return Error("Invalid VAARG record");
2341 const Type *OpTy = getTypeByID(Record[0]);
2342 Value *Op = getFnValueByID(Record[1], OpTy);
2343 const Type *ResTy = getTypeByID(Record[2]);
2344 if (!OpTy || !Op || !ResTy)
2345 return Error("Invalid VAARG record");
2346 I = new VAArgInst(Op, ResTy);
2347 InstructionList.push_back(I);
2352 // Add instruction to end of current BB. If there is no current BB, reject
2356 return Error("Invalid instruction with no BB");
2358 CurBB->getInstList().push_back(I);
2360 // If this was a terminator instruction, move to the next block.
2361 if (isa<TerminatorInst>(I)) {
2363 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2366 // Non-void values get registered in the value table for future use.
2367 if (I && !I->getType()->isVoidTy())
2368 ValueList.AssignValue(I, NextValueNo++);
2371 // Check the function list for unresolved values.
2372 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2373 if (A->getParent() == 0) {
2374 // We found at least one unresolved value. Nuke them all to avoid leaks.
2375 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2376 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2377 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2381 return Error("Never resolved value found in function!");
2385 // FIXME: Check for unresolved forward-declared metadata references
2386 // and clean up leaks.
2388 // See if anything took the address of blocks in this function. If so,
2389 // resolve them now.
2390 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2391 BlockAddrFwdRefs.find(F);
2392 if (BAFRI != BlockAddrFwdRefs.end()) {
2393 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2394 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2395 unsigned BlockIdx = RefList[i].first;
2396 if (BlockIdx >= FunctionBBs.size())
2397 return Error("Invalid blockaddress block #");
2399 GlobalVariable *FwdRef = RefList[i].second;
2400 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2401 FwdRef->eraseFromParent();
2404 BlockAddrFwdRefs.erase(BAFRI);
2407 // Trim the value list down to the size it was before we parsed this function.
2408 ValueList.shrinkTo(ModuleValueListSize);
2409 MDValueList.shrinkTo(ModuleMDValueListSize);
2410 std::vector<BasicBlock*>().swap(FunctionBBs);
2414 //===----------------------------------------------------------------------===//
2415 // GVMaterializer implementation
2416 //===----------------------------------------------------------------------===//
2419 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2420 if (const Function *F = dyn_cast<Function>(GV)) {
2421 return F->isDeclaration() &&
2422 DeferredFunctionInfo.count(const_cast<Function*>(F));
2427 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2428 Function *F = dyn_cast<Function>(GV);
2429 // If it's not a function or is already material, ignore the request.
2430 if (!F || !F->isMaterializable()) return false;
2432 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2433 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2435 // Move the bit stream to the saved position of the deferred function body.
2436 Stream.JumpToBit(DFII->second);
2438 if (ParseFunctionBody(F)) {
2439 if (ErrInfo) *ErrInfo = ErrorString;
2443 // Upgrade any old intrinsic calls in the function.
2444 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2445 E = UpgradedIntrinsics.end(); I != E; ++I) {
2446 if (I->first != I->second) {
2447 for (Value::use_iterator UI = I->first->use_begin(),
2448 UE = I->first->use_end(); UI != UE; ) {
2449 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2450 UpgradeIntrinsicCall(CI, I->second);
2458 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2459 const Function *F = dyn_cast<Function>(GV);
2460 if (!F || F->isDeclaration())
2462 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2465 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2466 Function *F = dyn_cast<Function>(GV);
2467 // If this function isn't dematerializable, this is a noop.
2468 if (!F || !isDematerializable(F))
2471 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2473 // Just forget the function body, we can remat it later.
2478 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2479 assert(M == TheModule &&
2480 "Can only Materialize the Module this BitcodeReader is attached to.");
2481 // Iterate over the module, deserializing any functions that are still on
2483 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2485 if (F->isMaterializable() &&
2486 Materialize(F, ErrInfo))
2489 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2490 // delete the old functions to clean up. We can't do this unless the entire
2491 // module is materialized because there could always be another function body
2492 // with calls to the old function.
2493 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2494 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2495 if (I->first != I->second) {
2496 for (Value::use_iterator UI = I->first->use_begin(),
2497 UE = I->first->use_end(); UI != UE; ) {
2498 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2499 UpgradeIntrinsicCall(CI, I->second);
2501 if (!I->first->use_empty())
2502 I->first->replaceAllUsesWith(I->second);
2503 I->first->eraseFromParent();
2506 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2508 // Check debug info intrinsics.
2509 CheckDebugInfoIntrinsics(TheModule);
2515 //===----------------------------------------------------------------------===//
2516 // External interface
2517 //===----------------------------------------------------------------------===//
2519 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2521 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2522 LLVMContext& Context,
2523 std::string *ErrMsg) {
2524 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2525 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2526 M->setMaterializer(R);
2527 if (R->ParseBitcodeInto(M)) {
2529 *ErrMsg = R->getErrorString();
2531 delete M; // Also deletes R.
2534 // Have the BitcodeReader dtor delete 'Buffer'.
2535 R->setBufferOwned(true);
2539 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2540 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2541 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2542 std::string *ErrMsg){
2543 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2546 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2547 // there was an error.
2548 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2550 // Read in the entire module, and destroy the BitcodeReader.
2551 if (M->MaterializeAllPermanently(ErrMsg)) {
2559 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2560 LLVMContext& Context,
2561 std::string *ErrMsg) {
2562 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2563 // Don't let the BitcodeReader dtor delete 'Buffer'.
2564 R->setBufferOwned(false);
2566 std::string Triple("");
2567 if (R->ParseTriple(Triple))
2569 *ErrMsg = R->getErrorString();