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/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/OperandTraits.h"
29 void BitcodeReader::FreeState() {
32 std::vector<PATypeHolder>().swap(TypeList);
35 std::vector<AttrListPtr>().swap(MAttributes);
36 std::vector<BasicBlock*>().swap(FunctionBBs);
37 std::vector<Function*>().swap(FunctionsWithBodies);
38 DeferredFunctionInfo.clear();
41 //===----------------------------------------------------------------------===//
42 // Helper functions to implement forward reference resolution, etc.
43 //===----------------------------------------------------------------------===//
45 /// ConvertToString - Convert a string from a record into an std::string, return
47 template<typename StrTy>
48 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
50 if (Idx > Record.size())
53 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54 Result += (char)Record[i];
58 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
60 default: // Map unknown/new linkages to external
61 case 0: return GlobalValue::ExternalLinkage;
62 case 1: return GlobalValue::WeakAnyLinkage;
63 case 2: return GlobalValue::AppendingLinkage;
64 case 3: return GlobalValue::InternalLinkage;
65 case 4: return GlobalValue::LinkOnceAnyLinkage;
66 case 5: return GlobalValue::DLLImportLinkage;
67 case 6: return GlobalValue::DLLExportLinkage;
68 case 7: return GlobalValue::ExternalWeakLinkage;
69 case 8: return GlobalValue::CommonLinkage;
70 case 9: return GlobalValue::PrivateLinkage;
71 case 10: return GlobalValue::WeakODRLinkage;
72 case 11: return GlobalValue::LinkOnceODRLinkage;
76 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
78 default: // Map unknown visibilities to default.
79 case 0: return GlobalValue::DefaultVisibility;
80 case 1: return GlobalValue::HiddenVisibility;
81 case 2: return GlobalValue::ProtectedVisibility;
85 static int GetDecodedCastOpcode(unsigned Val) {
88 case bitc::CAST_TRUNC : return Instruction::Trunc;
89 case bitc::CAST_ZEXT : return Instruction::ZExt;
90 case bitc::CAST_SEXT : return Instruction::SExt;
91 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
92 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
93 case bitc::CAST_UITOFP : return Instruction::UIToFP;
94 case bitc::CAST_SITOFP : return Instruction::SIToFP;
95 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
96 case bitc::CAST_FPEXT : return Instruction::FPExt;
97 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
98 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
99 case bitc::CAST_BITCAST : return Instruction::BitCast;
102 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
105 case bitc::BINOP_ADD: return Instruction::Add;
106 case bitc::BINOP_SUB: return Instruction::Sub;
107 case bitc::BINOP_MUL: return Instruction::Mul;
108 case bitc::BINOP_UDIV: return Instruction::UDiv;
109 case bitc::BINOP_SDIV:
110 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
111 case bitc::BINOP_UREM: return Instruction::URem;
112 case bitc::BINOP_SREM:
113 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
114 case bitc::BINOP_SHL: return Instruction::Shl;
115 case bitc::BINOP_LSHR: return Instruction::LShr;
116 case bitc::BINOP_ASHR: return Instruction::AShr;
117 case bitc::BINOP_AND: return Instruction::And;
118 case bitc::BINOP_OR: return Instruction::Or;
119 case bitc::BINOP_XOR: return Instruction::Xor;
125 /// @brief A class for maintaining the slot number definition
126 /// as a placeholder for the actual definition for forward constants defs.
127 class ConstantPlaceHolder : public ConstantExpr {
128 ConstantPlaceHolder(); // DO NOT IMPLEMENT
129 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
131 // allocate space for exactly one operand
132 void *operator new(size_t s) {
133 return User::operator new(s, 1);
135 explicit ConstantPlaceHolder(const Type *Ty)
136 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
137 Op<0>() = UndefValue::get(Type::Int32Ty);
140 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
141 static inline bool classof(const ConstantPlaceHolder *) { return true; }
142 static bool classof(const Value *V) {
143 return isa<ConstantExpr>(V) &&
144 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
148 /// Provide fast operand accessors
149 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
153 // FIXME: can we inherit this from ConstantExpr?
155 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
160 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
169 WeakVH &OldV = ValuePtrs[Idx];
175 // Handle constants and non-constants (e.g. instrs) differently for
177 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
178 ResolveConstants.push_back(std::make_pair(PHC, Idx));
181 // If there was a forward reference to this value, replace it.
182 Value *PrevVal = OldV;
183 OldV->replaceAllUsesWith(V);
189 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
194 if (Value *V = ValuePtrs[Idx]) {
195 assert(Ty == V->getType() && "Type mismatch in constant table!");
196 return cast<Constant>(V);
199 // Create and return a placeholder, which will later be RAUW'd.
200 Constant *C = new ConstantPlaceHolder(Ty);
205 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
209 if (Value *V = ValuePtrs[Idx]) {
210 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
214 // No type specified, must be invalid reference.
215 if (Ty == 0) return 0;
217 // Create and return a placeholder, which will later be RAUW'd.
218 Value *V = new Argument(Ty);
223 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
224 /// resolves any forward references. The idea behind this is that we sometimes
225 /// get constants (such as large arrays) which reference *many* forward ref
226 /// constants. Replacing each of these causes a lot of thrashing when
227 /// building/reuniquing the constant. Instead of doing this, we look at all the
228 /// uses and rewrite all the place holders at once for any constant that uses
230 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
231 // Sort the values by-pointer so that they are efficient to look up with a
233 std::sort(ResolveConstants.begin(), ResolveConstants.end());
235 SmallVector<Constant*, 64> NewOps;
237 while (!ResolveConstants.empty()) {
238 Value *RealVal = operator[](ResolveConstants.back().second);
239 Constant *Placeholder = ResolveConstants.back().first;
240 ResolveConstants.pop_back();
242 // Loop over all users of the placeholder, updating them to reference the
243 // new value. If they reference more than one placeholder, update them all
245 while (!Placeholder->use_empty()) {
246 Value::use_iterator UI = Placeholder->use_begin();
248 // If the using object isn't uniqued, just update the operands. This
249 // handles instructions and initializers for global variables.
250 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
251 UI.getUse().set(RealVal);
255 // Otherwise, we have a constant that uses the placeholder. Replace that
256 // constant with a new constant that has *all* placeholder uses updated.
257 Constant *UserC = cast<Constant>(*UI);
258 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
261 if (!isa<ConstantPlaceHolder>(*I)) {
262 // Not a placeholder reference.
264 } else if (*I == Placeholder) {
265 // Common case is that it just references this one placeholder.
268 // Otherwise, look up the placeholder in ResolveConstants.
269 ResolveConstantsTy::iterator It =
270 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
271 std::pair<Constant*, unsigned>(cast<Constant>(*I),
273 assert(It != ResolveConstants.end() && It->first == *I);
274 NewOp = operator[](It->second);
277 NewOps.push_back(cast<Constant>(NewOp));
280 // Make the new constant.
282 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
283 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
284 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
285 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
286 UserCS->getType()->isPacked());
287 } else if (isa<ConstantVector>(UserC)) {
288 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
290 // Must be a constant expression.
291 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
295 UserC->replaceAllUsesWith(NewC);
296 UserC->destroyConstant();
305 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
306 // If the TypeID is in range, return it.
307 if (ID < TypeList.size())
308 return TypeList[ID].get();
309 if (!isTypeTable) return 0;
311 // The type table allows forward references. Push as many Opaque types as
312 // needed to get up to ID.
313 while (TypeList.size() <= ID)
314 TypeList.push_back(OpaqueType::get());
315 return TypeList.back().get();
318 //===----------------------------------------------------------------------===//
319 // Functions for parsing blocks from the bitcode file
320 //===----------------------------------------------------------------------===//
322 bool BitcodeReader::ParseAttributeBlock() {
323 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
324 return Error("Malformed block record");
326 if (!MAttributes.empty())
327 return Error("Multiple PARAMATTR blocks found!");
329 SmallVector<uint64_t, 64> Record;
331 SmallVector<AttributeWithIndex, 8> Attrs;
333 // Read all the records.
335 unsigned Code = Stream.ReadCode();
336 if (Code == bitc::END_BLOCK) {
337 if (Stream.ReadBlockEnd())
338 return Error("Error at end of PARAMATTR block");
342 if (Code == bitc::ENTER_SUBBLOCK) {
343 // No known subblocks, always skip them.
344 Stream.ReadSubBlockID();
345 if (Stream.SkipBlock())
346 return Error("Malformed block record");
350 if (Code == bitc::DEFINE_ABBREV) {
351 Stream.ReadAbbrevRecord();
357 switch (Stream.ReadRecord(Code, Record)) {
358 default: // Default behavior: ignore.
360 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
361 if (Record.size() & 1)
362 return Error("Invalid ENTRY record");
364 // FIXME : Remove this autoupgrade code in LLVM 3.0.
365 // If Function attributes are using index 0 then transfer them
366 // to index ~0. Index 0 is used for return value attributes but used to be
367 // used for function attributes.
368 Attributes RetAttribute = Attribute::None;
369 Attributes FnAttribute = Attribute::None;
370 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
371 // FIXME: remove in LLVM 3.0
372 // The alignment is stored as a 16-bit raw value from bits 31--16.
373 // We shift the bits above 31 down by 11 bits.
375 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
376 if (Alignment && !isPowerOf2_32(Alignment))
377 return Error("Alignment is not a power of two.");
379 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
381 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
382 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
383 Record[i+1] = ReconstitutedAttr;
386 RetAttribute = Record[i+1];
387 else if (Record[i] == ~0U)
388 FnAttribute = Record[i+1];
391 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
392 Attribute::ReadOnly|Attribute::ReadNone);
394 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
395 (RetAttribute & OldRetAttrs) != 0) {
396 if (FnAttribute == Attribute::None) { // add a slot so they get added.
397 Record.push_back(~0U);
401 FnAttribute |= RetAttribute & OldRetAttrs;
402 RetAttribute &= ~OldRetAttrs;
405 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
406 if (Record[i] == 0) {
407 if (RetAttribute != Attribute::None)
408 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
409 } else if (Record[i] == ~0U) {
410 if (FnAttribute != Attribute::None)
411 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
412 } else if (Record[i+1] != Attribute::None)
413 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
416 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
425 bool BitcodeReader::ParseTypeTable() {
426 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
427 return Error("Malformed block record");
429 if (!TypeList.empty())
430 return Error("Multiple TYPE_BLOCKs found!");
432 SmallVector<uint64_t, 64> Record;
433 unsigned NumRecords = 0;
435 // Read all the records for this type table.
437 unsigned Code = Stream.ReadCode();
438 if (Code == bitc::END_BLOCK) {
439 if (NumRecords != TypeList.size())
440 return Error("Invalid type forward reference in TYPE_BLOCK");
441 if (Stream.ReadBlockEnd())
442 return Error("Error at end of type table block");
446 if (Code == bitc::ENTER_SUBBLOCK) {
447 // No known subblocks, always skip them.
448 Stream.ReadSubBlockID();
449 if (Stream.SkipBlock())
450 return Error("Malformed block record");
454 if (Code == bitc::DEFINE_ABBREV) {
455 Stream.ReadAbbrevRecord();
461 const Type *ResultTy = 0;
462 switch (Stream.ReadRecord(Code, Record)) {
463 default: // Default behavior: unknown type.
466 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
467 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
468 // type list. This allows us to reserve space.
469 if (Record.size() < 1)
470 return Error("Invalid TYPE_CODE_NUMENTRY record");
471 TypeList.reserve(Record[0]);
473 case bitc::TYPE_CODE_VOID: // VOID
474 ResultTy = Type::VoidTy;
476 case bitc::TYPE_CODE_FLOAT: // FLOAT
477 ResultTy = Type::FloatTy;
479 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
480 ResultTy = Type::DoubleTy;
482 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
483 ResultTy = Type::X86_FP80Ty;
485 case bitc::TYPE_CODE_FP128: // FP128
486 ResultTy = Type::FP128Ty;
488 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
489 ResultTy = Type::PPC_FP128Ty;
491 case bitc::TYPE_CODE_LABEL: // LABEL
492 ResultTy = Type::LabelTy;
494 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
497 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
498 if (Record.size() < 1)
499 return Error("Invalid Integer type record");
501 ResultTy = IntegerType::get(Record[0]);
503 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
504 // [pointee type, address space]
505 if (Record.size() < 1)
506 return Error("Invalid POINTER type record");
507 unsigned AddressSpace = 0;
508 if (Record.size() == 2)
509 AddressSpace = Record[1];
510 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
513 case bitc::TYPE_CODE_FUNCTION: {
514 // FIXME: attrid is dead, remove it in LLVM 3.0
515 // FUNCTION: [vararg, attrid, retty, paramty x N]
516 if (Record.size() < 3)
517 return Error("Invalid FUNCTION type record");
518 std::vector<const Type*> ArgTys;
519 for (unsigned i = 3, e = Record.size(); i != e; ++i)
520 ArgTys.push_back(getTypeByID(Record[i], true));
522 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
526 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
527 if (Record.size() < 1)
528 return Error("Invalid STRUCT type record");
529 std::vector<const Type*> EltTys;
530 for (unsigned i = 1, e = Record.size(); i != e; ++i)
531 EltTys.push_back(getTypeByID(Record[i], true));
532 ResultTy = StructType::get(EltTys, Record[0]);
535 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
536 if (Record.size() < 2)
537 return Error("Invalid ARRAY type record");
538 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
540 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
541 if (Record.size() < 2)
542 return Error("Invalid VECTOR type record");
543 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
547 if (NumRecords == TypeList.size()) {
548 // If this is a new type slot, just append it.
549 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
551 } else if (ResultTy == 0) {
552 // Otherwise, this was forward referenced, so an opaque type was created,
553 // but the result type is actually just an opaque. Leave the one we
554 // created previously.
557 // Otherwise, this was forward referenced, so an opaque type was created.
558 // Resolve the opaque type to the real type now.
559 assert(NumRecords < TypeList.size() && "Typelist imbalance");
560 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
562 // Don't directly push the new type on the Tab. Instead we want to replace
563 // the opaque type we previously inserted with the new concrete value. The
564 // refinement from the abstract (opaque) type to the new type causes all
565 // uses of the abstract type to use the concrete type (NewTy). This will
566 // also cause the opaque type to be deleted.
567 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
569 // This should have replaced the old opaque type with the new type in the
570 // value table... or with a preexisting type that was already in the
571 // system. Let's just make sure it did.
572 assert(TypeList[NumRecords-1].get() != OldTy &&
573 "refineAbstractType didn't work!");
579 bool BitcodeReader::ParseTypeSymbolTable() {
580 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
581 return Error("Malformed block record");
583 SmallVector<uint64_t, 64> Record;
585 // Read all the records for this type table.
586 std::string TypeName;
588 unsigned Code = Stream.ReadCode();
589 if (Code == bitc::END_BLOCK) {
590 if (Stream.ReadBlockEnd())
591 return Error("Error at end of type symbol table block");
595 if (Code == bitc::ENTER_SUBBLOCK) {
596 // No known subblocks, always skip them.
597 Stream.ReadSubBlockID();
598 if (Stream.SkipBlock())
599 return Error("Malformed block record");
603 if (Code == bitc::DEFINE_ABBREV) {
604 Stream.ReadAbbrevRecord();
610 switch (Stream.ReadRecord(Code, Record)) {
611 default: // Default behavior: unknown type.
613 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
614 if (ConvertToString(Record, 1, TypeName))
615 return Error("Invalid TST_ENTRY record");
616 unsigned TypeID = Record[0];
617 if (TypeID >= TypeList.size())
618 return Error("Invalid Type ID in TST_ENTRY record");
620 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
627 bool BitcodeReader::ParseValueSymbolTable() {
628 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
629 return Error("Malformed block record");
631 SmallVector<uint64_t, 64> Record;
633 // Read all the records for this value table.
634 SmallString<128> ValueName;
636 unsigned Code = Stream.ReadCode();
637 if (Code == bitc::END_BLOCK) {
638 if (Stream.ReadBlockEnd())
639 return Error("Error at end of value symbol table block");
642 if (Code == bitc::ENTER_SUBBLOCK) {
643 // No known subblocks, always skip them.
644 Stream.ReadSubBlockID();
645 if (Stream.SkipBlock())
646 return Error("Malformed block record");
650 if (Code == bitc::DEFINE_ABBREV) {
651 Stream.ReadAbbrevRecord();
657 switch (Stream.ReadRecord(Code, Record)) {
658 default: // Default behavior: unknown type.
660 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
661 if (ConvertToString(Record, 1, ValueName))
662 return Error("Invalid TST_ENTRY record");
663 unsigned ValueID = Record[0];
664 if (ValueID >= ValueList.size())
665 return Error("Invalid Value ID in VST_ENTRY record");
666 Value *V = ValueList[ValueID];
668 V->setName(&ValueName[0], ValueName.size());
672 case bitc::VST_CODE_BBENTRY: {
673 if (ConvertToString(Record, 1, ValueName))
674 return Error("Invalid VST_BBENTRY record");
675 BasicBlock *BB = getBasicBlock(Record[0]);
677 return Error("Invalid BB ID in VST_BBENTRY record");
679 BB->setName(&ValueName[0], ValueName.size());
687 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
688 /// the LSB for dense VBR encoding.
689 static uint64_t DecodeSignRotatedValue(uint64_t V) {
694 // There is no such thing as -0 with integers. "-0" really means MININT.
698 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
699 /// values and aliases that we can.
700 bool BitcodeReader::ResolveGlobalAndAliasInits() {
701 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
702 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
704 GlobalInitWorklist.swap(GlobalInits);
705 AliasInitWorklist.swap(AliasInits);
707 while (!GlobalInitWorklist.empty()) {
708 unsigned ValID = GlobalInitWorklist.back().second;
709 if (ValID >= ValueList.size()) {
710 // Not ready to resolve this yet, it requires something later in the file.
711 GlobalInits.push_back(GlobalInitWorklist.back());
713 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
714 GlobalInitWorklist.back().first->setInitializer(C);
716 return Error("Global variable initializer is not a constant!");
718 GlobalInitWorklist.pop_back();
721 while (!AliasInitWorklist.empty()) {
722 unsigned ValID = AliasInitWorklist.back().second;
723 if (ValID >= ValueList.size()) {
724 AliasInits.push_back(AliasInitWorklist.back());
726 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
727 AliasInitWorklist.back().first->setAliasee(C);
729 return Error("Alias initializer is not a constant!");
731 AliasInitWorklist.pop_back();
737 bool BitcodeReader::ParseConstants() {
738 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
739 return Error("Malformed block record");
741 SmallVector<uint64_t, 64> Record;
743 // Read all the records for this value table.
744 const Type *CurTy = Type::Int32Ty;
745 unsigned NextCstNo = ValueList.size();
747 unsigned Code = Stream.ReadCode();
748 if (Code == bitc::END_BLOCK)
751 if (Code == bitc::ENTER_SUBBLOCK) {
752 // No known subblocks, always skip them.
753 Stream.ReadSubBlockID();
754 if (Stream.SkipBlock())
755 return Error("Malformed block record");
759 if (Code == bitc::DEFINE_ABBREV) {
760 Stream.ReadAbbrevRecord();
767 switch (Stream.ReadRecord(Code, Record)) {
768 default: // Default behavior: unknown constant
769 case bitc::CST_CODE_UNDEF: // UNDEF
770 V = UndefValue::get(CurTy);
772 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
774 return Error("Malformed CST_SETTYPE record");
775 if (Record[0] >= TypeList.size())
776 return Error("Invalid Type ID in CST_SETTYPE record");
777 CurTy = TypeList[Record[0]];
778 continue; // Skip the ValueList manipulation.
779 case bitc::CST_CODE_NULL: // NULL
780 V = Constant::getNullValue(CurTy);
782 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
783 if (!isa<IntegerType>(CurTy) || Record.empty())
784 return Error("Invalid CST_INTEGER record");
785 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
787 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
788 if (!isa<IntegerType>(CurTy) || Record.empty())
789 return Error("Invalid WIDE_INTEGER record");
791 unsigned NumWords = Record.size();
792 SmallVector<uint64_t, 8> Words;
793 Words.resize(NumWords);
794 for (unsigned i = 0; i != NumWords; ++i)
795 Words[i] = DecodeSignRotatedValue(Record[i]);
796 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
797 NumWords, &Words[0]));
800 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
802 return Error("Invalid FLOAT record");
803 if (CurTy == Type::FloatTy)
804 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
805 else if (CurTy == Type::DoubleTy)
806 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
807 else if (CurTy == Type::X86_FP80Ty) {
808 // Bits are not stored the same way as a normal i80 APInt, compensate.
809 uint64_t Rearrange[2];
810 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
811 Rearrange[1] = Record[0] >> 48;
812 V = ConstantFP::get(APFloat(APInt(80, 2, Rearrange)));
813 } else if (CurTy == Type::FP128Ty)
814 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
815 else if (CurTy == Type::PPC_FP128Ty)
816 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
818 V = UndefValue::get(CurTy);
822 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
824 return Error("Invalid CST_AGGREGATE record");
826 unsigned Size = Record.size();
827 std::vector<Constant*> Elts;
829 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
830 for (unsigned i = 0; i != Size; ++i)
831 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
832 STy->getElementType(i)));
833 V = ConstantStruct::get(STy, Elts);
834 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
835 const Type *EltTy = ATy->getElementType();
836 for (unsigned i = 0; i != Size; ++i)
837 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
838 V = ConstantArray::get(ATy, Elts);
839 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
840 const Type *EltTy = VTy->getElementType();
841 for (unsigned i = 0; i != Size; ++i)
842 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
843 V = ConstantVector::get(Elts);
845 V = UndefValue::get(CurTy);
849 case bitc::CST_CODE_STRING: { // STRING: [values]
851 return Error("Invalid CST_AGGREGATE record");
853 const ArrayType *ATy = cast<ArrayType>(CurTy);
854 const Type *EltTy = ATy->getElementType();
856 unsigned Size = Record.size();
857 std::vector<Constant*> Elts;
858 for (unsigned i = 0; i != Size; ++i)
859 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
860 V = ConstantArray::get(ATy, Elts);
863 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
865 return Error("Invalid CST_AGGREGATE record");
867 const ArrayType *ATy = cast<ArrayType>(CurTy);
868 const Type *EltTy = ATy->getElementType();
870 unsigned Size = Record.size();
871 std::vector<Constant*> Elts;
872 for (unsigned i = 0; i != Size; ++i)
873 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
874 Elts.push_back(Constant::getNullValue(EltTy));
875 V = ConstantArray::get(ATy, Elts);
878 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
879 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
880 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
882 V = UndefValue::get(CurTy); // Unknown binop.
884 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
885 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
886 V = ConstantExpr::get(Opc, LHS, RHS);
890 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
891 if (Record.size() < 3) return Error("Invalid CE_CAST record");
892 int Opc = GetDecodedCastOpcode(Record[0]);
894 V = UndefValue::get(CurTy); // Unknown cast.
896 const Type *OpTy = getTypeByID(Record[1]);
897 if (!OpTy) return Error("Invalid CE_CAST record");
898 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
899 V = ConstantExpr::getCast(Opc, Op, CurTy);
903 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
904 if (Record.size() & 1) return Error("Invalid CE_GEP record");
905 SmallVector<Constant*, 16> Elts;
906 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
907 const Type *ElTy = getTypeByID(Record[i]);
908 if (!ElTy) return Error("Invalid CE_GEP record");
909 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
911 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
914 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
915 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
916 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
918 ValueList.getConstantFwdRef(Record[1],CurTy),
919 ValueList.getConstantFwdRef(Record[2],CurTy));
921 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
922 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
923 const VectorType *OpTy =
924 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
925 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
926 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
927 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
928 V = ConstantExpr::getExtractElement(Op0, Op1);
931 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
932 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
933 if (Record.size() < 3 || OpTy == 0)
934 return Error("Invalid CE_INSERTELT record");
935 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
936 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
937 OpTy->getElementType());
938 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
939 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
942 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
943 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
944 if (Record.size() < 3 || OpTy == 0)
945 return Error("Invalid CE_SHUFFLEVEC record");
946 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
947 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
948 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
949 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
950 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
953 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
954 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
955 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
956 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
957 return Error("Invalid CE_SHUFVEC_EX record");
958 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
959 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
960 const Type *ShufTy=VectorType::get(Type::Int32Ty, RTy->getNumElements());
961 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
962 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
965 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
966 if (Record.size() < 4) return Error("Invalid CE_CMP record");
967 const Type *OpTy = getTypeByID(Record[0]);
968 if (OpTy == 0) return Error("Invalid CE_CMP record");
969 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
970 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
972 if (OpTy->isFloatingPoint())
973 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
974 else if (!isa<VectorType>(OpTy))
975 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
976 else if (OpTy->isFPOrFPVector())
977 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
979 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
982 case bitc::CST_CODE_INLINEASM: {
983 if (Record.size() < 2) return Error("Invalid INLINEASM record");
984 std::string AsmStr, ConstrStr;
985 bool HasSideEffects = Record[0];
986 unsigned AsmStrSize = Record[1];
987 if (2+AsmStrSize >= Record.size())
988 return Error("Invalid INLINEASM record");
989 unsigned ConstStrSize = Record[2+AsmStrSize];
990 if (3+AsmStrSize+ConstStrSize > Record.size())
991 return Error("Invalid INLINEASM record");
993 for (unsigned i = 0; i != AsmStrSize; ++i)
994 AsmStr += (char)Record[2+i];
995 for (unsigned i = 0; i != ConstStrSize; ++i)
996 ConstrStr += (char)Record[3+AsmStrSize+i];
997 const PointerType *PTy = cast<PointerType>(CurTy);
998 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
999 AsmStr, ConstrStr, HasSideEffects);
1004 ValueList.AssignValue(V, NextCstNo);
1008 if (NextCstNo != ValueList.size())
1009 return Error("Invalid constant reference!");
1011 if (Stream.ReadBlockEnd())
1012 return Error("Error at end of constants block");
1014 // Once all the constants have been read, go through and resolve forward
1016 ValueList.ResolveConstantForwardRefs();
1020 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1021 /// remember where it is and then skip it. This lets us lazily deserialize the
1023 bool BitcodeReader::RememberAndSkipFunctionBody() {
1024 // Get the function we are talking about.
1025 if (FunctionsWithBodies.empty())
1026 return Error("Insufficient function protos");
1028 Function *Fn = FunctionsWithBodies.back();
1029 FunctionsWithBodies.pop_back();
1031 // Save the current stream state.
1032 uint64_t CurBit = Stream.GetCurrentBitNo();
1033 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1035 // Set the functions linkage to GhostLinkage so we know it is lazily
1037 Fn->setLinkage(GlobalValue::GhostLinkage);
1039 // Skip over the function block for now.
1040 if (Stream.SkipBlock())
1041 return Error("Malformed block record");
1045 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1046 // Reject multiple MODULE_BLOCK's in a single bitstream.
1048 return Error("Multiple MODULE_BLOCKs in same stream");
1050 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1051 return Error("Malformed block record");
1053 // Otherwise, create the module.
1054 TheModule = new Module(ModuleID);
1056 SmallVector<uint64_t, 64> Record;
1057 std::vector<std::string> SectionTable;
1058 std::vector<std::string> GCTable;
1060 // Read all the records for this module.
1061 while (!Stream.AtEndOfStream()) {
1062 unsigned Code = Stream.ReadCode();
1063 if (Code == bitc::END_BLOCK) {
1064 if (Stream.ReadBlockEnd())
1065 return Error("Error at end of module block");
1067 // Patch the initializers for globals and aliases up.
1068 ResolveGlobalAndAliasInits();
1069 if (!GlobalInits.empty() || !AliasInits.empty())
1070 return Error("Malformed global initializer set");
1071 if (!FunctionsWithBodies.empty())
1072 return Error("Too few function bodies found");
1074 // Look for intrinsic functions which need to be upgraded at some point
1075 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1078 if (UpgradeIntrinsicFunction(FI, NewFn))
1079 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1082 // Force deallocation of memory for these vectors to favor the client that
1083 // want lazy deserialization.
1084 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1085 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1086 std::vector<Function*>().swap(FunctionsWithBodies);
1090 if (Code == bitc::ENTER_SUBBLOCK) {
1091 switch (Stream.ReadSubBlockID()) {
1092 default: // Skip unknown content.
1093 if (Stream.SkipBlock())
1094 return Error("Malformed block record");
1096 case bitc::BLOCKINFO_BLOCK_ID:
1097 if (Stream.ReadBlockInfoBlock())
1098 return Error("Malformed BlockInfoBlock");
1100 case bitc::PARAMATTR_BLOCK_ID:
1101 if (ParseAttributeBlock())
1104 case bitc::TYPE_BLOCK_ID:
1105 if (ParseTypeTable())
1108 case bitc::TYPE_SYMTAB_BLOCK_ID:
1109 if (ParseTypeSymbolTable())
1112 case bitc::VALUE_SYMTAB_BLOCK_ID:
1113 if (ParseValueSymbolTable())
1116 case bitc::CONSTANTS_BLOCK_ID:
1117 if (ParseConstants() || ResolveGlobalAndAliasInits())
1120 case bitc::FUNCTION_BLOCK_ID:
1121 // If this is the first function body we've seen, reverse the
1122 // FunctionsWithBodies list.
1123 if (!HasReversedFunctionsWithBodies) {
1124 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1125 HasReversedFunctionsWithBodies = true;
1128 if (RememberAndSkipFunctionBody())
1135 if (Code == bitc::DEFINE_ABBREV) {
1136 Stream.ReadAbbrevRecord();
1141 switch (Stream.ReadRecord(Code, Record)) {
1142 default: break; // Default behavior, ignore unknown content.
1143 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1144 if (Record.size() < 1)
1145 return Error("Malformed MODULE_CODE_VERSION");
1146 // Only version #0 is supported so far.
1148 return Error("Unknown bitstream version!");
1150 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1152 if (ConvertToString(Record, 0, S))
1153 return Error("Invalid MODULE_CODE_TRIPLE record");
1154 TheModule->setTargetTriple(S);
1157 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1159 if (ConvertToString(Record, 0, S))
1160 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1161 TheModule->setDataLayout(S);
1164 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1166 if (ConvertToString(Record, 0, S))
1167 return Error("Invalid MODULE_CODE_ASM record");
1168 TheModule->setModuleInlineAsm(S);
1171 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1173 if (ConvertToString(Record, 0, S))
1174 return Error("Invalid MODULE_CODE_DEPLIB record");
1175 TheModule->addLibrary(S);
1178 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1180 if (ConvertToString(Record, 0, S))
1181 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1182 SectionTable.push_back(S);
1185 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1187 if (ConvertToString(Record, 0, S))
1188 return Error("Invalid MODULE_CODE_GCNAME record");
1189 GCTable.push_back(S);
1192 // GLOBALVAR: [pointer type, isconst, initid,
1193 // linkage, alignment, section, visibility, threadlocal]
1194 case bitc::MODULE_CODE_GLOBALVAR: {
1195 if (Record.size() < 6)
1196 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1197 const Type *Ty = getTypeByID(Record[0]);
1198 if (!isa<PointerType>(Ty))
1199 return Error("Global not a pointer type!");
1200 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1201 Ty = cast<PointerType>(Ty)->getElementType();
1203 bool isConstant = Record[1];
1204 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1205 unsigned Alignment = (1 << Record[4]) >> 1;
1206 std::string Section;
1208 if (Record[5]-1 >= SectionTable.size())
1209 return Error("Invalid section ID");
1210 Section = SectionTable[Record[5]-1];
1212 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1213 if (Record.size() > 6)
1214 Visibility = GetDecodedVisibility(Record[6]);
1215 bool isThreadLocal = false;
1216 if (Record.size() > 7)
1217 isThreadLocal = Record[7];
1219 GlobalVariable *NewGV =
1220 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1221 isThreadLocal, AddressSpace);
1222 NewGV->setAlignment(Alignment);
1223 if (!Section.empty())
1224 NewGV->setSection(Section);
1225 NewGV->setVisibility(Visibility);
1226 NewGV->setThreadLocal(isThreadLocal);
1228 ValueList.push_back(NewGV);
1230 // Remember which value to use for the global initializer.
1231 if (unsigned InitID = Record[2])
1232 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1235 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1236 // alignment, section, visibility, gc]
1237 case bitc::MODULE_CODE_FUNCTION: {
1238 if (Record.size() < 8)
1239 return Error("Invalid MODULE_CODE_FUNCTION record");
1240 const Type *Ty = getTypeByID(Record[0]);
1241 if (!isa<PointerType>(Ty))
1242 return Error("Function not a pointer type!");
1243 const FunctionType *FTy =
1244 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1246 return Error("Function not a pointer to function type!");
1248 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1251 Func->setCallingConv(Record[1]);
1252 bool isProto = Record[2];
1253 Func->setLinkage(GetDecodedLinkage(Record[3]));
1254 Func->setAttributes(getAttributes(Record[4]));
1256 Func->setAlignment((1 << Record[5]) >> 1);
1258 if (Record[6]-1 >= SectionTable.size())
1259 return Error("Invalid section ID");
1260 Func->setSection(SectionTable[Record[6]-1]);
1262 Func->setVisibility(GetDecodedVisibility(Record[7]));
1263 if (Record.size() > 8 && Record[8]) {
1264 if (Record[8]-1 > GCTable.size())
1265 return Error("Invalid GC ID");
1266 Func->setGC(GCTable[Record[8]-1].c_str());
1268 ValueList.push_back(Func);
1270 // If this is a function with a body, remember the prototype we are
1271 // creating now, so that we can match up the body with them later.
1273 FunctionsWithBodies.push_back(Func);
1276 // ALIAS: [alias type, aliasee val#, linkage]
1277 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1278 case bitc::MODULE_CODE_ALIAS: {
1279 if (Record.size() < 3)
1280 return Error("Invalid MODULE_ALIAS record");
1281 const Type *Ty = getTypeByID(Record[0]);
1282 if (!isa<PointerType>(Ty))
1283 return Error("Function not a pointer type!");
1285 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1287 // Old bitcode files didn't have visibility field.
1288 if (Record.size() > 3)
1289 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1290 ValueList.push_back(NewGA);
1291 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1294 /// MODULE_CODE_PURGEVALS: [numvals]
1295 case bitc::MODULE_CODE_PURGEVALS:
1296 // Trim down the value list to the specified size.
1297 if (Record.size() < 1 || Record[0] > ValueList.size())
1298 return Error("Invalid MODULE_PURGEVALS record");
1299 ValueList.shrinkTo(Record[0]);
1305 return Error("Premature end of bitstream");
1308 /// SkipWrapperHeader - Some systems wrap bc files with a special header for
1309 /// padding or other reasons. The format of this header is:
1311 /// struct bc_header {
1312 /// uint32_t Magic; // 0x0B17C0DE
1313 /// uint32_t Version; // Version, currently always 0.
1314 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1315 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1316 /// ... potentially other gunk ...
1319 /// This function is called when we find a file with a matching magic number.
1320 /// In this case, skip down to the subsection of the file that is actually a BC
1322 static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1324 KnownHeaderSize = 4*4, // Size of header we read.
1325 OffsetField = 2*4, // Offset in bytes to Offset field.
1326 SizeField = 3*4 // Offset in bytes to Size field.
1330 // Must contain the header!
1331 if (BufEnd-BufPtr < KnownHeaderSize) return true;
1333 unsigned Offset = ( BufPtr[OffsetField ] |
1334 (BufPtr[OffsetField+1] << 8) |
1335 (BufPtr[OffsetField+2] << 16) |
1336 (BufPtr[OffsetField+3] << 24));
1337 unsigned Size = ( BufPtr[SizeField ] |
1338 (BufPtr[SizeField +1] << 8) |
1339 (BufPtr[SizeField +2] << 16) |
1340 (BufPtr[SizeField +3] << 24));
1342 // Verify that Offset+Size fits in the file.
1343 if (Offset+Size > unsigned(BufEnd-BufPtr))
1346 BufEnd = BufPtr+Size;
1350 bool BitcodeReader::ParseBitcode() {
1353 if (Buffer->getBufferSize() & 3)
1354 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1356 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1357 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1359 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1360 // The magic number is 0x0B17C0DE stored in little endian.
1361 if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1362 BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1363 if (SkipWrapperHeader(BufPtr, BufEnd))
1364 return Error("Invalid bitcode wrapper header");
1366 Stream.init(BufPtr, BufEnd);
1368 // Sniff for the signature.
1369 if (Stream.Read(8) != 'B' ||
1370 Stream.Read(8) != 'C' ||
1371 Stream.Read(4) != 0x0 ||
1372 Stream.Read(4) != 0xC ||
1373 Stream.Read(4) != 0xE ||
1374 Stream.Read(4) != 0xD)
1375 return Error("Invalid bitcode signature");
1377 // We expect a number of well-defined blocks, though we don't necessarily
1378 // need to understand them all.
1379 while (!Stream.AtEndOfStream()) {
1380 unsigned Code = Stream.ReadCode();
1382 if (Code != bitc::ENTER_SUBBLOCK)
1383 return Error("Invalid record at top-level");
1385 unsigned BlockID = Stream.ReadSubBlockID();
1387 // We only know the MODULE subblock ID.
1389 case bitc::BLOCKINFO_BLOCK_ID:
1390 if (Stream.ReadBlockInfoBlock())
1391 return Error("Malformed BlockInfoBlock");
1393 case bitc::MODULE_BLOCK_ID:
1394 if (ParseModule(Buffer->getBufferIdentifier()))
1398 if (Stream.SkipBlock())
1399 return Error("Malformed block record");
1408 /// ParseFunctionBody - Lazily parse the specified function body block.
1409 bool BitcodeReader::ParseFunctionBody(Function *F) {
1410 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1411 return Error("Malformed block record");
1413 unsigned ModuleValueListSize = ValueList.size();
1415 // Add all the function arguments to the value table.
1416 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1417 ValueList.push_back(I);
1419 unsigned NextValueNo = ValueList.size();
1420 BasicBlock *CurBB = 0;
1421 unsigned CurBBNo = 0;
1423 // Read all the records.
1424 SmallVector<uint64_t, 64> Record;
1426 unsigned Code = Stream.ReadCode();
1427 if (Code == bitc::END_BLOCK) {
1428 if (Stream.ReadBlockEnd())
1429 return Error("Error at end of function block");
1433 if (Code == bitc::ENTER_SUBBLOCK) {
1434 switch (Stream.ReadSubBlockID()) {
1435 default: // Skip unknown content.
1436 if (Stream.SkipBlock())
1437 return Error("Malformed block record");
1439 case bitc::CONSTANTS_BLOCK_ID:
1440 if (ParseConstants()) return true;
1441 NextValueNo = ValueList.size();
1443 case bitc::VALUE_SYMTAB_BLOCK_ID:
1444 if (ParseValueSymbolTable()) return true;
1450 if (Code == bitc::DEFINE_ABBREV) {
1451 Stream.ReadAbbrevRecord();
1458 switch (Stream.ReadRecord(Code, Record)) {
1459 default: // Default behavior: reject
1460 return Error("Unknown instruction");
1461 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1462 if (Record.size() < 1 || Record[0] == 0)
1463 return Error("Invalid DECLAREBLOCKS record");
1464 // Create all the basic blocks for the function.
1465 FunctionBBs.resize(Record[0]);
1466 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1467 FunctionBBs[i] = BasicBlock::Create("", F);
1468 CurBB = FunctionBBs[0];
1471 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1474 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1475 getValue(Record, OpNum, LHS->getType(), RHS) ||
1476 OpNum+1 != Record.size())
1477 return Error("Invalid BINOP record");
1479 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1480 if (Opc == -1) return Error("Invalid BINOP record");
1481 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1484 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1487 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1488 OpNum+2 != Record.size())
1489 return Error("Invalid CAST record");
1491 const Type *ResTy = getTypeByID(Record[OpNum]);
1492 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1493 if (Opc == -1 || ResTy == 0)
1494 return Error("Invalid CAST record");
1495 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1498 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1501 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1502 return Error("Invalid GEP record");
1504 SmallVector<Value*, 16> GEPIdx;
1505 while (OpNum != Record.size()) {
1507 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1508 return Error("Invalid GEP record");
1509 GEPIdx.push_back(Op);
1512 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1516 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1517 // EXTRACTVAL: [opty, opval, n x indices]
1520 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1521 return Error("Invalid EXTRACTVAL record");
1523 SmallVector<unsigned, 4> EXTRACTVALIdx;
1524 for (unsigned RecSize = Record.size();
1525 OpNum != RecSize; ++OpNum) {
1526 uint64_t Index = Record[OpNum];
1527 if ((unsigned)Index != Index)
1528 return Error("Invalid EXTRACTVAL index");
1529 EXTRACTVALIdx.push_back((unsigned)Index);
1532 I = ExtractValueInst::Create(Agg,
1533 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1537 case bitc::FUNC_CODE_INST_INSERTVAL: {
1538 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1541 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1542 return Error("Invalid INSERTVAL record");
1544 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1545 return Error("Invalid INSERTVAL record");
1547 SmallVector<unsigned, 4> INSERTVALIdx;
1548 for (unsigned RecSize = Record.size();
1549 OpNum != RecSize; ++OpNum) {
1550 uint64_t Index = Record[OpNum];
1551 if ((unsigned)Index != Index)
1552 return Error("Invalid INSERTVAL index");
1553 INSERTVALIdx.push_back((unsigned)Index);
1556 I = InsertValueInst::Create(Agg, Val,
1557 INSERTVALIdx.begin(), INSERTVALIdx.end());
1561 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1562 // obsolete form of select
1563 // handles select i1 ... in old bitcode
1565 Value *TrueVal, *FalseVal, *Cond;
1566 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1567 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1568 getValue(Record, OpNum, Type::Int1Ty, Cond))
1569 return Error("Invalid SELECT record");
1571 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1575 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1576 // new form of select
1577 // handles select i1 or select [N x i1]
1579 Value *TrueVal, *FalseVal, *Cond;
1580 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1581 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1582 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1583 return Error("Invalid SELECT record");
1585 // select condition can be either i1 or [N x i1]
1586 if (const VectorType* vector_type =
1587 dyn_cast<const VectorType>(Cond->getType())) {
1589 if (vector_type->getElementType() != Type::Int1Ty)
1590 return Error("Invalid SELECT condition type");
1593 if (Cond->getType() != Type::Int1Ty)
1594 return Error("Invalid SELECT condition type");
1597 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1601 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1604 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1605 getValue(Record, OpNum, Type::Int32Ty, Idx))
1606 return Error("Invalid EXTRACTELT record");
1607 I = new ExtractElementInst(Vec, Idx);
1611 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1613 Value *Vec, *Elt, *Idx;
1614 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1615 getValue(Record, OpNum,
1616 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1617 getValue(Record, OpNum, Type::Int32Ty, Idx))
1618 return Error("Invalid INSERTELT record");
1619 I = InsertElementInst::Create(Vec, Elt, Idx);
1623 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1625 Value *Vec1, *Vec2, *Mask;
1626 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1627 getValue(Record, OpNum, Vec1->getType(), Vec2))
1628 return Error("Invalid SHUFFLEVEC record");
1630 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1631 return Error("Invalid SHUFFLEVEC record");
1632 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1636 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1638 // or old form of ICmp/FCmp returning bool
1641 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1642 getValue(Record, OpNum, LHS->getType(), RHS) ||
1643 OpNum+1 != Record.size())
1644 return Error("Invalid CMP record");
1646 if (LHS->getType()->isFloatingPoint())
1647 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1648 else if (!isa<VectorType>(LHS->getType()))
1649 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1650 else if (LHS->getType()->isFPOrFPVector())
1651 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1653 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1656 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1657 // Fcmp/ICmp returning bool or vector of bool
1660 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1661 getValue(Record, OpNum, LHS->getType(), RHS) ||
1662 OpNum+1 != Record.size())
1663 return Error("Invalid CMP2 record");
1665 if (LHS->getType()->isFPOrFPVector())
1666 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1668 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1671 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1672 if (Record.size() != 2)
1673 return Error("Invalid GETRESULT record");
1676 getValueTypePair(Record, OpNum, NextValueNo, Op);
1677 unsigned Index = Record[1];
1678 I = ExtractValueInst::Create(Op, Index);
1682 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1684 unsigned Size = Record.size();
1686 I = ReturnInst::Create();
1691 SmallVector<Value *,4> Vs;
1694 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1695 return Error("Invalid RET record");
1697 } while(OpNum != Record.size());
1699 const Type *ReturnType = F->getReturnType();
1700 if (Vs.size() > 1 ||
1701 (isa<StructType>(ReturnType) &&
1702 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1703 Value *RV = UndefValue::get(ReturnType);
1704 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1705 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1706 CurBB->getInstList().push_back(I);
1707 ValueList.AssignValue(I, NextValueNo++);
1710 I = ReturnInst::Create(RV);
1714 I = ReturnInst::Create(Vs[0]);
1717 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1718 if (Record.size() != 1 && Record.size() != 3)
1719 return Error("Invalid BR record");
1720 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1722 return Error("Invalid BR record");
1724 if (Record.size() == 1)
1725 I = BranchInst::Create(TrueDest);
1727 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1728 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1729 if (FalseDest == 0 || Cond == 0)
1730 return Error("Invalid BR record");
1731 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1735 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1736 if (Record.size() < 3 || (Record.size() & 1) == 0)
1737 return Error("Invalid SWITCH record");
1738 const Type *OpTy = getTypeByID(Record[0]);
1739 Value *Cond = getFnValueByID(Record[1], OpTy);
1740 BasicBlock *Default = getBasicBlock(Record[2]);
1741 if (OpTy == 0 || Cond == 0 || Default == 0)
1742 return Error("Invalid SWITCH record");
1743 unsigned NumCases = (Record.size()-3)/2;
1744 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1745 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1746 ConstantInt *CaseVal =
1747 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1748 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1749 if (CaseVal == 0 || DestBB == 0) {
1751 return Error("Invalid SWITCH record!");
1753 SI->addCase(CaseVal, DestBB);
1759 case bitc::FUNC_CODE_INST_INVOKE: {
1760 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1761 if (Record.size() < 4) return Error("Invalid INVOKE record");
1762 AttrListPtr PAL = getAttributes(Record[0]);
1763 unsigned CCInfo = Record[1];
1764 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1765 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1769 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1770 return Error("Invalid INVOKE record");
1772 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1773 const FunctionType *FTy = !CalleeTy ? 0 :
1774 dyn_cast<FunctionType>(CalleeTy->getElementType());
1776 // Check that the right number of fixed parameters are here.
1777 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1778 Record.size() < OpNum+FTy->getNumParams())
1779 return Error("Invalid INVOKE record");
1781 SmallVector<Value*, 16> Ops;
1782 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1783 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1784 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1787 if (!FTy->isVarArg()) {
1788 if (Record.size() != OpNum)
1789 return Error("Invalid INVOKE record");
1791 // Read type/value pairs for varargs params.
1792 while (OpNum != Record.size()) {
1794 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1795 return Error("Invalid INVOKE record");
1800 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1801 Ops.begin(), Ops.end());
1802 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1803 cast<InvokeInst>(I)->setAttributes(PAL);
1806 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1807 I = new UnwindInst();
1809 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1810 I = new UnreachableInst();
1812 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1813 if (Record.size() < 1 || ((Record.size()-1)&1))
1814 return Error("Invalid PHI record");
1815 const Type *Ty = getTypeByID(Record[0]);
1816 if (!Ty) return Error("Invalid PHI record");
1818 PHINode *PN = PHINode::Create(Ty);
1819 PN->reserveOperandSpace((Record.size()-1)/2);
1821 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1822 Value *V = getFnValueByID(Record[1+i], Ty);
1823 BasicBlock *BB = getBasicBlock(Record[2+i]);
1824 if (!V || !BB) return Error("Invalid PHI record");
1825 PN->addIncoming(V, BB);
1831 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1832 if (Record.size() < 3)
1833 return Error("Invalid MALLOC record");
1834 const PointerType *Ty =
1835 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1836 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1837 unsigned Align = Record[2];
1838 if (!Ty || !Size) return Error("Invalid MALLOC record");
1839 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1842 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1845 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1846 OpNum != Record.size())
1847 return Error("Invalid FREE record");
1848 I = new FreeInst(Op);
1851 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1852 if (Record.size() < 3)
1853 return Error("Invalid ALLOCA record");
1854 const PointerType *Ty =
1855 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1856 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1857 unsigned Align = Record[2];
1858 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1859 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1862 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1865 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1866 OpNum+2 != Record.size())
1867 return Error("Invalid LOAD record");
1869 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1872 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1875 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1876 getValue(Record, OpNum,
1877 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1878 OpNum+2 != Record.size())
1879 return Error("Invalid STORE record");
1881 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1884 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1885 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1888 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1889 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1890 OpNum+2 != Record.size())
1891 return Error("Invalid STORE record");
1893 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1896 case bitc::FUNC_CODE_INST_CALL: {
1897 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1898 if (Record.size() < 3)
1899 return Error("Invalid CALL record");
1901 AttrListPtr PAL = getAttributes(Record[0]);
1902 unsigned CCInfo = Record[1];
1906 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1907 return Error("Invalid CALL record");
1909 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1910 const FunctionType *FTy = 0;
1911 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1912 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1913 return Error("Invalid CALL record");
1915 SmallVector<Value*, 16> Args;
1916 // Read the fixed params.
1917 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1918 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1919 Args.push_back(getBasicBlock(Record[OpNum]));
1921 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1922 if (Args.back() == 0) return Error("Invalid CALL record");
1925 // Read type/value pairs for varargs params.
1926 if (!FTy->isVarArg()) {
1927 if (OpNum != Record.size())
1928 return Error("Invalid CALL record");
1930 while (OpNum != Record.size()) {
1932 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1933 return Error("Invalid CALL record");
1938 I = CallInst::Create(Callee, Args.begin(), Args.end());
1939 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1940 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1941 cast<CallInst>(I)->setAttributes(PAL);
1944 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1945 if (Record.size() < 3)
1946 return Error("Invalid VAARG record");
1947 const Type *OpTy = getTypeByID(Record[0]);
1948 Value *Op = getFnValueByID(Record[1], OpTy);
1949 const Type *ResTy = getTypeByID(Record[2]);
1950 if (!OpTy || !Op || !ResTy)
1951 return Error("Invalid VAARG record");
1952 I = new VAArgInst(Op, ResTy);
1957 // Add instruction to end of current BB. If there is no current BB, reject
1961 return Error("Invalid instruction with no BB");
1963 CurBB->getInstList().push_back(I);
1965 // If this was a terminator instruction, move to the next block.
1966 if (isa<TerminatorInst>(I)) {
1968 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1971 // Non-void values get registered in the value table for future use.
1972 if (I && I->getType() != Type::VoidTy)
1973 ValueList.AssignValue(I, NextValueNo++);
1976 // Check the function list for unresolved values.
1977 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1978 if (A->getParent() == 0) {
1979 // We found at least one unresolved value. Nuke them all to avoid leaks.
1980 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1981 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1982 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1986 return Error("Never resolved value found in function!");
1990 // Trim the value list down to the size it was before we parsed this function.
1991 ValueList.shrinkTo(ModuleValueListSize);
1992 std::vector<BasicBlock*>().swap(FunctionBBs);
1997 //===----------------------------------------------------------------------===//
1998 // ModuleProvider implementation
1999 //===----------------------------------------------------------------------===//
2002 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2003 // If it already is material, ignore the request.
2004 if (!F->hasNotBeenReadFromBitcode()) return false;
2006 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2007 DeferredFunctionInfo.find(F);
2008 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2010 // Move the bit stream to the saved position of the deferred function body and
2011 // restore the real linkage type for the function.
2012 Stream.JumpToBit(DFII->second.first);
2013 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2015 if (ParseFunctionBody(F)) {
2016 if (ErrInfo) *ErrInfo = ErrorString;
2020 // Upgrade any old intrinsic calls in the function.
2021 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2022 E = UpgradedIntrinsics.end(); I != E; ++I) {
2023 if (I->first != I->second) {
2024 for (Value::use_iterator UI = I->first->use_begin(),
2025 UE = I->first->use_end(); UI != UE; ) {
2026 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2027 UpgradeIntrinsicCall(CI, I->second);
2035 void BitcodeReader::dematerializeFunction(Function *F) {
2036 // If this function isn't materialized, or if it is a proto, this is a noop.
2037 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2040 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2042 // Just forget the function body, we can remat it later.
2044 F->setLinkage(GlobalValue::GhostLinkage);
2048 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2049 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
2050 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
2052 Function *F = I->first;
2053 if (F->hasNotBeenReadFromBitcode() &&
2054 materializeFunction(F, ErrInfo))
2058 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2059 // delete the old functions to clean up. We can't do this unless the entire
2060 // module is materialized because there could always be another function body
2061 // with calls to the old function.
2062 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2063 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2064 if (I->first != I->second) {
2065 for (Value::use_iterator UI = I->first->use_begin(),
2066 UE = I->first->use_end(); UI != UE; ) {
2067 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2068 UpgradeIntrinsicCall(CI, I->second);
2070 I->first->replaceAllUsesWith(I->second);
2071 I->first->eraseFromParent();
2074 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2080 /// This method is provided by the parent ModuleProvde class and overriden
2081 /// here. It simply releases the module from its provided and frees up our
2083 /// @brief Release our hold on the generated module
2084 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2085 // Since we're losing control of this Module, we must hand it back complete
2086 Module *M = ModuleProvider::releaseModule(ErrInfo);
2092 //===----------------------------------------------------------------------===//
2093 // External interface
2094 //===----------------------------------------------------------------------===//
2096 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2098 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2099 std::string *ErrMsg) {
2100 BitcodeReader *R = new BitcodeReader(Buffer);
2101 if (R->ParseBitcode()) {
2103 *ErrMsg = R->getErrorString();
2105 // Don't let the BitcodeReader dtor delete 'Buffer'.
2106 R->releaseMemoryBuffer();
2113 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2114 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2115 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2117 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2120 // Read in the entire module.
2121 Module *M = R->materializeModule(ErrMsg);
2123 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2124 // there was an error.
2125 R->releaseMemoryBuffer();
2127 // If there was no error, tell ModuleProvider not to delete it when its dtor
2130 M = R->releaseModule(ErrMsg);