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/LLVMContext.h"
21 #include "llvm/MDNode.h"
22 #include "llvm/Module.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);
37 std::vector<AttrListPtr>().swap(MAttributes);
38 std::vector<BasicBlock*>().swap(FunctionBBs);
39 std::vector<Function*>().swap(FunctionsWithBodies);
40 DeferredFunctionInfo.clear();
43 //===----------------------------------------------------------------------===//
44 // Helper functions to implement forward reference resolution, etc.
45 //===----------------------------------------------------------------------===//
47 /// ConvertToString - Convert a string from a record into an std::string, return
49 template<typename StrTy>
50 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
52 if (Idx > Record.size())
55 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
56 Result += (char)Record[i];
60 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
62 default: // Map unknown/new linkages to external
63 case 0: return GlobalValue::ExternalLinkage;
64 case 1: return GlobalValue::WeakAnyLinkage;
65 case 2: return GlobalValue::AppendingLinkage;
66 case 3: return GlobalValue::InternalLinkage;
67 case 4: return GlobalValue::LinkOnceAnyLinkage;
68 case 5: return GlobalValue::DLLImportLinkage;
69 case 6: return GlobalValue::DLLExportLinkage;
70 case 7: return GlobalValue::ExternalWeakLinkage;
71 case 8: return GlobalValue::CommonLinkage;
72 case 9: return GlobalValue::PrivateLinkage;
73 case 10: return GlobalValue::WeakODRLinkage;
74 case 11: return GlobalValue::LinkOnceODRLinkage;
75 case 12: return GlobalValue::AvailableExternallyLinkage;
76 case 13: return GlobalValue::LinkerPrivateLinkage;
80 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
82 default: // Map unknown visibilities to default.
83 case 0: return GlobalValue::DefaultVisibility;
84 case 1: return GlobalValue::HiddenVisibility;
85 case 2: return GlobalValue::ProtectedVisibility;
89 static int GetDecodedCastOpcode(unsigned Val) {
92 case bitc::CAST_TRUNC : return Instruction::Trunc;
93 case bitc::CAST_ZEXT : return Instruction::ZExt;
94 case bitc::CAST_SEXT : return Instruction::SExt;
95 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
96 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
97 case bitc::CAST_UITOFP : return Instruction::UIToFP;
98 case bitc::CAST_SITOFP : return Instruction::SIToFP;
99 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
100 case bitc::CAST_FPEXT : return Instruction::FPExt;
101 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
102 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
103 case bitc::CAST_BITCAST : return Instruction::BitCast;
106 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
109 case bitc::BINOP_ADD:
110 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
111 case bitc::BINOP_SUB:
112 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
113 case bitc::BINOP_MUL:
114 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
115 case bitc::BINOP_UDIV: return Instruction::UDiv;
116 case bitc::BINOP_SDIV:
117 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
118 case bitc::BINOP_UREM: return Instruction::URem;
119 case bitc::BINOP_SREM:
120 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
121 case bitc::BINOP_SHL: return Instruction::Shl;
122 case bitc::BINOP_LSHR: return Instruction::LShr;
123 case bitc::BINOP_ASHR: return Instruction::AShr;
124 case bitc::BINOP_AND: return Instruction::And;
125 case bitc::BINOP_OR: return Instruction::Or;
126 case bitc::BINOP_XOR: return Instruction::Xor;
132 /// @brief A class for maintaining the slot number definition
133 /// as a placeholder for the actual definition for forward constants defs.
134 class ConstantPlaceHolder : public ConstantExpr {
135 ConstantPlaceHolder(); // DO NOT IMPLEMENT
136 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
138 // allocate space for exactly one operand
139 void *operator new(size_t s) {
140 return User::operator new(s, 1);
142 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
143 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
144 Op<0>() = Context.getUndef(Type::Int32Ty);
147 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
148 static inline bool classof(const ConstantPlaceHolder *) { return true; }
149 static bool classof(const Value *V) {
150 return isa<ConstantExpr>(V) &&
151 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
155 /// Provide fast operand accessors
156 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
160 // FIXME: can we inherit this from ConstantExpr?
162 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
167 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
176 WeakVH &OldV = ValuePtrs[Idx];
182 // Handle constants and non-constants (e.g. instrs) differently for
184 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
185 ResolveConstants.push_back(std::make_pair(PHC, Idx));
188 // If there was a forward reference to this value, replace it.
189 Value *PrevVal = OldV;
190 OldV->replaceAllUsesWith(V);
196 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
201 if (Value *V = ValuePtrs[Idx]) {
202 assert(Ty == V->getType() && "Type mismatch in constant table!");
203 return cast<Constant>(V);
206 // Create and return a placeholder, which will later be RAUW'd.
207 Constant *C = new ConstantPlaceHolder(Ty, Context);
212 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
216 if (Value *V = ValuePtrs[Idx]) {
217 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
221 // No type specified, must be invalid reference.
222 if (Ty == 0) return 0;
224 // Create and return a placeholder, which will later be RAUW'd.
225 Value *V = new Argument(Ty);
230 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
231 /// resolves any forward references. The idea behind this is that we sometimes
232 /// get constants (such as large arrays) which reference *many* forward ref
233 /// constants. Replacing each of these causes a lot of thrashing when
234 /// building/reuniquing the constant. Instead of doing this, we look at all the
235 /// uses and rewrite all the place holders at once for any constant that uses
237 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
238 // Sort the values by-pointer so that they are efficient to look up with a
240 std::sort(ResolveConstants.begin(), ResolveConstants.end());
242 SmallVector<Constant*, 64> NewOps;
244 while (!ResolveConstants.empty()) {
245 Value *RealVal = operator[](ResolveConstants.back().second);
246 Constant *Placeholder = ResolveConstants.back().first;
247 ResolveConstants.pop_back();
249 // Loop over all users of the placeholder, updating them to reference the
250 // new value. If they reference more than one placeholder, update them all
252 while (!Placeholder->use_empty()) {
253 Value::use_iterator UI = Placeholder->use_begin();
255 // If the using object isn't uniqued, just update the operands. This
256 // handles instructions and initializers for global variables.
257 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
258 UI.getUse().set(RealVal);
262 // Otherwise, we have a constant that uses the placeholder. Replace that
263 // constant with a new constant that has *all* placeholder uses updated.
264 Constant *UserC = cast<Constant>(*UI);
265 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
268 if (!isa<ConstantPlaceHolder>(*I)) {
269 // Not a placeholder reference.
271 } else if (*I == Placeholder) {
272 // Common case is that it just references this one placeholder.
275 // Otherwise, look up the placeholder in ResolveConstants.
276 ResolveConstantsTy::iterator It =
277 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
278 std::pair<Constant*, unsigned>(cast<Constant>(*I),
280 assert(It != ResolveConstants.end() && It->first == *I);
281 NewOp = operator[](It->second);
284 NewOps.push_back(cast<Constant>(NewOp));
287 // Make the new constant.
289 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
290 NewC = Context.getConstantArray(UserCA->getType(), &NewOps[0],
292 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
293 NewC = Context.getConstantStruct(&NewOps[0], NewOps.size(),
294 UserCS->getType()->isPacked());
295 } else if (isa<ConstantVector>(UserC)) {
296 NewC = Context.getConstantVector(&NewOps[0], NewOps.size());
298 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
299 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
303 UserC->replaceAllUsesWith(NewC);
304 UserC->destroyConstant();
308 // Update all ValueHandles, they should be the only users at this point.
309 Placeholder->replaceAllUsesWith(RealVal);
315 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
316 // If the TypeID is in range, return it.
317 if (ID < TypeList.size())
318 return TypeList[ID].get();
319 if (!isTypeTable) return 0;
321 // The type table allows forward references. Push as many Opaque types as
322 // needed to get up to ID.
323 while (TypeList.size() <= ID)
324 TypeList.push_back(Context.getOpaqueType());
325 return TypeList.back().get();
328 //===----------------------------------------------------------------------===//
329 // Functions for parsing blocks from the bitcode file
330 //===----------------------------------------------------------------------===//
332 bool BitcodeReader::ParseAttributeBlock() {
333 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
334 return Error("Malformed block record");
336 if (!MAttributes.empty())
337 return Error("Multiple PARAMATTR blocks found!");
339 SmallVector<uint64_t, 64> Record;
341 SmallVector<AttributeWithIndex, 8> Attrs;
343 // Read all the records.
345 unsigned Code = Stream.ReadCode();
346 if (Code == bitc::END_BLOCK) {
347 if (Stream.ReadBlockEnd())
348 return Error("Error at end of PARAMATTR block");
352 if (Code == bitc::ENTER_SUBBLOCK) {
353 // No known subblocks, always skip them.
354 Stream.ReadSubBlockID();
355 if (Stream.SkipBlock())
356 return Error("Malformed block record");
360 if (Code == bitc::DEFINE_ABBREV) {
361 Stream.ReadAbbrevRecord();
367 switch (Stream.ReadRecord(Code, Record)) {
368 default: // Default behavior: ignore.
370 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
371 if (Record.size() & 1)
372 return Error("Invalid ENTRY record");
374 // FIXME : Remove this autoupgrade code in LLVM 3.0.
375 // If Function attributes are using index 0 then transfer them
376 // to index ~0. Index 0 is used for return value attributes but used to be
377 // used for function attributes.
378 Attributes RetAttribute = Attribute::None;
379 Attributes FnAttribute = Attribute::None;
380 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
381 // FIXME: remove in LLVM 3.0
382 // The alignment is stored as a 16-bit raw value from bits 31--16.
383 // We shift the bits above 31 down by 11 bits.
385 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
386 if (Alignment && !isPowerOf2_32(Alignment))
387 return Error("Alignment is not a power of two.");
389 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
391 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
392 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
393 Record[i+1] = ReconstitutedAttr;
396 RetAttribute = Record[i+1];
397 else if (Record[i] == ~0U)
398 FnAttribute = Record[i+1];
401 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
402 Attribute::ReadOnly|Attribute::ReadNone);
404 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
405 (RetAttribute & OldRetAttrs) != 0) {
406 if (FnAttribute == Attribute::None) { // add a slot so they get added.
407 Record.push_back(~0U);
411 FnAttribute |= RetAttribute & OldRetAttrs;
412 RetAttribute &= ~OldRetAttrs;
415 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
416 if (Record[i] == 0) {
417 if (RetAttribute != Attribute::None)
418 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
419 } else if (Record[i] == ~0U) {
420 if (FnAttribute != Attribute::None)
421 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
422 } else if (Record[i+1] != Attribute::None)
423 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
426 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
435 bool BitcodeReader::ParseTypeTable() {
436 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
437 return Error("Malformed block record");
439 if (!TypeList.empty())
440 return Error("Multiple TYPE_BLOCKs found!");
442 SmallVector<uint64_t, 64> Record;
443 unsigned NumRecords = 0;
445 // Read all the records for this type table.
447 unsigned Code = Stream.ReadCode();
448 if (Code == bitc::END_BLOCK) {
449 if (NumRecords != TypeList.size())
450 return Error("Invalid type forward reference in TYPE_BLOCK");
451 if (Stream.ReadBlockEnd())
452 return Error("Error at end of type table block");
456 if (Code == bitc::ENTER_SUBBLOCK) {
457 // No known subblocks, always skip them.
458 Stream.ReadSubBlockID();
459 if (Stream.SkipBlock())
460 return Error("Malformed block record");
464 if (Code == bitc::DEFINE_ABBREV) {
465 Stream.ReadAbbrevRecord();
471 const Type *ResultTy = 0;
472 switch (Stream.ReadRecord(Code, Record)) {
473 default: // Default behavior: unknown type.
476 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
477 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
478 // type list. This allows us to reserve space.
479 if (Record.size() < 1)
480 return Error("Invalid TYPE_CODE_NUMENTRY record");
481 TypeList.reserve(Record[0]);
483 case bitc::TYPE_CODE_VOID: // VOID
484 ResultTy = Type::VoidTy;
486 case bitc::TYPE_CODE_FLOAT: // FLOAT
487 ResultTy = Type::FloatTy;
489 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
490 ResultTy = Type::DoubleTy;
492 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
493 ResultTy = Type::X86_FP80Ty;
495 case bitc::TYPE_CODE_FP128: // FP128
496 ResultTy = Type::FP128Ty;
498 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
499 ResultTy = Type::PPC_FP128Ty;
501 case bitc::TYPE_CODE_LABEL: // LABEL
502 ResultTy = Type::LabelTy;
504 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
507 case bitc::TYPE_CODE_METADATA: // METADATA
508 ResultTy = Type::MetadataTy;
510 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
511 if (Record.size() < 1)
512 return Error("Invalid Integer type record");
514 ResultTy = Context.getIntegerType(Record[0]);
516 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
517 // [pointee type, address space]
518 if (Record.size() < 1)
519 return Error("Invalid POINTER type record");
520 unsigned AddressSpace = 0;
521 if (Record.size() == 2)
522 AddressSpace = Record[1];
523 ResultTy = Context.getPointerType(getTypeByID(Record[0], true),
527 case bitc::TYPE_CODE_FUNCTION: {
528 // FIXME: attrid is dead, remove it in LLVM 3.0
529 // FUNCTION: [vararg, attrid, retty, paramty x N]
530 if (Record.size() < 3)
531 return Error("Invalid FUNCTION type record");
532 std::vector<const Type*> ArgTys;
533 for (unsigned i = 3, e = Record.size(); i != e; ++i)
534 ArgTys.push_back(getTypeByID(Record[i], true));
536 ResultTy = Context.getFunctionType(getTypeByID(Record[2], true), ArgTys,
540 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
541 if (Record.size() < 1)
542 return Error("Invalid STRUCT type record");
543 std::vector<const Type*> EltTys;
544 for (unsigned i = 1, e = Record.size(); i != e; ++i)
545 EltTys.push_back(getTypeByID(Record[i], true));
546 ResultTy = Context.getStructType(EltTys, Record[0]);
549 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
550 if (Record.size() < 2)
551 return Error("Invalid ARRAY type record");
552 ResultTy = Context.getArrayType(getTypeByID(Record[1], true), Record[0]);
554 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
555 if (Record.size() < 2)
556 return Error("Invalid VECTOR type record");
557 ResultTy = Context.getVectorType(getTypeByID(Record[1], true), Record[0]);
561 if (NumRecords == TypeList.size()) {
562 // If this is a new type slot, just append it.
563 TypeList.push_back(ResultTy ? ResultTy : Context.getOpaqueType());
565 } else if (ResultTy == 0) {
566 // Otherwise, this was forward referenced, so an opaque type was created,
567 // but the result type is actually just an opaque. Leave the one we
568 // created previously.
571 // Otherwise, this was forward referenced, so an opaque type was created.
572 // Resolve the opaque type to the real type now.
573 assert(NumRecords < TypeList.size() && "Typelist imbalance");
574 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
576 // Don't directly push the new type on the Tab. Instead we want to replace
577 // the opaque type we previously inserted with the new concrete value. The
578 // refinement from the abstract (opaque) type to the new type causes all
579 // uses of the abstract type to use the concrete type (NewTy). This will
580 // also cause the opaque type to be deleted.
581 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
583 // This should have replaced the old opaque type with the new type in the
584 // value table... or with a preexisting type that was already in the
585 // system. Let's just make sure it did.
586 assert(TypeList[NumRecords-1].get() != OldTy &&
587 "refineAbstractType didn't work!");
593 bool BitcodeReader::ParseTypeSymbolTable() {
594 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
595 return Error("Malformed block record");
597 SmallVector<uint64_t, 64> Record;
599 // Read all the records for this type table.
600 std::string TypeName;
602 unsigned Code = Stream.ReadCode();
603 if (Code == bitc::END_BLOCK) {
604 if (Stream.ReadBlockEnd())
605 return Error("Error at end of type symbol table block");
609 if (Code == bitc::ENTER_SUBBLOCK) {
610 // No known subblocks, always skip them.
611 Stream.ReadSubBlockID();
612 if (Stream.SkipBlock())
613 return Error("Malformed block record");
617 if (Code == bitc::DEFINE_ABBREV) {
618 Stream.ReadAbbrevRecord();
624 switch (Stream.ReadRecord(Code, Record)) {
625 default: // Default behavior: unknown type.
627 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
628 if (ConvertToString(Record, 1, TypeName))
629 return Error("Invalid TST_ENTRY record");
630 unsigned TypeID = Record[0];
631 if (TypeID >= TypeList.size())
632 return Error("Invalid Type ID in TST_ENTRY record");
634 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
641 bool BitcodeReader::ParseValueSymbolTable() {
642 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
643 return Error("Malformed block record");
645 SmallVector<uint64_t, 64> Record;
647 // Read all the records for this value table.
648 SmallString<128> ValueName;
650 unsigned Code = Stream.ReadCode();
651 if (Code == bitc::END_BLOCK) {
652 if (Stream.ReadBlockEnd())
653 return Error("Error at end of value symbol table block");
656 if (Code == bitc::ENTER_SUBBLOCK) {
657 // No known subblocks, always skip them.
658 Stream.ReadSubBlockID();
659 if (Stream.SkipBlock())
660 return Error("Malformed block record");
664 if (Code == bitc::DEFINE_ABBREV) {
665 Stream.ReadAbbrevRecord();
671 switch (Stream.ReadRecord(Code, Record)) {
672 default: // Default behavior: unknown type.
674 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
675 if (ConvertToString(Record, 1, ValueName))
676 return Error("Invalid VST_ENTRY record");
677 unsigned ValueID = Record[0];
678 if (ValueID >= ValueList.size())
679 return Error("Invalid Value ID in VST_ENTRY record");
680 Value *V = ValueList[ValueID];
682 V->setName(&ValueName[0], ValueName.size());
686 case bitc::VST_CODE_BBENTRY: {
687 if (ConvertToString(Record, 1, ValueName))
688 return Error("Invalid VST_BBENTRY record");
689 BasicBlock *BB = getBasicBlock(Record[0]);
691 return Error("Invalid BB ID in VST_BBENTRY record");
693 BB->setName(&ValueName[0], ValueName.size());
701 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
702 /// the LSB for dense VBR encoding.
703 static uint64_t DecodeSignRotatedValue(uint64_t V) {
708 // There is no such thing as -0 with integers. "-0" really means MININT.
712 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
713 /// values and aliases that we can.
714 bool BitcodeReader::ResolveGlobalAndAliasInits() {
715 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
716 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
718 GlobalInitWorklist.swap(GlobalInits);
719 AliasInitWorklist.swap(AliasInits);
721 while (!GlobalInitWorklist.empty()) {
722 unsigned ValID = GlobalInitWorklist.back().second;
723 if (ValID >= ValueList.size()) {
724 // Not ready to resolve this yet, it requires something later in the file.
725 GlobalInits.push_back(GlobalInitWorklist.back());
727 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
728 GlobalInitWorklist.back().first->setInitializer(C);
730 return Error("Global variable initializer is not a constant!");
732 GlobalInitWorklist.pop_back();
735 while (!AliasInitWorklist.empty()) {
736 unsigned ValID = AliasInitWorklist.back().second;
737 if (ValID >= ValueList.size()) {
738 AliasInits.push_back(AliasInitWorklist.back());
740 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
741 AliasInitWorklist.back().first->setAliasee(C);
743 return Error("Alias initializer is not a constant!");
745 AliasInitWorklist.pop_back();
751 bool BitcodeReader::ParseConstants() {
752 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
753 return Error("Malformed block record");
755 SmallVector<uint64_t, 64> Record;
757 // Read all the records for this value table.
758 const Type *CurTy = Type::Int32Ty;
759 unsigned NextCstNo = ValueList.size();
761 unsigned Code = Stream.ReadCode();
762 if (Code == bitc::END_BLOCK)
765 if (Code == bitc::ENTER_SUBBLOCK) {
766 // No known subblocks, always skip them.
767 Stream.ReadSubBlockID();
768 if (Stream.SkipBlock())
769 return Error("Malformed block record");
773 if (Code == bitc::DEFINE_ABBREV) {
774 Stream.ReadAbbrevRecord();
781 switch (Stream.ReadRecord(Code, Record)) {
782 default: // Default behavior: unknown constant
783 case bitc::CST_CODE_UNDEF: // UNDEF
784 V = Context.getUndef(CurTy);
786 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
788 return Error("Malformed CST_SETTYPE record");
789 if (Record[0] >= TypeList.size())
790 return Error("Invalid Type ID in CST_SETTYPE record");
791 CurTy = TypeList[Record[0]];
792 continue; // Skip the ValueList manipulation.
793 case bitc::CST_CODE_NULL: // NULL
794 V = Context.getNullValue(CurTy);
796 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
797 if (!isa<IntegerType>(CurTy) || Record.empty())
798 return Error("Invalid CST_INTEGER record");
799 V = Context.getConstantInt(CurTy, DecodeSignRotatedValue(Record[0]));
801 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
802 if (!isa<IntegerType>(CurTy) || Record.empty())
803 return Error("Invalid WIDE_INTEGER record");
805 unsigned NumWords = Record.size();
806 SmallVector<uint64_t, 8> Words;
807 Words.resize(NumWords);
808 for (unsigned i = 0; i != NumWords; ++i)
809 Words[i] = DecodeSignRotatedValue(Record[i]);
810 V = Context.getConstantInt(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
811 NumWords, &Words[0]));
814 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
816 return Error("Invalid FLOAT record");
817 if (CurTy == Type::FloatTy)
818 V = Context.getConstantFP(APFloat(APInt(32, (uint32_t)Record[0])));
819 else if (CurTy == Type::DoubleTy)
820 V = Context.getConstantFP(APFloat(APInt(64, Record[0])));
821 else if (CurTy == Type::X86_FP80Ty) {
822 // Bits are not stored the same way as a normal i80 APInt, compensate.
823 uint64_t Rearrange[2];
824 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
825 Rearrange[1] = Record[0] >> 48;
826 V = Context.getConstantFP(APFloat(APInt(80, 2, Rearrange)));
827 } else if (CurTy == Type::FP128Ty)
828 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0]), true));
829 else if (CurTy == Type::PPC_FP128Ty)
830 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0])));
832 V = Context.getUndef(CurTy);
836 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
838 return Error("Invalid CST_AGGREGATE record");
840 unsigned Size = Record.size();
841 std::vector<Constant*> Elts;
843 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
844 for (unsigned i = 0; i != Size; ++i)
845 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
846 STy->getElementType(i)));
847 V = Context.getConstantStruct(STy, Elts);
848 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
849 const Type *EltTy = ATy->getElementType();
850 for (unsigned i = 0; i != Size; ++i)
851 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
852 V = Context.getConstantArray(ATy, Elts);
853 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
854 const Type *EltTy = VTy->getElementType();
855 for (unsigned i = 0; i != Size; ++i)
856 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
857 V = Context.getConstantVector(Elts);
859 V = Context.getUndef(CurTy);
863 case bitc::CST_CODE_STRING: { // STRING: [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(Context.getConstantInt(EltTy, Record[i]));
874 V = Context.getConstantArray(ATy, Elts);
877 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
879 return Error("Invalid CST_AGGREGATE record");
881 const ArrayType *ATy = cast<ArrayType>(CurTy);
882 const Type *EltTy = ATy->getElementType();
884 unsigned Size = Record.size();
885 std::vector<Constant*> Elts;
886 for (unsigned i = 0; i != Size; ++i)
887 Elts.push_back(Context.getConstantInt(EltTy, Record[i]));
888 Elts.push_back(Context.getNullValue(EltTy));
889 V = Context.getConstantArray(ATy, Elts);
892 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
893 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
894 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
896 V = Context.getUndef(CurTy); // Unknown binop.
898 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
899 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
900 V = Context.getConstantExpr(Opc, LHS, RHS);
904 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
905 if (Record.size() < 3) return Error("Invalid CE_CAST record");
906 int Opc = GetDecodedCastOpcode(Record[0]);
908 V = Context.getUndef(CurTy); // Unknown cast.
910 const Type *OpTy = getTypeByID(Record[1]);
911 if (!OpTy) return Error("Invalid CE_CAST record");
912 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
913 V = Context.getConstantExprCast(Opc, Op, CurTy);
917 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
918 if (Record.size() & 1) return Error("Invalid CE_GEP record");
919 SmallVector<Constant*, 16> Elts;
920 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
921 const Type *ElTy = getTypeByID(Record[i]);
922 if (!ElTy) return Error("Invalid CE_GEP record");
923 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
925 V = Context.getConstantExprGetElementPtr(Elts[0], &Elts[1],
929 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
930 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
931 V = Context.getConstantExprSelect(ValueList.getConstantFwdRef(Record[0],
933 ValueList.getConstantFwdRef(Record[1],CurTy),
934 ValueList.getConstantFwdRef(Record[2],CurTy));
936 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
937 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
938 const VectorType *OpTy =
939 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
940 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
941 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
942 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
943 V = Context.getConstantExprExtractElement(Op0, Op1);
946 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
947 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
948 if (Record.size() < 3 || OpTy == 0)
949 return Error("Invalid CE_INSERTELT record");
950 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
951 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
952 OpTy->getElementType());
953 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
954 V = Context.getConstantExprInsertElement(Op0, Op1, Op2);
957 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
958 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
959 if (Record.size() < 3 || OpTy == 0)
960 return Error("Invalid CE_SHUFFLEVEC record");
961 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
962 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
963 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
964 OpTy->getNumElements());
965 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
966 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
969 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
970 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
971 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
972 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
973 return Error("Invalid CE_SHUFVEC_EX record");
974 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
975 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
976 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
977 RTy->getNumElements());
978 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
979 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
982 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
983 if (Record.size() < 4) return Error("Invalid CE_CMP record");
984 const Type *OpTy = getTypeByID(Record[0]);
985 if (OpTy == 0) return Error("Invalid CE_CMP record");
986 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
987 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
989 if (OpTy->isFloatingPoint())
990 V = Context.getConstantExprFCmp(Record[3], Op0, Op1);
992 V = Context.getConstantExprICmp(Record[3], Op0, Op1);
995 case bitc::CST_CODE_INLINEASM: {
996 if (Record.size() < 2) return Error("Invalid INLINEASM record");
997 std::string AsmStr, ConstrStr;
998 bool HasSideEffects = Record[0];
999 unsigned AsmStrSize = Record[1];
1000 if (2+AsmStrSize >= Record.size())
1001 return Error("Invalid INLINEASM record");
1002 unsigned ConstStrSize = Record[2+AsmStrSize];
1003 if (3+AsmStrSize+ConstStrSize > Record.size())
1004 return Error("Invalid INLINEASM record");
1006 for (unsigned i = 0; i != AsmStrSize; ++i)
1007 AsmStr += (char)Record[2+i];
1008 for (unsigned i = 0; i != ConstStrSize; ++i)
1009 ConstrStr += (char)Record[3+AsmStrSize+i];
1010 const PointerType *PTy = cast<PointerType>(CurTy);
1011 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1012 AsmStr, ConstrStr, HasSideEffects);
1015 case bitc::CST_CODE_MDSTRING: {
1016 unsigned MDStringLength = Record.size();
1017 SmallString<8> String;
1018 String.resize(MDStringLength);
1019 for (unsigned i = 0; i != MDStringLength; ++i)
1020 String[i] = Record[i];
1021 V = Context.getMDString(String.c_str(), String.c_str() + MDStringLength);
1024 case bitc::CST_CODE_MDNODE: {
1025 if (Record.empty() || Record.size() % 2 == 1)
1026 return Error("Invalid CST_MDNODE record");
1028 unsigned Size = Record.size();
1029 SmallVector<Value*, 8> Elts;
1030 for (unsigned i = 0; i != Size; i += 2) {
1031 const Type *Ty = getTypeByID(Record[i], false);
1032 if (Ty != Type::VoidTy)
1033 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1035 Elts.push_back(NULL);
1037 V = Context.getMDNode(&Elts[0], Elts.size());
1042 ValueList.AssignValue(V, NextCstNo);
1046 if (NextCstNo != ValueList.size())
1047 return Error("Invalid constant reference!");
1049 if (Stream.ReadBlockEnd())
1050 return Error("Error at end of constants block");
1052 // Once all the constants have been read, go through and resolve forward
1054 ValueList.ResolveConstantForwardRefs();
1058 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1059 /// remember where it is and then skip it. This lets us lazily deserialize the
1061 bool BitcodeReader::RememberAndSkipFunctionBody() {
1062 // Get the function we are talking about.
1063 if (FunctionsWithBodies.empty())
1064 return Error("Insufficient function protos");
1066 Function *Fn = FunctionsWithBodies.back();
1067 FunctionsWithBodies.pop_back();
1069 // Save the current stream state.
1070 uint64_t CurBit = Stream.GetCurrentBitNo();
1071 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1073 // Set the functions linkage to GhostLinkage so we know it is lazily
1075 Fn->setLinkage(GlobalValue::GhostLinkage);
1077 // Skip over the function block for now.
1078 if (Stream.SkipBlock())
1079 return Error("Malformed block record");
1083 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1084 // Reject multiple MODULE_BLOCK's in a single bitstream.
1086 return Error("Multiple MODULE_BLOCKs in same stream");
1088 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1089 return Error("Malformed block record");
1091 // Otherwise, create the module.
1092 TheModule = new Module(ModuleID, Context);
1094 SmallVector<uint64_t, 64> Record;
1095 std::vector<std::string> SectionTable;
1096 std::vector<std::string> GCTable;
1098 // Read all the records for this module.
1099 while (!Stream.AtEndOfStream()) {
1100 unsigned Code = Stream.ReadCode();
1101 if (Code == bitc::END_BLOCK) {
1102 if (Stream.ReadBlockEnd())
1103 return Error("Error at end of module block");
1105 // Patch the initializers for globals and aliases up.
1106 ResolveGlobalAndAliasInits();
1107 if (!GlobalInits.empty() || !AliasInits.empty())
1108 return Error("Malformed global initializer set");
1109 if (!FunctionsWithBodies.empty())
1110 return Error("Too few function bodies found");
1112 // Look for intrinsic functions which need to be upgraded at some point
1113 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1116 if (UpgradeIntrinsicFunction(FI, NewFn))
1117 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1120 // Force deallocation of memory for these vectors to favor the client that
1121 // want lazy deserialization.
1122 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1123 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1124 std::vector<Function*>().swap(FunctionsWithBodies);
1128 if (Code == bitc::ENTER_SUBBLOCK) {
1129 switch (Stream.ReadSubBlockID()) {
1130 default: // Skip unknown content.
1131 if (Stream.SkipBlock())
1132 return Error("Malformed block record");
1134 case bitc::BLOCKINFO_BLOCK_ID:
1135 if (Stream.ReadBlockInfoBlock())
1136 return Error("Malformed BlockInfoBlock");
1138 case bitc::PARAMATTR_BLOCK_ID:
1139 if (ParseAttributeBlock())
1142 case bitc::TYPE_BLOCK_ID:
1143 if (ParseTypeTable())
1146 case bitc::TYPE_SYMTAB_BLOCK_ID:
1147 if (ParseTypeSymbolTable())
1150 case bitc::VALUE_SYMTAB_BLOCK_ID:
1151 if (ParseValueSymbolTable())
1154 case bitc::CONSTANTS_BLOCK_ID:
1155 if (ParseConstants() || ResolveGlobalAndAliasInits())
1158 case bitc::FUNCTION_BLOCK_ID:
1159 // If this is the first function body we've seen, reverse the
1160 // FunctionsWithBodies list.
1161 if (!HasReversedFunctionsWithBodies) {
1162 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1163 HasReversedFunctionsWithBodies = true;
1166 if (RememberAndSkipFunctionBody())
1173 if (Code == bitc::DEFINE_ABBREV) {
1174 Stream.ReadAbbrevRecord();
1179 switch (Stream.ReadRecord(Code, Record)) {
1180 default: break; // Default behavior, ignore unknown content.
1181 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1182 if (Record.size() < 1)
1183 return Error("Malformed MODULE_CODE_VERSION");
1184 // Only version #0 is supported so far.
1186 return Error("Unknown bitstream version!");
1188 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1190 if (ConvertToString(Record, 0, S))
1191 return Error("Invalid MODULE_CODE_TRIPLE record");
1192 TheModule->setTargetTriple(S);
1195 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1197 if (ConvertToString(Record, 0, S))
1198 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1199 TheModule->setDataLayout(S);
1202 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1204 if (ConvertToString(Record, 0, S))
1205 return Error("Invalid MODULE_CODE_ASM record");
1206 TheModule->setModuleInlineAsm(S);
1209 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1211 if (ConvertToString(Record, 0, S))
1212 return Error("Invalid MODULE_CODE_DEPLIB record");
1213 TheModule->addLibrary(S);
1216 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1218 if (ConvertToString(Record, 0, S))
1219 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1220 SectionTable.push_back(S);
1223 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1225 if (ConvertToString(Record, 0, S))
1226 return Error("Invalid MODULE_CODE_GCNAME record");
1227 GCTable.push_back(S);
1230 // GLOBALVAR: [pointer type, isconst, initid,
1231 // linkage, alignment, section, visibility, threadlocal]
1232 case bitc::MODULE_CODE_GLOBALVAR: {
1233 if (Record.size() < 6)
1234 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1235 const Type *Ty = getTypeByID(Record[0]);
1236 if (!isa<PointerType>(Ty))
1237 return Error("Global not a pointer type!");
1238 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1239 Ty = cast<PointerType>(Ty)->getElementType();
1241 bool isConstant = Record[1];
1242 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1243 unsigned Alignment = (1 << Record[4]) >> 1;
1244 std::string Section;
1246 if (Record[5]-1 >= SectionTable.size())
1247 return Error("Invalid section ID");
1248 Section = SectionTable[Record[5]-1];
1250 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1251 if (Record.size() > 6)
1252 Visibility = GetDecodedVisibility(Record[6]);
1253 bool isThreadLocal = false;
1254 if (Record.size() > 7)
1255 isThreadLocal = Record[7];
1257 GlobalVariable *NewGV =
1258 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1259 isThreadLocal, AddressSpace);
1260 NewGV->setAlignment(Alignment);
1261 if (!Section.empty())
1262 NewGV->setSection(Section);
1263 NewGV->setVisibility(Visibility);
1264 NewGV->setThreadLocal(isThreadLocal);
1266 ValueList.push_back(NewGV);
1268 // Remember which value to use for the global initializer.
1269 if (unsigned InitID = Record[2])
1270 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1273 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1274 // alignment, section, visibility, gc]
1275 case bitc::MODULE_CODE_FUNCTION: {
1276 if (Record.size() < 8)
1277 return Error("Invalid MODULE_CODE_FUNCTION record");
1278 const Type *Ty = getTypeByID(Record[0]);
1279 if (!isa<PointerType>(Ty))
1280 return Error("Function not a pointer type!");
1281 const FunctionType *FTy =
1282 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1284 return Error("Function not a pointer to function type!");
1286 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1289 Func->setCallingConv(Record[1]);
1290 bool isProto = Record[2];
1291 Func->setLinkage(GetDecodedLinkage(Record[3]));
1292 Func->setAttributes(getAttributes(Record[4]));
1294 Func->setAlignment((1 << Record[5]) >> 1);
1296 if (Record[6]-1 >= SectionTable.size())
1297 return Error("Invalid section ID");
1298 Func->setSection(SectionTable[Record[6]-1]);
1300 Func->setVisibility(GetDecodedVisibility(Record[7]));
1301 if (Record.size() > 8 && Record[8]) {
1302 if (Record[8]-1 > GCTable.size())
1303 return Error("Invalid GC ID");
1304 Func->setGC(GCTable[Record[8]-1].c_str());
1306 ValueList.push_back(Func);
1308 // If this is a function with a body, remember the prototype we are
1309 // creating now, so that we can match up the body with them later.
1311 FunctionsWithBodies.push_back(Func);
1314 // ALIAS: [alias type, aliasee val#, linkage]
1315 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1316 case bitc::MODULE_CODE_ALIAS: {
1317 if (Record.size() < 3)
1318 return Error("Invalid MODULE_ALIAS record");
1319 const Type *Ty = getTypeByID(Record[0]);
1320 if (!isa<PointerType>(Ty))
1321 return Error("Function not a pointer type!");
1323 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1325 // Old bitcode files didn't have visibility field.
1326 if (Record.size() > 3)
1327 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1328 ValueList.push_back(NewGA);
1329 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1332 /// MODULE_CODE_PURGEVALS: [numvals]
1333 case bitc::MODULE_CODE_PURGEVALS:
1334 // Trim down the value list to the specified size.
1335 if (Record.size() < 1 || Record[0] > ValueList.size())
1336 return Error("Invalid MODULE_PURGEVALS record");
1337 ValueList.shrinkTo(Record[0]);
1343 return Error("Premature end of bitstream");
1346 bool BitcodeReader::ParseBitcode() {
1349 if (Buffer->getBufferSize() & 3)
1350 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1352 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1353 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1355 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1356 // The magic number is 0x0B17C0DE stored in little endian.
1357 if (isBitcodeWrapper(BufPtr, BufEnd))
1358 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1359 return Error("Invalid bitcode wrapper header");
1361 StreamFile.init(BufPtr, BufEnd);
1362 Stream.init(StreamFile);
1364 // Sniff for the signature.
1365 if (Stream.Read(8) != 'B' ||
1366 Stream.Read(8) != 'C' ||
1367 Stream.Read(4) != 0x0 ||
1368 Stream.Read(4) != 0xC ||
1369 Stream.Read(4) != 0xE ||
1370 Stream.Read(4) != 0xD)
1371 return Error("Invalid bitcode signature");
1373 // We expect a number of well-defined blocks, though we don't necessarily
1374 // need to understand them all.
1375 while (!Stream.AtEndOfStream()) {
1376 unsigned Code = Stream.ReadCode();
1378 if (Code != bitc::ENTER_SUBBLOCK)
1379 return Error("Invalid record at top-level");
1381 unsigned BlockID = Stream.ReadSubBlockID();
1383 // We only know the MODULE subblock ID.
1385 case bitc::BLOCKINFO_BLOCK_ID:
1386 if (Stream.ReadBlockInfoBlock())
1387 return Error("Malformed BlockInfoBlock");
1389 case bitc::MODULE_BLOCK_ID:
1390 if (ParseModule(Buffer->getBufferIdentifier()))
1394 if (Stream.SkipBlock())
1395 return Error("Malformed block record");
1404 /// ParseFunctionBody - Lazily parse the specified function body block.
1405 bool BitcodeReader::ParseFunctionBody(Function *F) {
1406 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1407 return Error("Malformed block record");
1409 unsigned ModuleValueListSize = ValueList.size();
1411 // Add all the function arguments to the value table.
1412 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1413 ValueList.push_back(I);
1415 unsigned NextValueNo = ValueList.size();
1416 BasicBlock *CurBB = 0;
1417 unsigned CurBBNo = 0;
1419 // Read all the records.
1420 SmallVector<uint64_t, 64> Record;
1422 unsigned Code = Stream.ReadCode();
1423 if (Code == bitc::END_BLOCK) {
1424 if (Stream.ReadBlockEnd())
1425 return Error("Error at end of function block");
1429 if (Code == bitc::ENTER_SUBBLOCK) {
1430 switch (Stream.ReadSubBlockID()) {
1431 default: // Skip unknown content.
1432 if (Stream.SkipBlock())
1433 return Error("Malformed block record");
1435 case bitc::CONSTANTS_BLOCK_ID:
1436 if (ParseConstants()) return true;
1437 NextValueNo = ValueList.size();
1439 case bitc::VALUE_SYMTAB_BLOCK_ID:
1440 if (ParseValueSymbolTable()) return true;
1446 if (Code == bitc::DEFINE_ABBREV) {
1447 Stream.ReadAbbrevRecord();
1454 switch (Stream.ReadRecord(Code, Record)) {
1455 default: // Default behavior: reject
1456 return Error("Unknown instruction");
1457 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1458 if (Record.size() < 1 || Record[0] == 0)
1459 return Error("Invalid DECLAREBLOCKS record");
1460 // Create all the basic blocks for the function.
1461 FunctionBBs.resize(Record[0]);
1462 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1463 FunctionBBs[i] = BasicBlock::Create("", F);
1464 CurBB = FunctionBBs[0];
1467 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1470 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1471 getValue(Record, OpNum, LHS->getType(), RHS) ||
1472 OpNum+1 != Record.size())
1473 return Error("Invalid BINOP record");
1475 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1476 if (Opc == -1) return Error("Invalid BINOP record");
1477 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1480 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1483 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1484 OpNum+2 != Record.size())
1485 return Error("Invalid CAST record");
1487 const Type *ResTy = getTypeByID(Record[OpNum]);
1488 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1489 if (Opc == -1 || ResTy == 0)
1490 return Error("Invalid CAST record");
1491 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1494 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1497 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1498 return Error("Invalid GEP record");
1500 SmallVector<Value*, 16> GEPIdx;
1501 while (OpNum != Record.size()) {
1503 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1504 return Error("Invalid GEP record");
1505 GEPIdx.push_back(Op);
1508 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1512 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1513 // EXTRACTVAL: [opty, opval, n x indices]
1516 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1517 return Error("Invalid EXTRACTVAL record");
1519 SmallVector<unsigned, 4> EXTRACTVALIdx;
1520 for (unsigned RecSize = Record.size();
1521 OpNum != RecSize; ++OpNum) {
1522 uint64_t Index = Record[OpNum];
1523 if ((unsigned)Index != Index)
1524 return Error("Invalid EXTRACTVAL index");
1525 EXTRACTVALIdx.push_back((unsigned)Index);
1528 I = ExtractValueInst::Create(Agg,
1529 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1533 case bitc::FUNC_CODE_INST_INSERTVAL: {
1534 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1537 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1538 return Error("Invalid INSERTVAL record");
1540 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1541 return Error("Invalid INSERTVAL record");
1543 SmallVector<unsigned, 4> INSERTVALIdx;
1544 for (unsigned RecSize = Record.size();
1545 OpNum != RecSize; ++OpNum) {
1546 uint64_t Index = Record[OpNum];
1547 if ((unsigned)Index != Index)
1548 return Error("Invalid INSERTVAL index");
1549 INSERTVALIdx.push_back((unsigned)Index);
1552 I = InsertValueInst::Create(Agg, Val,
1553 INSERTVALIdx.begin(), INSERTVALIdx.end());
1557 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1558 // obsolete form of select
1559 // handles select i1 ... in old bitcode
1561 Value *TrueVal, *FalseVal, *Cond;
1562 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1563 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1564 getValue(Record, OpNum, Type::Int1Ty, Cond))
1565 return Error("Invalid SELECT record");
1567 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1571 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1572 // new form of select
1573 // handles select i1 or select [N x i1]
1575 Value *TrueVal, *FalseVal, *Cond;
1576 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1577 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1578 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1579 return Error("Invalid SELECT record");
1581 // select condition can be either i1 or [N x i1]
1582 if (const VectorType* vector_type =
1583 dyn_cast<const VectorType>(Cond->getType())) {
1585 if (vector_type->getElementType() != Type::Int1Ty)
1586 return Error("Invalid SELECT condition type");
1589 if (Cond->getType() != Type::Int1Ty)
1590 return Error("Invalid SELECT condition type");
1593 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1597 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1600 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1601 getValue(Record, OpNum, Type::Int32Ty, Idx))
1602 return Error("Invalid EXTRACTELT record");
1603 I = new ExtractElementInst(Vec, Idx);
1607 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1609 Value *Vec, *Elt, *Idx;
1610 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1611 getValue(Record, OpNum,
1612 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1613 getValue(Record, OpNum, Type::Int32Ty, Idx))
1614 return Error("Invalid INSERTELT record");
1615 I = InsertElementInst::Create(Vec, Elt, Idx);
1619 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1621 Value *Vec1, *Vec2, *Mask;
1622 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1623 getValue(Record, OpNum, Vec1->getType(), Vec2))
1624 return Error("Invalid SHUFFLEVEC record");
1626 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1627 return Error("Invalid SHUFFLEVEC record");
1628 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1632 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1633 // Old form of ICmp/FCmp returning bool
1634 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1635 // both legal on vectors but had different behaviour.
1636 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1637 // FCmp/ICmp returning bool or vector of 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()->isFPOrFPVector())
1647 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1649 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1653 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1654 if (Record.size() != 2)
1655 return Error("Invalid GETRESULT record");
1658 getValueTypePair(Record, OpNum, NextValueNo, Op);
1659 unsigned Index = Record[1];
1660 I = ExtractValueInst::Create(Op, Index);
1664 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1666 unsigned Size = Record.size();
1668 I = ReturnInst::Create();
1673 SmallVector<Value *,4> Vs;
1676 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1677 return Error("Invalid RET record");
1679 } while(OpNum != Record.size());
1681 const Type *ReturnType = F->getReturnType();
1682 if (Vs.size() > 1 ||
1683 (isa<StructType>(ReturnType) &&
1684 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1685 Value *RV = Context.getUndef(ReturnType);
1686 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1687 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1688 CurBB->getInstList().push_back(I);
1689 ValueList.AssignValue(I, NextValueNo++);
1692 I = ReturnInst::Create(RV);
1696 I = ReturnInst::Create(Vs[0]);
1699 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1700 if (Record.size() != 1 && Record.size() != 3)
1701 return Error("Invalid BR record");
1702 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1704 return Error("Invalid BR record");
1706 if (Record.size() == 1)
1707 I = BranchInst::Create(TrueDest);
1709 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1710 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1711 if (FalseDest == 0 || Cond == 0)
1712 return Error("Invalid BR record");
1713 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1717 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1718 if (Record.size() < 3 || (Record.size() & 1) == 0)
1719 return Error("Invalid SWITCH record");
1720 const Type *OpTy = getTypeByID(Record[0]);
1721 Value *Cond = getFnValueByID(Record[1], OpTy);
1722 BasicBlock *Default = getBasicBlock(Record[2]);
1723 if (OpTy == 0 || Cond == 0 || Default == 0)
1724 return Error("Invalid SWITCH record");
1725 unsigned NumCases = (Record.size()-3)/2;
1726 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1727 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1728 ConstantInt *CaseVal =
1729 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1730 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1731 if (CaseVal == 0 || DestBB == 0) {
1733 return Error("Invalid SWITCH record!");
1735 SI->addCase(CaseVal, DestBB);
1741 case bitc::FUNC_CODE_INST_INVOKE: {
1742 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1743 if (Record.size() < 4) return Error("Invalid INVOKE record");
1744 AttrListPtr PAL = getAttributes(Record[0]);
1745 unsigned CCInfo = Record[1];
1746 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1747 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1751 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1752 return Error("Invalid INVOKE record");
1754 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1755 const FunctionType *FTy = !CalleeTy ? 0 :
1756 dyn_cast<FunctionType>(CalleeTy->getElementType());
1758 // Check that the right number of fixed parameters are here.
1759 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1760 Record.size() < OpNum+FTy->getNumParams())
1761 return Error("Invalid INVOKE record");
1763 SmallVector<Value*, 16> Ops;
1764 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1765 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1766 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1769 if (!FTy->isVarArg()) {
1770 if (Record.size() != OpNum)
1771 return Error("Invalid INVOKE record");
1773 // Read type/value pairs for varargs params.
1774 while (OpNum != Record.size()) {
1776 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1777 return Error("Invalid INVOKE record");
1782 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1783 Ops.begin(), Ops.end());
1784 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1785 cast<InvokeInst>(I)->setAttributes(PAL);
1788 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1789 I = new UnwindInst();
1791 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1792 I = new UnreachableInst();
1794 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1795 if (Record.size() < 1 || ((Record.size()-1)&1))
1796 return Error("Invalid PHI record");
1797 const Type *Ty = getTypeByID(Record[0]);
1798 if (!Ty) return Error("Invalid PHI record");
1800 PHINode *PN = PHINode::Create(Ty);
1801 PN->reserveOperandSpace((Record.size()-1)/2);
1803 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1804 Value *V = getFnValueByID(Record[1+i], Ty);
1805 BasicBlock *BB = getBasicBlock(Record[2+i]);
1806 if (!V || !BB) return Error("Invalid PHI record");
1807 PN->addIncoming(V, BB);
1813 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1814 if (Record.size() < 3)
1815 return Error("Invalid MALLOC record");
1816 const PointerType *Ty =
1817 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1818 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1819 unsigned Align = Record[2];
1820 if (!Ty || !Size) return Error("Invalid MALLOC record");
1821 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1824 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1827 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1828 OpNum != Record.size())
1829 return Error("Invalid FREE record");
1830 I = new FreeInst(Op);
1833 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1834 if (Record.size() < 3)
1835 return Error("Invalid ALLOCA record");
1836 const PointerType *Ty =
1837 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1838 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1839 unsigned Align = Record[2];
1840 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1841 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1844 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1847 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1848 OpNum+2 != Record.size())
1849 return Error("Invalid LOAD record");
1851 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1854 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1857 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1858 getValue(Record, OpNum,
1859 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1860 OpNum+2 != Record.size())
1861 return Error("Invalid STORE record");
1863 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1866 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1867 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1870 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1871 getValue(Record, OpNum,
1872 Context.getPointerTypeUnqual(Val->getType()), Ptr)||
1873 OpNum+2 != Record.size())
1874 return Error("Invalid STORE record");
1876 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1879 case bitc::FUNC_CODE_INST_CALL: {
1880 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1881 if (Record.size() < 3)
1882 return Error("Invalid CALL record");
1884 AttrListPtr PAL = getAttributes(Record[0]);
1885 unsigned CCInfo = Record[1];
1889 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1890 return Error("Invalid CALL record");
1892 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1893 const FunctionType *FTy = 0;
1894 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1895 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1896 return Error("Invalid CALL record");
1898 SmallVector<Value*, 16> Args;
1899 // Read the fixed params.
1900 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1901 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1902 Args.push_back(getBasicBlock(Record[OpNum]));
1904 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1905 if (Args.back() == 0) return Error("Invalid CALL record");
1908 // Read type/value pairs for varargs params.
1909 if (!FTy->isVarArg()) {
1910 if (OpNum != Record.size())
1911 return Error("Invalid CALL record");
1913 while (OpNum != Record.size()) {
1915 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1916 return Error("Invalid CALL record");
1921 I = CallInst::Create(Callee, Args.begin(), Args.end());
1922 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1923 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1924 cast<CallInst>(I)->setAttributes(PAL);
1927 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1928 if (Record.size() < 3)
1929 return Error("Invalid VAARG record");
1930 const Type *OpTy = getTypeByID(Record[0]);
1931 Value *Op = getFnValueByID(Record[1], OpTy);
1932 const Type *ResTy = getTypeByID(Record[2]);
1933 if (!OpTy || !Op || !ResTy)
1934 return Error("Invalid VAARG record");
1935 I = new VAArgInst(Op, ResTy);
1940 // Add instruction to end of current BB. If there is no current BB, reject
1944 return Error("Invalid instruction with no BB");
1946 CurBB->getInstList().push_back(I);
1948 // If this was a terminator instruction, move to the next block.
1949 if (isa<TerminatorInst>(I)) {
1951 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1954 // Non-void values get registered in the value table for future use.
1955 if (I && I->getType() != Type::VoidTy)
1956 ValueList.AssignValue(I, NextValueNo++);
1959 // Check the function list for unresolved values.
1960 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1961 if (A->getParent() == 0) {
1962 // We found at least one unresolved value. Nuke them all to avoid leaks.
1963 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1964 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1965 A->replaceAllUsesWith(Context.getUndef(A->getType()));
1969 return Error("Never resolved value found in function!");
1973 // Trim the value list down to the size it was before we parsed this function.
1974 ValueList.shrinkTo(ModuleValueListSize);
1975 std::vector<BasicBlock*>().swap(FunctionBBs);
1980 //===----------------------------------------------------------------------===//
1981 // ModuleProvider implementation
1982 //===----------------------------------------------------------------------===//
1985 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1986 // If it already is material, ignore the request.
1987 if (!F->hasNotBeenReadFromBitcode()) return false;
1989 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1990 DeferredFunctionInfo.find(F);
1991 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1993 // Move the bit stream to the saved position of the deferred function body and
1994 // restore the real linkage type for the function.
1995 Stream.JumpToBit(DFII->second.first);
1996 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1998 if (ParseFunctionBody(F)) {
1999 if (ErrInfo) *ErrInfo = ErrorString;
2003 // Upgrade any old intrinsic calls in the function.
2004 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2005 E = UpgradedIntrinsics.end(); I != E; ++I) {
2006 if (I->first != I->second) {
2007 for (Value::use_iterator UI = I->first->use_begin(),
2008 UE = I->first->use_end(); UI != UE; ) {
2009 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2010 UpgradeIntrinsicCall(CI, I->second);
2018 void BitcodeReader::dematerializeFunction(Function *F) {
2019 // If this function isn't materialized, or if it is a proto, this is a noop.
2020 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2023 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2025 // Just forget the function body, we can remat it later.
2027 F->setLinkage(GlobalValue::GhostLinkage);
2031 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2032 // Iterate over the module, deserializing any functions that are still on
2034 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2036 if (F->hasNotBeenReadFromBitcode() &&
2037 materializeFunction(F, ErrInfo))
2040 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2041 // delete the old functions to clean up. We can't do this unless the entire
2042 // module is materialized because there could always be another function body
2043 // with calls to the old function.
2044 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2045 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2046 if (I->first != I->second) {
2047 for (Value::use_iterator UI = I->first->use_begin(),
2048 UE = I->first->use_end(); UI != UE; ) {
2049 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2050 UpgradeIntrinsicCall(CI, I->second);
2052 if (!I->first->use_empty())
2053 I->first->replaceAllUsesWith(I->second);
2054 I->first->eraseFromParent();
2057 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2063 /// This method is provided by the parent ModuleProvde class and overriden
2064 /// here. It simply releases the module from its provided and frees up our
2066 /// @brief Release our hold on the generated module
2067 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2068 // Since we're losing control of this Module, we must hand it back complete
2069 Module *M = ModuleProvider::releaseModule(ErrInfo);
2075 //===----------------------------------------------------------------------===//
2076 // External interface
2077 //===----------------------------------------------------------------------===//
2079 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2081 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2082 LLVMContext& Context,
2083 std::string *ErrMsg) {
2084 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2085 if (R->ParseBitcode()) {
2087 *ErrMsg = R->getErrorString();
2089 // Don't let the BitcodeReader dtor delete 'Buffer'.
2090 R->releaseMemoryBuffer();
2097 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2098 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2099 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2100 std::string *ErrMsg){
2102 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2106 // Read in the entire module.
2107 Module *M = R->materializeModule(ErrMsg);
2109 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2110 // there was an error.
2111 R->releaseMemoryBuffer();
2113 // If there was no error, tell ModuleProvider not to delete it when its dtor
2116 M = R->releaseModule(ErrMsg);