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/LLVMContext.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/AutoUpgrade.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/OperandTraits.h"
31 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();
44 //===----------------------------------------------------------------------===//
45 // Helper functions to implement forward reference resolution, etc.
46 //===----------------------------------------------------------------------===//
48 /// ConvertToString - Convert a string from a record into an std::string, return
50 template<typename StrTy>
51 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
53 if (Idx > Record.size())
56 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57 Result += (char)Record[i];
61 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63 default: // Map unknown/new linkages to external
64 case 0: return GlobalValue::ExternalLinkage;
65 case 1: return GlobalValue::WeakAnyLinkage;
66 case 2: return GlobalValue::AppendingLinkage;
67 case 3: return GlobalValue::InternalLinkage;
68 case 4: return GlobalValue::LinkOnceAnyLinkage;
69 case 5: return GlobalValue::DLLImportLinkage;
70 case 6: return GlobalValue::DLLExportLinkage;
71 case 7: return GlobalValue::ExternalWeakLinkage;
72 case 8: return GlobalValue::CommonLinkage;
73 case 9: return GlobalValue::PrivateLinkage;
74 case 10: return GlobalValue::WeakODRLinkage;
75 case 11: return GlobalValue::LinkOnceODRLinkage;
76 case 12: return GlobalValue::AvailableExternallyLinkage;
77 case 13: return GlobalValue::LinkerPrivateLinkage;
81 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
83 default: // Map unknown visibilities to default.
84 case 0: return GlobalValue::DefaultVisibility;
85 case 1: return GlobalValue::HiddenVisibility;
86 case 2: return GlobalValue::ProtectedVisibility;
90 static int GetDecodedCastOpcode(unsigned Val) {
93 case bitc::CAST_TRUNC : return Instruction::Trunc;
94 case bitc::CAST_ZEXT : return Instruction::ZExt;
95 case bitc::CAST_SEXT : return Instruction::SExt;
96 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
97 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
98 case bitc::CAST_UITOFP : return Instruction::UIToFP;
99 case bitc::CAST_SITOFP : return Instruction::SIToFP;
100 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
101 case bitc::CAST_FPEXT : return Instruction::FPExt;
102 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
103 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
104 case bitc::CAST_BITCAST : return Instruction::BitCast;
107 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
110 case bitc::BINOP_ADD:
111 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
112 case bitc::BINOP_SUB:
113 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
114 case bitc::BINOP_MUL:
115 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
116 case bitc::BINOP_UDIV: return Instruction::UDiv;
117 case bitc::BINOP_SDIV:
118 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
119 case bitc::BINOP_UREM: return Instruction::URem;
120 case bitc::BINOP_SREM:
121 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
122 case bitc::BINOP_SHL: return Instruction::Shl;
123 case bitc::BINOP_LSHR: return Instruction::LShr;
124 case bitc::BINOP_ASHR: return Instruction::AShr;
125 case bitc::BINOP_AND: return Instruction::And;
126 case bitc::BINOP_OR: return Instruction::Or;
127 case bitc::BINOP_XOR: return Instruction::Xor;
133 /// @brief A class for maintaining the slot number definition
134 /// as a placeholder for the actual definition for forward constants defs.
135 class ConstantPlaceHolder : public ConstantExpr {
136 ConstantPlaceHolder(); // DO NOT IMPLEMENT
137 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
139 // allocate space for exactly one operand
140 void *operator new(size_t s) {
141 return User::operator new(s, 1);
143 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
144 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
145 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
148 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
149 static inline bool classof(const ConstantPlaceHolder *) { return true; }
150 static bool classof(const Value *V) {
151 return isa<ConstantExpr>(V) &&
152 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
156 /// Provide fast operand accessors
157 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
161 // FIXME: can we inherit this from ConstantExpr?
163 struct OperandTraits<ConstantPlaceHolder> : public FixedNumOperandTraits<1> {
168 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
177 WeakVH &OldV = ValuePtrs[Idx];
183 // Handle constants and non-constants (e.g. instrs) differently for
185 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186 ResolveConstants.push_back(std::make_pair(PHC, Idx));
189 // If there was a forward reference to this value, replace it.
190 Value *PrevVal = OldV;
191 OldV->replaceAllUsesWith(V);
197 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
202 if (Value *V = ValuePtrs[Idx]) {
203 assert(Ty == V->getType() && "Type mismatch in constant table!");
204 return cast<Constant>(V);
207 // Create and return a placeholder, which will later be RAUW'd.
208 Constant *C = new ConstantPlaceHolder(Ty, Context);
213 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
217 if (Value *V = ValuePtrs[Idx]) {
218 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
222 // No type specified, must be invalid reference.
223 if (Ty == 0) return 0;
225 // Create and return a placeholder, which will later be RAUW'd.
226 Value *V = new Argument(Ty);
231 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
232 /// resolves any forward references. The idea behind this is that we sometimes
233 /// get constants (such as large arrays) which reference *many* forward ref
234 /// constants. Replacing each of these causes a lot of thrashing when
235 /// building/reuniquing the constant. Instead of doing this, we look at all the
236 /// uses and rewrite all the place holders at once for any constant that uses
238 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
239 // Sort the values by-pointer so that they are efficient to look up with a
241 std::sort(ResolveConstants.begin(), ResolveConstants.end());
243 SmallVector<Constant*, 64> NewOps;
245 while (!ResolveConstants.empty()) {
246 Value *RealVal = operator[](ResolveConstants.back().second);
247 Constant *Placeholder = ResolveConstants.back().first;
248 ResolveConstants.pop_back();
250 // Loop over all users of the placeholder, updating them to reference the
251 // new value. If they reference more than one placeholder, update them all
253 while (!Placeholder->use_empty()) {
254 Value::use_iterator UI = Placeholder->use_begin();
256 // If the using object isn't uniqued, just update the operands. This
257 // handles instructions and initializers for global variables.
258 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
259 UI.getUse().set(RealVal);
263 // Otherwise, we have a constant that uses the placeholder. Replace that
264 // constant with a new constant that has *all* placeholder uses updated.
265 Constant *UserC = cast<Constant>(*UI);
266 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
269 if (!isa<ConstantPlaceHolder>(*I)) {
270 // Not a placeholder reference.
272 } else if (*I == Placeholder) {
273 // Common case is that it just references this one placeholder.
276 // Otherwise, look up the placeholder in ResolveConstants.
277 ResolveConstantsTy::iterator It =
278 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
279 std::pair<Constant*, unsigned>(cast<Constant>(*I),
281 assert(It != ResolveConstants.end() && It->first == *I);
282 NewOp = operator[](It->second);
285 NewOps.push_back(cast<Constant>(NewOp));
288 // Make the new constant.
290 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
291 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
293 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
294 NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(),
295 UserCS->getType()->isPacked());
296 } else if (isa<ConstantVector>(UserC)) {
297 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
299 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
300 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
304 UserC->replaceAllUsesWith(NewC);
305 UserC->destroyConstant();
309 // Update all ValueHandles, they should be the only users at this point.
310 Placeholder->replaceAllUsesWith(RealVal);
315 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
324 WeakVH &OldV = MDValuePtrs[Idx];
330 // If there was a forward reference to this value, replace it.
331 Value *PrevVal = OldV;
332 OldV->replaceAllUsesWith(V);
334 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
336 MDValuePtrs[Idx] = V;
339 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
343 if (Value *V = MDValuePtrs[Idx]) {
344 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
348 // Create and return a placeholder, which will later be RAUW'd.
349 Value *V = new Argument(Type::getMetadataTy(Context));
350 MDValuePtrs[Idx] = V;
354 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
355 // If the TypeID is in range, return it.
356 if (ID < TypeList.size())
357 return TypeList[ID].get();
358 if (!isTypeTable) return 0;
360 // The type table allows forward references. Push as many Opaque types as
361 // needed to get up to ID.
362 while (TypeList.size() <= ID)
363 TypeList.push_back(OpaqueType::get(Context));
364 return TypeList.back().get();
367 //===----------------------------------------------------------------------===//
368 // Functions for parsing blocks from the bitcode file
369 //===----------------------------------------------------------------------===//
371 bool BitcodeReader::ParseAttributeBlock() {
372 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
373 return Error("Malformed block record");
375 if (!MAttributes.empty())
376 return Error("Multiple PARAMATTR blocks found!");
378 SmallVector<uint64_t, 64> Record;
380 SmallVector<AttributeWithIndex, 8> Attrs;
382 // Read all the records.
384 unsigned Code = Stream.ReadCode();
385 if (Code == bitc::END_BLOCK) {
386 if (Stream.ReadBlockEnd())
387 return Error("Error at end of PARAMATTR block");
391 if (Code == bitc::ENTER_SUBBLOCK) {
392 // No known subblocks, always skip them.
393 Stream.ReadSubBlockID();
394 if (Stream.SkipBlock())
395 return Error("Malformed block record");
399 if (Code == bitc::DEFINE_ABBREV) {
400 Stream.ReadAbbrevRecord();
406 switch (Stream.ReadRecord(Code, Record)) {
407 default: // Default behavior: ignore.
409 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
410 if (Record.size() & 1)
411 return Error("Invalid ENTRY record");
413 // FIXME : Remove this autoupgrade code in LLVM 3.0.
414 // If Function attributes are using index 0 then transfer them
415 // to index ~0. Index 0 is used for return value attributes but used to be
416 // used for function attributes.
417 Attributes RetAttribute = Attribute::None;
418 Attributes FnAttribute = Attribute::None;
419 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
420 // FIXME: remove in LLVM 3.0
421 // The alignment is stored as a 16-bit raw value from bits 31--16.
422 // We shift the bits above 31 down by 11 bits.
424 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
425 if (Alignment && !isPowerOf2_32(Alignment))
426 return Error("Alignment is not a power of two.");
428 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
430 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
431 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
432 Record[i+1] = ReconstitutedAttr;
435 RetAttribute = Record[i+1];
436 else if (Record[i] == ~0U)
437 FnAttribute = Record[i+1];
440 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
441 Attribute::ReadOnly|Attribute::ReadNone);
443 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
444 (RetAttribute & OldRetAttrs) != 0) {
445 if (FnAttribute == Attribute::None) { // add a slot so they get added.
446 Record.push_back(~0U);
450 FnAttribute |= RetAttribute & OldRetAttrs;
451 RetAttribute &= ~OldRetAttrs;
454 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
455 if (Record[i] == 0) {
456 if (RetAttribute != Attribute::None)
457 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
458 } else if (Record[i] == ~0U) {
459 if (FnAttribute != Attribute::None)
460 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
461 } else if (Record[i+1] != Attribute::None)
462 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
465 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
474 bool BitcodeReader::ParseTypeTable() {
475 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
476 return Error("Malformed block record");
478 if (!TypeList.empty())
479 return Error("Multiple TYPE_BLOCKs found!");
481 SmallVector<uint64_t, 64> Record;
482 unsigned NumRecords = 0;
484 // Read all the records for this type table.
486 unsigned Code = Stream.ReadCode();
487 if (Code == bitc::END_BLOCK) {
488 if (NumRecords != TypeList.size())
489 return Error("Invalid type forward reference in TYPE_BLOCK");
490 if (Stream.ReadBlockEnd())
491 return Error("Error at end of type table block");
495 if (Code == bitc::ENTER_SUBBLOCK) {
496 // No known subblocks, always skip them.
497 Stream.ReadSubBlockID();
498 if (Stream.SkipBlock())
499 return Error("Malformed block record");
503 if (Code == bitc::DEFINE_ABBREV) {
504 Stream.ReadAbbrevRecord();
510 const Type *ResultTy = 0;
511 switch (Stream.ReadRecord(Code, Record)) {
512 default: // Default behavior: unknown type.
515 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
516 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
517 // type list. This allows us to reserve space.
518 if (Record.size() < 1)
519 return Error("Invalid TYPE_CODE_NUMENTRY record");
520 TypeList.reserve(Record[0]);
522 case bitc::TYPE_CODE_VOID: // VOID
523 ResultTy = Type::getVoidTy(Context);
525 case bitc::TYPE_CODE_FLOAT: // FLOAT
526 ResultTy = Type::getFloatTy(Context);
528 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
529 ResultTy = Type::getDoubleTy(Context);
531 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
532 ResultTy = Type::getX86_FP80Ty(Context);
534 case bitc::TYPE_CODE_FP128: // FP128
535 ResultTy = Type::getFP128Ty(Context);
537 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
538 ResultTy = Type::getPPC_FP128Ty(Context);
540 case bitc::TYPE_CODE_LABEL: // LABEL
541 ResultTy = Type::getLabelTy(Context);
543 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
546 case bitc::TYPE_CODE_METADATA: // METADATA
547 ResultTy = Type::getMetadataTy(Context);
549 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
550 if (Record.size() < 1)
551 return Error("Invalid Integer type record");
553 ResultTy = IntegerType::get(Context, Record[0]);
555 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
556 // [pointee type, address space]
557 if (Record.size() < 1)
558 return Error("Invalid POINTER type record");
559 unsigned AddressSpace = 0;
560 if (Record.size() == 2)
561 AddressSpace = Record[1];
562 ResultTy = PointerType::get(getTypeByID(Record[0], true),
566 case bitc::TYPE_CODE_FUNCTION: {
567 // FIXME: attrid is dead, remove it in LLVM 3.0
568 // FUNCTION: [vararg, attrid, retty, paramty x N]
569 if (Record.size() < 3)
570 return Error("Invalid FUNCTION type record");
571 std::vector<const Type*> ArgTys;
572 for (unsigned i = 3, e = Record.size(); i != e; ++i)
573 ArgTys.push_back(getTypeByID(Record[i], true));
575 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
579 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
580 if (Record.size() < 1)
581 return Error("Invalid STRUCT type record");
582 std::vector<const Type*> EltTys;
583 for (unsigned i = 1, e = Record.size(); i != e; ++i)
584 EltTys.push_back(getTypeByID(Record[i], true));
585 ResultTy = StructType::get(Context, EltTys, Record[0]);
588 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
589 if (Record.size() < 2)
590 return Error("Invalid ARRAY type record");
591 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
593 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
594 if (Record.size() < 2)
595 return Error("Invalid VECTOR type record");
596 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
600 if (NumRecords == TypeList.size()) {
601 // If this is a new type slot, just append it.
602 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
604 } else if (ResultTy == 0) {
605 // Otherwise, this was forward referenced, so an opaque type was created,
606 // but the result type is actually just an opaque. Leave the one we
607 // created previously.
610 // Otherwise, this was forward referenced, so an opaque type was created.
611 // Resolve the opaque type to the real type now.
612 assert(NumRecords < TypeList.size() && "Typelist imbalance");
613 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
615 // Don't directly push the new type on the Tab. Instead we want to replace
616 // the opaque type we previously inserted with the new concrete value. The
617 // refinement from the abstract (opaque) type to the new type causes all
618 // uses of the abstract type to use the concrete type (NewTy). This will
619 // also cause the opaque type to be deleted.
620 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
622 // This should have replaced the old opaque type with the new type in the
623 // value table... or with a preexisting type that was already in the
624 // system. Let's just make sure it did.
625 assert(TypeList[NumRecords-1].get() != OldTy &&
626 "refineAbstractType didn't work!");
632 bool BitcodeReader::ParseTypeSymbolTable() {
633 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
634 return Error("Malformed block record");
636 SmallVector<uint64_t, 64> Record;
638 // Read all the records for this type table.
639 std::string TypeName;
641 unsigned Code = Stream.ReadCode();
642 if (Code == bitc::END_BLOCK) {
643 if (Stream.ReadBlockEnd())
644 return Error("Error at end of type symbol table block");
648 if (Code == bitc::ENTER_SUBBLOCK) {
649 // No known subblocks, always skip them.
650 Stream.ReadSubBlockID();
651 if (Stream.SkipBlock())
652 return Error("Malformed block record");
656 if (Code == bitc::DEFINE_ABBREV) {
657 Stream.ReadAbbrevRecord();
663 switch (Stream.ReadRecord(Code, Record)) {
664 default: // Default behavior: unknown type.
666 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
667 if (ConvertToString(Record, 1, TypeName))
668 return Error("Invalid TST_ENTRY record");
669 unsigned TypeID = Record[0];
670 if (TypeID >= TypeList.size())
671 return Error("Invalid Type ID in TST_ENTRY record");
673 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
680 bool BitcodeReader::ParseValueSymbolTable() {
681 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
682 return Error("Malformed block record");
684 SmallVector<uint64_t, 64> Record;
686 // Read all the records for this value table.
687 SmallString<128> ValueName;
689 unsigned Code = Stream.ReadCode();
690 if (Code == bitc::END_BLOCK) {
691 if (Stream.ReadBlockEnd())
692 return Error("Error at end of value symbol table block");
695 if (Code == bitc::ENTER_SUBBLOCK) {
696 // No known subblocks, always skip them.
697 Stream.ReadSubBlockID();
698 if (Stream.SkipBlock())
699 return Error("Malformed block record");
703 if (Code == bitc::DEFINE_ABBREV) {
704 Stream.ReadAbbrevRecord();
710 switch (Stream.ReadRecord(Code, Record)) {
711 default: // Default behavior: unknown type.
713 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
714 if (ConvertToString(Record, 1, ValueName))
715 return Error("Invalid VST_ENTRY record");
716 unsigned ValueID = Record[0];
717 if (ValueID >= ValueList.size())
718 return Error("Invalid Value ID in VST_ENTRY record");
719 Value *V = ValueList[ValueID];
721 V->setName(StringRef(ValueName.data(), ValueName.size()));
725 case bitc::VST_CODE_BBENTRY: {
726 if (ConvertToString(Record, 1, ValueName))
727 return Error("Invalid VST_BBENTRY record");
728 BasicBlock *BB = getBasicBlock(Record[0]);
730 return Error("Invalid BB ID in VST_BBENTRY record");
732 BB->setName(StringRef(ValueName.data(), ValueName.size()));
740 bool BitcodeReader::ParseMetadata() {
741 unsigned NextValueNo = MDValueList.size();
743 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
744 return Error("Malformed block record");
746 SmallVector<uint64_t, 64> Record;
748 // Read all the records.
750 unsigned Code = Stream.ReadCode();
751 if (Code == bitc::END_BLOCK) {
752 if (Stream.ReadBlockEnd())
753 return Error("Error at end of PARAMATTR block");
757 if (Code == bitc::ENTER_SUBBLOCK) {
758 // No known subblocks, always skip them.
759 Stream.ReadSubBlockID();
760 if (Stream.SkipBlock())
761 return Error("Malformed block record");
765 if (Code == bitc::DEFINE_ABBREV) {
766 Stream.ReadAbbrevRecord();
772 switch (Stream.ReadRecord(Code, Record)) {
773 default: // Default behavior: ignore.
775 case bitc::METADATA_NAME: {
776 // Read named of the named metadata.
777 unsigned NameLength = Record.size();
779 Name.resize(NameLength);
780 for (unsigned i = 0; i != NameLength; ++i)
783 Code = Stream.ReadCode();
785 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
786 if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
787 assert ( 0 && "Inavlid Named Metadata record");
789 // Read named metadata elements.
790 unsigned Size = Record.size();
791 SmallVector<MetadataBase*, 8> Elts;
792 for (unsigned i = 0; i != Size; ++i) {
793 Value *MD = MDValueList.getValueFwdRef(Record[i]);
794 if (MetadataBase *B = dyn_cast<MetadataBase>(MD))
797 Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(),
798 Elts.size(), TheModule);
799 MDValueList.AssignValue(V, NextValueNo++);
802 case bitc::METADATA_NODE: {
803 if (Record.empty() || Record.size() % 2 == 1)
804 return Error("Invalid METADATA_NODE record");
806 unsigned Size = Record.size();
807 SmallVector<Value*, 8> Elts;
808 for (unsigned i = 0; i != Size; i += 2) {
809 const Type *Ty = getTypeByID(Record[i], false);
810 if (Ty->isMetadataTy())
811 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
812 else if (Ty != Type::getVoidTy(Context))
813 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
815 Elts.push_back(NULL);
817 Value *V = MDNode::get(Context, &Elts[0], Elts.size());
818 MDValueList.AssignValue(V, NextValueNo++);
821 case bitc::METADATA_STRING: {
822 unsigned MDStringLength = Record.size();
823 SmallString<8> String;
824 String.resize(MDStringLength);
825 for (unsigned i = 0; i != MDStringLength; ++i)
826 String[i] = Record[i];
827 Value *V = MDString::get(Context,
828 StringRef(String.data(), String.size()));
829 MDValueList.AssignValue(V, NextValueNo++);
832 case bitc::METADATA_KIND: {
833 unsigned RecordLength = Record.size();
834 if (Record.empty() || RecordLength < 2)
835 return Error("Invalid METADATA_KIND record");
837 Name.resize(RecordLength-1);
838 unsigned Kind = Record[0];
840 for (unsigned i = 1; i != RecordLength; ++i)
841 Name[i-1] = Record[i];
843 unsigned NewKind = Context.getMetadata().getMDKindID(Name.str());
844 assert(Kind == NewKind &&
845 "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind;
852 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
853 /// the LSB for dense VBR encoding.
854 static uint64_t DecodeSignRotatedValue(uint64_t V) {
859 // There is no such thing as -0 with integers. "-0" really means MININT.
863 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
864 /// values and aliases that we can.
865 bool BitcodeReader::ResolveGlobalAndAliasInits() {
866 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
867 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
869 GlobalInitWorklist.swap(GlobalInits);
870 AliasInitWorklist.swap(AliasInits);
872 while (!GlobalInitWorklist.empty()) {
873 unsigned ValID = GlobalInitWorklist.back().second;
874 if (ValID >= ValueList.size()) {
875 // Not ready to resolve this yet, it requires something later in the file.
876 GlobalInits.push_back(GlobalInitWorklist.back());
878 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
879 GlobalInitWorklist.back().first->setInitializer(C);
881 return Error("Global variable initializer is not a constant!");
883 GlobalInitWorklist.pop_back();
886 while (!AliasInitWorklist.empty()) {
887 unsigned ValID = AliasInitWorklist.back().second;
888 if (ValID >= ValueList.size()) {
889 AliasInits.push_back(AliasInitWorklist.back());
891 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
892 AliasInitWorklist.back().first->setAliasee(C);
894 return Error("Alias initializer is not a constant!");
896 AliasInitWorklist.pop_back();
901 bool BitcodeReader::ParseConstants() {
902 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
903 return Error("Malformed block record");
905 SmallVector<uint64_t, 64> Record;
907 // Read all the records for this value table.
908 const Type *CurTy = Type::getInt32Ty(Context);
909 unsigned NextCstNo = ValueList.size();
911 unsigned Code = Stream.ReadCode();
912 if (Code == bitc::END_BLOCK)
915 if (Code == bitc::ENTER_SUBBLOCK) {
916 // No known subblocks, always skip them.
917 Stream.ReadSubBlockID();
918 if (Stream.SkipBlock())
919 return Error("Malformed block record");
923 if (Code == bitc::DEFINE_ABBREV) {
924 Stream.ReadAbbrevRecord();
931 unsigned BitCode = Stream.ReadRecord(Code, Record);
933 default: // Default behavior: unknown constant
934 case bitc::CST_CODE_UNDEF: // UNDEF
935 V = UndefValue::get(CurTy);
937 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
939 return Error("Malformed CST_SETTYPE record");
940 if (Record[0] >= TypeList.size())
941 return Error("Invalid Type ID in CST_SETTYPE record");
942 CurTy = TypeList[Record[0]];
943 continue; // Skip the ValueList manipulation.
944 case bitc::CST_CODE_NULL: // NULL
945 V = Constant::getNullValue(CurTy);
947 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
948 if (!isa<IntegerType>(CurTy) || Record.empty())
949 return Error("Invalid CST_INTEGER record");
950 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
952 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
953 if (!isa<IntegerType>(CurTy) || Record.empty())
954 return Error("Invalid WIDE_INTEGER record");
956 unsigned NumWords = Record.size();
957 SmallVector<uint64_t, 8> Words;
958 Words.resize(NumWords);
959 for (unsigned i = 0; i != NumWords; ++i)
960 Words[i] = DecodeSignRotatedValue(Record[i]);
961 V = ConstantInt::get(Context,
962 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
963 NumWords, &Words[0]));
966 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
968 return Error("Invalid FLOAT record");
969 if (CurTy->isFloatTy())
970 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
971 else if (CurTy->isDoubleTy())
972 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
973 else if (CurTy->isX86_FP80Ty()) {
974 // Bits are not stored the same way as a normal i80 APInt, compensate.
975 uint64_t Rearrange[2];
976 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
977 Rearrange[1] = Record[0] >> 48;
978 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
979 } else if (CurTy->isFP128Ty())
980 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
981 else if (CurTy->isPPC_FP128Ty())
982 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
984 V = UndefValue::get(CurTy);
988 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
990 return Error("Invalid CST_AGGREGATE record");
992 unsigned Size = Record.size();
993 std::vector<Constant*> Elts;
995 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
996 for (unsigned i = 0; i != Size; ++i)
997 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
998 STy->getElementType(i)));
999 V = ConstantStruct::get(STy, Elts);
1000 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1001 const Type *EltTy = ATy->getElementType();
1002 for (unsigned i = 0; i != Size; ++i)
1003 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1004 V = ConstantArray::get(ATy, Elts);
1005 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1006 const Type *EltTy = VTy->getElementType();
1007 for (unsigned i = 0; i != Size; ++i)
1008 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1009 V = ConstantVector::get(Elts);
1011 V = UndefValue::get(CurTy);
1015 case bitc::CST_CODE_STRING: { // STRING: [values]
1017 return Error("Invalid CST_AGGREGATE record");
1019 const ArrayType *ATy = cast<ArrayType>(CurTy);
1020 const Type *EltTy = ATy->getElementType();
1022 unsigned Size = Record.size();
1023 std::vector<Constant*> Elts;
1024 for (unsigned i = 0; i != Size; ++i)
1025 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1026 V = ConstantArray::get(ATy, Elts);
1029 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1031 return Error("Invalid CST_AGGREGATE record");
1033 const ArrayType *ATy = cast<ArrayType>(CurTy);
1034 const Type *EltTy = ATy->getElementType();
1036 unsigned Size = Record.size();
1037 std::vector<Constant*> Elts;
1038 for (unsigned i = 0; i != Size; ++i)
1039 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1040 Elts.push_back(Constant::getNullValue(EltTy));
1041 V = ConstantArray::get(ATy, Elts);
1044 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1045 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1046 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1048 V = UndefValue::get(CurTy); // Unknown binop.
1050 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1051 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1053 if (Record.size() >= 4) {
1054 if (Opc == Instruction::Add ||
1055 Opc == Instruction::Sub ||
1056 Opc == Instruction::Mul) {
1057 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1058 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1059 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1060 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1061 } else if (Opc == Instruction::SDiv) {
1062 if (Record[3] & (1 << bitc::SDIV_EXACT))
1063 Flags |= SDivOperator::IsExact;
1066 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1070 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1071 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1072 int Opc = GetDecodedCastOpcode(Record[0]);
1074 V = UndefValue::get(CurTy); // Unknown cast.
1076 const Type *OpTy = getTypeByID(Record[1]);
1077 if (!OpTy) return Error("Invalid CE_CAST record");
1078 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1079 V = ConstantExpr::getCast(Opc, Op, CurTy);
1083 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1084 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1085 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1086 SmallVector<Constant*, 16> Elts;
1087 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1088 const Type *ElTy = getTypeByID(Record[i]);
1089 if (!ElTy) return Error("Invalid CE_GEP record");
1090 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1092 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1093 V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
1096 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1100 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1101 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1102 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1103 Type::getInt1Ty(Context)),
1104 ValueList.getConstantFwdRef(Record[1],CurTy),
1105 ValueList.getConstantFwdRef(Record[2],CurTy));
1107 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1108 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1109 const VectorType *OpTy =
1110 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1111 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1112 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1113 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1114 V = ConstantExpr::getExtractElement(Op0, Op1);
1117 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1118 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1119 if (Record.size() < 3 || OpTy == 0)
1120 return Error("Invalid CE_INSERTELT record");
1121 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1122 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1123 OpTy->getElementType());
1124 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1125 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1128 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1129 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1130 if (Record.size() < 3 || OpTy == 0)
1131 return Error("Invalid CE_SHUFFLEVEC record");
1132 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1133 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1134 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1135 OpTy->getNumElements());
1136 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1137 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1140 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1141 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1142 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1143 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1144 return Error("Invalid CE_SHUFVEC_EX record");
1145 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1146 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1147 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1148 RTy->getNumElements());
1149 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1150 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1153 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1154 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1155 const Type *OpTy = getTypeByID(Record[0]);
1156 if (OpTy == 0) return Error("Invalid CE_CMP record");
1157 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1158 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1160 if (OpTy->isFloatingPoint())
1161 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1163 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1166 case bitc::CST_CODE_INLINEASM: {
1167 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1168 std::string AsmStr, ConstrStr;
1169 bool HasSideEffects = Record[0] & 1;
1170 bool IsAlignStack = Record[0] >> 1;
1171 unsigned AsmStrSize = Record[1];
1172 if (2+AsmStrSize >= Record.size())
1173 return Error("Invalid INLINEASM record");
1174 unsigned ConstStrSize = Record[2+AsmStrSize];
1175 if (3+AsmStrSize+ConstStrSize > Record.size())
1176 return Error("Invalid INLINEASM record");
1178 for (unsigned i = 0; i != AsmStrSize; ++i)
1179 AsmStr += (char)Record[2+i];
1180 for (unsigned i = 0; i != ConstStrSize; ++i)
1181 ConstrStr += (char)Record[3+AsmStrSize+i];
1182 const PointerType *PTy = cast<PointerType>(CurTy);
1183 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1184 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1187 case bitc::CST_CODE_BLOCKADDRESS:{
1188 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1189 const Type *FnTy = getTypeByID(Record[0]);
1190 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1192 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1193 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1195 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1196 Type::getInt8Ty(Context),
1197 false, GlobalValue::InternalLinkage,
1199 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1205 ValueList.AssignValue(V, NextCstNo);
1209 if (NextCstNo != ValueList.size())
1210 return Error("Invalid constant reference!");
1212 if (Stream.ReadBlockEnd())
1213 return Error("Error at end of constants block");
1215 // Once all the constants have been read, go through and resolve forward
1217 ValueList.ResolveConstantForwardRefs();
1221 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1222 /// remember where it is and then skip it. This lets us lazily deserialize the
1224 bool BitcodeReader::RememberAndSkipFunctionBody() {
1225 // Get the function we are talking about.
1226 if (FunctionsWithBodies.empty())
1227 return Error("Insufficient function protos");
1229 Function *Fn = FunctionsWithBodies.back();
1230 FunctionsWithBodies.pop_back();
1232 // Save the current stream state.
1233 uint64_t CurBit = Stream.GetCurrentBitNo();
1234 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1236 // Set the functions linkage to GhostLinkage so we know it is lazily
1238 Fn->setLinkage(GlobalValue::GhostLinkage);
1240 // Skip over the function block for now.
1241 if (Stream.SkipBlock())
1242 return Error("Malformed block record");
1246 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1247 // Reject multiple MODULE_BLOCK's in a single bitstream.
1249 return Error("Multiple MODULE_BLOCKs in same stream");
1251 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1252 return Error("Malformed block record");
1254 // Otherwise, create the module.
1255 TheModule = new Module(ModuleID, Context);
1257 SmallVector<uint64_t, 64> Record;
1258 std::vector<std::string> SectionTable;
1259 std::vector<std::string> GCTable;
1261 // Read all the records for this module.
1262 while (!Stream.AtEndOfStream()) {
1263 unsigned Code = Stream.ReadCode();
1264 if (Code == bitc::END_BLOCK) {
1265 if (Stream.ReadBlockEnd())
1266 return Error("Error at end of module block");
1268 // Patch the initializers for globals and aliases up.
1269 ResolveGlobalAndAliasInits();
1270 if (!GlobalInits.empty() || !AliasInits.empty())
1271 return Error("Malformed global initializer set");
1272 if (!FunctionsWithBodies.empty())
1273 return Error("Too few function bodies found");
1275 // Look for intrinsic functions which need to be upgraded at some point
1276 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1279 if (UpgradeIntrinsicFunction(FI, NewFn))
1280 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1283 // Force deallocation of memory for these vectors to favor the client that
1284 // want lazy deserialization.
1285 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1286 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1287 std::vector<Function*>().swap(FunctionsWithBodies);
1291 if (Code == bitc::ENTER_SUBBLOCK) {
1292 switch (Stream.ReadSubBlockID()) {
1293 default: // Skip unknown content.
1294 if (Stream.SkipBlock())
1295 return Error("Malformed block record");
1297 case bitc::BLOCKINFO_BLOCK_ID:
1298 if (Stream.ReadBlockInfoBlock())
1299 return Error("Malformed BlockInfoBlock");
1301 case bitc::PARAMATTR_BLOCK_ID:
1302 if (ParseAttributeBlock())
1305 case bitc::TYPE_BLOCK_ID:
1306 if (ParseTypeTable())
1309 case bitc::TYPE_SYMTAB_BLOCK_ID:
1310 if (ParseTypeSymbolTable())
1313 case bitc::VALUE_SYMTAB_BLOCK_ID:
1314 if (ParseValueSymbolTable())
1317 case bitc::CONSTANTS_BLOCK_ID:
1318 if (ParseConstants() || ResolveGlobalAndAliasInits())
1321 case bitc::METADATA_BLOCK_ID:
1322 if (ParseMetadata())
1325 case bitc::FUNCTION_BLOCK_ID:
1326 // If this is the first function body we've seen, reverse the
1327 // FunctionsWithBodies list.
1328 if (!HasReversedFunctionsWithBodies) {
1329 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1330 HasReversedFunctionsWithBodies = true;
1333 if (RememberAndSkipFunctionBody())
1340 if (Code == bitc::DEFINE_ABBREV) {
1341 Stream.ReadAbbrevRecord();
1346 switch (Stream.ReadRecord(Code, Record)) {
1347 default: break; // Default behavior, ignore unknown content.
1348 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1349 if (Record.size() < 1)
1350 return Error("Malformed MODULE_CODE_VERSION");
1351 // Only version #0 is supported so far.
1353 return Error("Unknown bitstream version!");
1355 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1357 if (ConvertToString(Record, 0, S))
1358 return Error("Invalid MODULE_CODE_TRIPLE record");
1359 TheModule->setTargetTriple(S);
1362 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1364 if (ConvertToString(Record, 0, S))
1365 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1366 TheModule->setDataLayout(S);
1369 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1371 if (ConvertToString(Record, 0, S))
1372 return Error("Invalid MODULE_CODE_ASM record");
1373 TheModule->setModuleInlineAsm(S);
1376 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1378 if (ConvertToString(Record, 0, S))
1379 return Error("Invalid MODULE_CODE_DEPLIB record");
1380 TheModule->addLibrary(S);
1383 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1385 if (ConvertToString(Record, 0, S))
1386 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1387 SectionTable.push_back(S);
1390 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1392 if (ConvertToString(Record, 0, S))
1393 return Error("Invalid MODULE_CODE_GCNAME record");
1394 GCTable.push_back(S);
1397 // GLOBALVAR: [pointer type, isconst, initid,
1398 // linkage, alignment, section, visibility, threadlocal]
1399 case bitc::MODULE_CODE_GLOBALVAR: {
1400 if (Record.size() < 6)
1401 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1402 const Type *Ty = getTypeByID(Record[0]);
1403 if (!isa<PointerType>(Ty))
1404 return Error("Global not a pointer type!");
1405 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1406 Ty = cast<PointerType>(Ty)->getElementType();
1408 bool isConstant = Record[1];
1409 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1410 unsigned Alignment = (1 << Record[4]) >> 1;
1411 std::string Section;
1413 if (Record[5]-1 >= SectionTable.size())
1414 return Error("Invalid section ID");
1415 Section = SectionTable[Record[5]-1];
1417 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1418 if (Record.size() > 6)
1419 Visibility = GetDecodedVisibility(Record[6]);
1420 bool isThreadLocal = false;
1421 if (Record.size() > 7)
1422 isThreadLocal = Record[7];
1424 GlobalVariable *NewGV =
1425 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1426 isThreadLocal, AddressSpace);
1427 NewGV->setAlignment(Alignment);
1428 if (!Section.empty())
1429 NewGV->setSection(Section);
1430 NewGV->setVisibility(Visibility);
1431 NewGV->setThreadLocal(isThreadLocal);
1433 ValueList.push_back(NewGV);
1435 // Remember which value to use for the global initializer.
1436 if (unsigned InitID = Record[2])
1437 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1440 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1441 // alignment, section, visibility, gc]
1442 case bitc::MODULE_CODE_FUNCTION: {
1443 if (Record.size() < 8)
1444 return Error("Invalid MODULE_CODE_FUNCTION record");
1445 const Type *Ty = getTypeByID(Record[0]);
1446 if (!isa<PointerType>(Ty))
1447 return Error("Function not a pointer type!");
1448 const FunctionType *FTy =
1449 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1451 return Error("Function not a pointer to function type!");
1453 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1456 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1457 bool isProto = Record[2];
1458 Func->setLinkage(GetDecodedLinkage(Record[3]));
1459 Func->setAttributes(getAttributes(Record[4]));
1461 Func->setAlignment((1 << Record[5]) >> 1);
1463 if (Record[6]-1 >= SectionTable.size())
1464 return Error("Invalid section ID");
1465 Func->setSection(SectionTable[Record[6]-1]);
1467 Func->setVisibility(GetDecodedVisibility(Record[7]));
1468 if (Record.size() > 8 && Record[8]) {
1469 if (Record[8]-1 > GCTable.size())
1470 return Error("Invalid GC ID");
1471 Func->setGC(GCTable[Record[8]-1].c_str());
1473 ValueList.push_back(Func);
1475 // If this is a function with a body, remember the prototype we are
1476 // creating now, so that we can match up the body with them later.
1478 FunctionsWithBodies.push_back(Func);
1481 // ALIAS: [alias type, aliasee val#, linkage]
1482 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1483 case bitc::MODULE_CODE_ALIAS: {
1484 if (Record.size() < 3)
1485 return Error("Invalid MODULE_ALIAS record");
1486 const Type *Ty = getTypeByID(Record[0]);
1487 if (!isa<PointerType>(Ty))
1488 return Error("Function not a pointer type!");
1490 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1492 // Old bitcode files didn't have visibility field.
1493 if (Record.size() > 3)
1494 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1495 ValueList.push_back(NewGA);
1496 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1499 /// MODULE_CODE_PURGEVALS: [numvals]
1500 case bitc::MODULE_CODE_PURGEVALS:
1501 // Trim down the value list to the specified size.
1502 if (Record.size() < 1 || Record[0] > ValueList.size())
1503 return Error("Invalid MODULE_PURGEVALS record");
1504 ValueList.shrinkTo(Record[0]);
1510 return Error("Premature end of bitstream");
1513 bool BitcodeReader::ParseBitcode() {
1516 if (Buffer->getBufferSize() & 3)
1517 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1519 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1520 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1522 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1523 // The magic number is 0x0B17C0DE stored in little endian.
1524 if (isBitcodeWrapper(BufPtr, BufEnd))
1525 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1526 return Error("Invalid bitcode wrapper header");
1528 StreamFile.init(BufPtr, BufEnd);
1529 Stream.init(StreamFile);
1531 // Sniff for the signature.
1532 if (Stream.Read(8) != 'B' ||
1533 Stream.Read(8) != 'C' ||
1534 Stream.Read(4) != 0x0 ||
1535 Stream.Read(4) != 0xC ||
1536 Stream.Read(4) != 0xE ||
1537 Stream.Read(4) != 0xD)
1538 return Error("Invalid bitcode signature");
1540 // We expect a number of well-defined blocks, though we don't necessarily
1541 // need to understand them all.
1542 while (!Stream.AtEndOfStream()) {
1543 unsigned Code = Stream.ReadCode();
1545 if (Code != bitc::ENTER_SUBBLOCK)
1546 return Error("Invalid record at top-level");
1548 unsigned BlockID = Stream.ReadSubBlockID();
1550 // We only know the MODULE subblock ID.
1552 case bitc::BLOCKINFO_BLOCK_ID:
1553 if (Stream.ReadBlockInfoBlock())
1554 return Error("Malformed BlockInfoBlock");
1556 case bitc::MODULE_BLOCK_ID:
1557 if (ParseModule(Buffer->getBufferIdentifier()))
1561 if (Stream.SkipBlock())
1562 return Error("Malformed block record");
1570 /// ParseMetadataAttachment - Parse metadata attachments.
1571 bool BitcodeReader::ParseMetadataAttachment() {
1572 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1573 return Error("Malformed block record");
1575 SmallVector<uint64_t, 64> Record;
1577 unsigned Code = Stream.ReadCode();
1578 if (Code == bitc::END_BLOCK) {
1579 if (Stream.ReadBlockEnd())
1580 return Error("Error at end of PARAMATTR block");
1583 if (Code == bitc::DEFINE_ABBREV) {
1584 Stream.ReadAbbrevRecord();
1587 // Read a metadata attachment record.
1589 switch (Stream.ReadRecord(Code, Record)) {
1590 default: // Default behavior: ignore.
1592 case bitc::METADATA_ATTACHMENT: {
1593 unsigned RecordLength = Record.size();
1594 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1595 return Error ("Invalid METADATA_ATTACHMENT reader!");
1596 Instruction *Inst = InstructionList[Record[0]];
1597 for (unsigned i = 1; i != RecordLength; i = i+2) {
1598 unsigned Kind = Record[i];
1599 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1600 Inst->setMetadata(Kind, cast<MDNode>(Node));
1609 /// ParseFunctionBody - Lazily parse the specified function body block.
1610 bool BitcodeReader::ParseFunctionBody(Function *F) {
1611 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1612 return Error("Malformed block record");
1614 unsigned ModuleValueListSize = ValueList.size();
1616 // Add all the function arguments to the value table.
1617 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1618 ValueList.push_back(I);
1620 unsigned NextValueNo = ValueList.size();
1621 BasicBlock *CurBB = 0;
1622 unsigned CurBBNo = 0;
1624 // Read all the records.
1625 SmallVector<uint64_t, 64> Record;
1627 unsigned Code = Stream.ReadCode();
1628 if (Code == bitc::END_BLOCK) {
1629 if (Stream.ReadBlockEnd())
1630 return Error("Error at end of function block");
1634 if (Code == bitc::ENTER_SUBBLOCK) {
1635 switch (Stream.ReadSubBlockID()) {
1636 default: // Skip unknown content.
1637 if (Stream.SkipBlock())
1638 return Error("Malformed block record");
1640 case bitc::CONSTANTS_BLOCK_ID:
1641 if (ParseConstants()) return true;
1642 NextValueNo = ValueList.size();
1644 case bitc::VALUE_SYMTAB_BLOCK_ID:
1645 if (ParseValueSymbolTable()) return true;
1647 case bitc::METADATA_ATTACHMENT_ID:
1648 if (ParseMetadataAttachment()) return true;
1654 if (Code == bitc::DEFINE_ABBREV) {
1655 Stream.ReadAbbrevRecord();
1662 unsigned BitCode = Stream.ReadRecord(Code, Record);
1664 default: // Default behavior: reject
1665 return Error("Unknown instruction");
1666 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1667 if (Record.size() < 1 || Record[0] == 0)
1668 return Error("Invalid DECLAREBLOCKS record");
1669 // Create all the basic blocks for the function.
1670 FunctionBBs.resize(Record[0]);
1671 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1672 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1673 CurBB = FunctionBBs[0];
1676 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1679 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1680 getValue(Record, OpNum, LHS->getType(), RHS) ||
1681 OpNum+1 > Record.size())
1682 return Error("Invalid BINOP record");
1684 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1685 if (Opc == -1) return Error("Invalid BINOP record");
1686 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1687 InstructionList.push_back(I);
1688 if (OpNum < Record.size()) {
1689 if (Opc == Instruction::Add ||
1690 Opc == Instruction::Sub ||
1691 Opc == Instruction::Mul) {
1692 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1693 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1694 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1695 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1696 } else if (Opc == Instruction::SDiv) {
1697 if (Record[3] & (1 << bitc::SDIV_EXACT))
1698 cast<BinaryOperator>(I)->setIsExact(true);
1703 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1706 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1707 OpNum+2 != Record.size())
1708 return Error("Invalid CAST record");
1710 const Type *ResTy = getTypeByID(Record[OpNum]);
1711 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1712 if (Opc == -1 || ResTy == 0)
1713 return Error("Invalid CAST record");
1714 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1715 InstructionList.push_back(I);
1718 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1719 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1722 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1723 return Error("Invalid GEP record");
1725 SmallVector<Value*, 16> GEPIdx;
1726 while (OpNum != Record.size()) {
1728 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1729 return Error("Invalid GEP record");
1730 GEPIdx.push_back(Op);
1733 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1734 InstructionList.push_back(I);
1735 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1736 cast<GetElementPtrInst>(I)->setIsInBounds(true);
1740 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1741 // EXTRACTVAL: [opty, opval, n x indices]
1744 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1745 return Error("Invalid EXTRACTVAL record");
1747 SmallVector<unsigned, 4> EXTRACTVALIdx;
1748 for (unsigned RecSize = Record.size();
1749 OpNum != RecSize; ++OpNum) {
1750 uint64_t Index = Record[OpNum];
1751 if ((unsigned)Index != Index)
1752 return Error("Invalid EXTRACTVAL index");
1753 EXTRACTVALIdx.push_back((unsigned)Index);
1756 I = ExtractValueInst::Create(Agg,
1757 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1758 InstructionList.push_back(I);
1762 case bitc::FUNC_CODE_INST_INSERTVAL: {
1763 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1766 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1767 return Error("Invalid INSERTVAL record");
1769 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1770 return Error("Invalid INSERTVAL record");
1772 SmallVector<unsigned, 4> INSERTVALIdx;
1773 for (unsigned RecSize = Record.size();
1774 OpNum != RecSize; ++OpNum) {
1775 uint64_t Index = Record[OpNum];
1776 if ((unsigned)Index != Index)
1777 return Error("Invalid INSERTVAL index");
1778 INSERTVALIdx.push_back((unsigned)Index);
1781 I = InsertValueInst::Create(Agg, Val,
1782 INSERTVALIdx.begin(), INSERTVALIdx.end());
1783 InstructionList.push_back(I);
1787 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1788 // obsolete form of select
1789 // handles select i1 ... in old bitcode
1791 Value *TrueVal, *FalseVal, *Cond;
1792 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1793 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1794 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
1795 return Error("Invalid SELECT record");
1797 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1798 InstructionList.push_back(I);
1802 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1803 // new form of select
1804 // handles select i1 or select [N x i1]
1806 Value *TrueVal, *FalseVal, *Cond;
1807 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1808 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1809 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1810 return Error("Invalid SELECT record");
1812 // select condition can be either i1 or [N x i1]
1813 if (const VectorType* vector_type =
1814 dyn_cast<const VectorType>(Cond->getType())) {
1816 if (vector_type->getElementType() != Type::getInt1Ty(Context))
1817 return Error("Invalid SELECT condition type");
1820 if (Cond->getType() != Type::getInt1Ty(Context))
1821 return Error("Invalid SELECT condition type");
1824 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1825 InstructionList.push_back(I);
1829 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1832 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1833 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
1834 return Error("Invalid EXTRACTELT record");
1835 I = ExtractElementInst::Create(Vec, Idx);
1836 InstructionList.push_back(I);
1840 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1842 Value *Vec, *Elt, *Idx;
1843 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1844 getValue(Record, OpNum,
1845 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1846 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
1847 return Error("Invalid INSERTELT record");
1848 I = InsertElementInst::Create(Vec, Elt, Idx);
1849 InstructionList.push_back(I);
1853 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1855 Value *Vec1, *Vec2, *Mask;
1856 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1857 getValue(Record, OpNum, Vec1->getType(), Vec2))
1858 return Error("Invalid SHUFFLEVEC record");
1860 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1861 return Error("Invalid SHUFFLEVEC record");
1862 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1863 InstructionList.push_back(I);
1867 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1868 // Old form of ICmp/FCmp returning bool
1869 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1870 // both legal on vectors but had different behaviour.
1871 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1872 // FCmp/ICmp returning bool or vector of bool
1876 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1877 getValue(Record, OpNum, LHS->getType(), RHS) ||
1878 OpNum+1 != Record.size())
1879 return Error("Invalid CMP record");
1881 if (LHS->getType()->isFPOrFPVector())
1882 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1884 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1885 InstructionList.push_back(I);
1889 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1890 if (Record.size() != 2)
1891 return Error("Invalid GETRESULT record");
1894 getValueTypePair(Record, OpNum, NextValueNo, Op);
1895 unsigned Index = Record[1];
1896 I = ExtractValueInst::Create(Op, Index);
1897 InstructionList.push_back(I);
1901 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1903 unsigned Size = Record.size();
1905 I = ReturnInst::Create(Context);
1906 InstructionList.push_back(I);
1911 SmallVector<Value *,4> Vs;
1914 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1915 return Error("Invalid RET record");
1917 } while(OpNum != Record.size());
1919 const Type *ReturnType = F->getReturnType();
1920 if (Vs.size() > 1 ||
1921 (isa<StructType>(ReturnType) &&
1922 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1923 Value *RV = UndefValue::get(ReturnType);
1924 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1925 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1926 InstructionList.push_back(I);
1927 CurBB->getInstList().push_back(I);
1928 ValueList.AssignValue(I, NextValueNo++);
1931 I = ReturnInst::Create(Context, RV);
1932 InstructionList.push_back(I);
1936 I = ReturnInst::Create(Context, Vs[0]);
1937 InstructionList.push_back(I);
1940 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1941 if (Record.size() != 1 && Record.size() != 3)
1942 return Error("Invalid BR record");
1943 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1945 return Error("Invalid BR record");
1947 if (Record.size() == 1) {
1948 I = BranchInst::Create(TrueDest);
1949 InstructionList.push_back(I);
1952 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1953 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
1954 if (FalseDest == 0 || Cond == 0)
1955 return Error("Invalid BR record");
1956 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1957 InstructionList.push_back(I);
1961 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
1962 if (Record.size() < 3 || (Record.size() & 1) == 0)
1963 return Error("Invalid SWITCH record");
1964 const Type *OpTy = getTypeByID(Record[0]);
1965 Value *Cond = getFnValueByID(Record[1], OpTy);
1966 BasicBlock *Default = getBasicBlock(Record[2]);
1967 if (OpTy == 0 || Cond == 0 || Default == 0)
1968 return Error("Invalid SWITCH record");
1969 unsigned NumCases = (Record.size()-3)/2;
1970 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1971 InstructionList.push_back(SI);
1972 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1973 ConstantInt *CaseVal =
1974 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1975 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1976 if (CaseVal == 0 || DestBB == 0) {
1978 return Error("Invalid SWITCH record!");
1980 SI->addCase(CaseVal, DestBB);
1985 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
1986 if (Record.size() < 2)
1987 return Error("Invalid INDIRECTBR record");
1988 const Type *OpTy = getTypeByID(Record[0]);
1989 Value *Address = getFnValueByID(Record[1], OpTy);
1990 if (OpTy == 0 || Address == 0)
1991 return Error("Invalid INDIRECTBR record");
1992 unsigned NumDests = Record.size()-2;
1993 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
1994 InstructionList.push_back(IBI);
1995 for (unsigned i = 0, e = NumDests; i != e; ++i) {
1996 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
1997 IBI->addDestination(DestBB);
2000 return Error("Invalid INDIRECTBR record!");
2007 case bitc::FUNC_CODE_INST_INVOKE: {
2008 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2009 if (Record.size() < 4) return Error("Invalid INVOKE record");
2010 AttrListPtr PAL = getAttributes(Record[0]);
2011 unsigned CCInfo = Record[1];
2012 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2013 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2017 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2018 return Error("Invalid INVOKE record");
2020 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2021 const FunctionType *FTy = !CalleeTy ? 0 :
2022 dyn_cast<FunctionType>(CalleeTy->getElementType());
2024 // Check that the right number of fixed parameters are here.
2025 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2026 Record.size() < OpNum+FTy->getNumParams())
2027 return Error("Invalid INVOKE record");
2029 SmallVector<Value*, 16> Ops;
2030 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2031 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2032 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2035 if (!FTy->isVarArg()) {
2036 if (Record.size() != OpNum)
2037 return Error("Invalid INVOKE record");
2039 // Read type/value pairs for varargs params.
2040 while (OpNum != Record.size()) {
2042 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2043 return Error("Invalid INVOKE record");
2048 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
2049 Ops.begin(), Ops.end());
2050 InstructionList.push_back(I);
2051 cast<InvokeInst>(I)->setCallingConv(
2052 static_cast<CallingConv::ID>(CCInfo));
2053 cast<InvokeInst>(I)->setAttributes(PAL);
2056 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2057 I = new UnwindInst(Context);
2058 InstructionList.push_back(I);
2060 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2061 I = new UnreachableInst(Context);
2062 InstructionList.push_back(I);
2064 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2065 if (Record.size() < 1 || ((Record.size()-1)&1))
2066 return Error("Invalid PHI record");
2067 const Type *Ty = getTypeByID(Record[0]);
2068 if (!Ty) return Error("Invalid PHI record");
2070 PHINode *PN = PHINode::Create(Ty);
2071 InstructionList.push_back(PN);
2072 PN->reserveOperandSpace((Record.size()-1)/2);
2074 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2075 Value *V = getFnValueByID(Record[1+i], Ty);
2076 BasicBlock *BB = getBasicBlock(Record[2+i]);
2077 if (!V || !BB) return Error("Invalid PHI record");
2078 PN->addIncoming(V, BB);
2084 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
2085 // Autoupgrade malloc instruction to malloc call.
2086 // FIXME: Remove in LLVM 3.0.
2087 if (Record.size() < 3)
2088 return Error("Invalid MALLOC record");
2089 const PointerType *Ty =
2090 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2091 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
2092 if (!Ty || !Size) return Error("Invalid MALLOC record");
2093 if (!CurBB) return Error("Invalid malloc instruction with no BB");
2094 const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
2095 Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
2096 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
2097 I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
2098 AllocSize, Size, NULL);
2099 InstructionList.push_back(I);
2102 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
2105 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2106 OpNum != Record.size())
2107 return Error("Invalid FREE record");
2108 if (!CurBB) return Error("Invalid free instruction with no BB");
2109 I = CallInst::CreateFree(Op, CurBB);
2110 InstructionList.push_back(I);
2113 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
2114 if (Record.size() < 3)
2115 return Error("Invalid ALLOCA record");
2116 const PointerType *Ty =
2117 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2118 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
2119 unsigned Align = Record[2];
2120 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2121 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2122 InstructionList.push_back(I);
2125 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2128 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2129 OpNum+2 != Record.size())
2130 return Error("Invalid LOAD record");
2132 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2133 InstructionList.push_back(I);
2136 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
2139 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2140 getValue(Record, OpNum,
2141 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2142 OpNum+2 != Record.size())
2143 return Error("Invalid STORE record");
2145 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2146 InstructionList.push_back(I);
2149 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
2150 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
2153 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
2154 getValue(Record, OpNum,
2155 PointerType::getUnqual(Val->getType()), Ptr)||
2156 OpNum+2 != Record.size())
2157 return Error("Invalid STORE record");
2159 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2160 InstructionList.push_back(I);
2163 case bitc::FUNC_CODE_INST_CALL: {
2164 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2165 if (Record.size() < 3)
2166 return Error("Invalid CALL record");
2168 AttrListPtr PAL = getAttributes(Record[0]);
2169 unsigned CCInfo = Record[1];
2173 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2174 return Error("Invalid CALL record");
2176 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2177 const FunctionType *FTy = 0;
2178 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2179 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2180 return Error("Invalid CALL record");
2182 SmallVector<Value*, 16> Args;
2183 // Read the fixed params.
2184 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2185 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2186 Args.push_back(getBasicBlock(Record[OpNum]));
2188 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2189 if (Args.back() == 0) return Error("Invalid CALL record");
2192 // Read type/value pairs for varargs params.
2193 if (!FTy->isVarArg()) {
2194 if (OpNum != Record.size())
2195 return Error("Invalid CALL record");
2197 while (OpNum != Record.size()) {
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2200 return Error("Invalid CALL record");
2205 I = CallInst::Create(Callee, Args.begin(), Args.end());
2206 InstructionList.push_back(I);
2207 cast<CallInst>(I)->setCallingConv(
2208 static_cast<CallingConv::ID>(CCInfo>>1));
2209 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2210 cast<CallInst>(I)->setAttributes(PAL);
2213 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2214 if (Record.size() < 3)
2215 return Error("Invalid VAARG record");
2216 const Type *OpTy = getTypeByID(Record[0]);
2217 Value *Op = getFnValueByID(Record[1], OpTy);
2218 const Type *ResTy = getTypeByID(Record[2]);
2219 if (!OpTy || !Op || !ResTy)
2220 return Error("Invalid VAARG record");
2221 I = new VAArgInst(Op, ResTy);
2222 InstructionList.push_back(I);
2227 // Add instruction to end of current BB. If there is no current BB, reject
2231 return Error("Invalid instruction with no BB");
2233 CurBB->getInstList().push_back(I);
2235 // If this was a terminator instruction, move to the next block.
2236 if (isa<TerminatorInst>(I)) {
2238 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2241 // Non-void values get registered in the value table for future use.
2242 if (I && I->getType() != Type::getVoidTy(Context))
2243 ValueList.AssignValue(I, NextValueNo++);
2246 // Check the function list for unresolved values.
2247 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2248 if (A->getParent() == 0) {
2249 // We found at least one unresolved value. Nuke them all to avoid leaks.
2250 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2251 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
2252 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2256 return Error("Never resolved value found in function!");
2260 // See if anything took the address of blocks in this function. If so,
2261 // resolve them now.
2262 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
2263 /// are resolved lazily when functions are loaded.
2264 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2265 BlockAddrFwdRefs.find(F);
2266 if (BAFRI != BlockAddrFwdRefs.end()) {
2267 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2268 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2269 unsigned BlockIdx = RefList[i].first;
2270 if (BlockIdx >= FunctionBBs.size())
2271 return Error("Invalid blockaddress block #");
2273 GlobalVariable *FwdRef = RefList[i].second;
2274 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2275 FwdRef->eraseFromParent();
2278 BlockAddrFwdRefs.erase(BAFRI);
2281 // Trim the value list down to the size it was before we parsed this function.
2282 ValueList.shrinkTo(ModuleValueListSize);
2283 std::vector<BasicBlock*>().swap(FunctionBBs);
2288 //===----------------------------------------------------------------------===//
2289 // ModuleProvider implementation
2290 //===----------------------------------------------------------------------===//
2293 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2294 // If it already is material, ignore the request.
2295 if (!F->hasNotBeenReadFromBitcode()) return false;
2297 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2298 DeferredFunctionInfo.find(F);
2299 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2301 // Move the bit stream to the saved position of the deferred function body and
2302 // restore the real linkage type for the function.
2303 Stream.JumpToBit(DFII->second.first);
2304 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2306 if (ParseFunctionBody(F)) {
2307 if (ErrInfo) *ErrInfo = ErrorString;
2311 // Upgrade any old intrinsic calls in the function.
2312 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2313 E = UpgradedIntrinsics.end(); I != E; ++I) {
2314 if (I->first != I->second) {
2315 for (Value::use_iterator UI = I->first->use_begin(),
2316 UE = I->first->use_end(); UI != UE; ) {
2317 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2318 UpgradeIntrinsicCall(CI, I->second);
2326 void BitcodeReader::dematerializeFunction(Function *F) {
2327 // If this function isn't materialized, or if it is a proto, this is a noop.
2328 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2331 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2333 // Just forget the function body, we can remat it later.
2335 F->setLinkage(GlobalValue::GhostLinkage);
2339 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2340 // Iterate over the module, deserializing any functions that are still on
2342 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2344 if (F->hasNotBeenReadFromBitcode() &&
2345 materializeFunction(F, ErrInfo))
2348 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2349 // delete the old functions to clean up. We can't do this unless the entire
2350 // module is materialized because there could always be another function body
2351 // with calls to the old function.
2352 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2353 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2354 if (I->first != I->second) {
2355 for (Value::use_iterator UI = I->first->use_begin(),
2356 UE = I->first->use_end(); UI != UE; ) {
2357 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2358 UpgradeIntrinsicCall(CI, I->second);
2360 if (!I->first->use_empty())
2361 I->first->replaceAllUsesWith(I->second);
2362 I->first->eraseFromParent();
2365 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2367 // Check debug info intrinsics.
2368 CheckDebugInfoIntrinsics(TheModule);
2374 /// This method is provided by the parent ModuleProvde class and overriden
2375 /// here. It simply releases the module from its provided and frees up our
2377 /// @brief Release our hold on the generated module
2378 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2379 // Since we're losing control of this Module, we must hand it back complete
2380 Module *M = ModuleProvider::releaseModule(ErrInfo);
2386 //===----------------------------------------------------------------------===//
2387 // External interface
2388 //===----------------------------------------------------------------------===//
2390 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2392 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2393 LLVMContext& Context,
2394 std::string *ErrMsg) {
2395 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2396 if (R->ParseBitcode()) {
2398 *ErrMsg = R->getErrorString();
2400 // Don't let the BitcodeReader dtor delete 'Buffer'.
2401 R->releaseMemoryBuffer();
2408 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2409 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2410 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2411 std::string *ErrMsg){
2413 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2417 // Read in the entire module.
2418 Module *M = R->materializeModule(ErrMsg);
2420 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2421 // there was an error.
2422 R->releaseMemoryBuffer();
2424 // If there was no error, tell ModuleProvider not to delete it when its dtor
2427 M = R->releaseModule(ErrMsg);