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);
154 // FIXME: can we inherit this from ConstantExpr?
156 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
159 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
162 void BitcodeReaderValueList::resize(unsigned Desired) {
163 if (Desired > Capacity) {
164 // Since we expect many values to come from the bitcode file we better
165 // allocate the double amount, so that the array size grows exponentially
166 // at each reallocation. Also, add a small amount of 100 extra elements
167 // each time, to reallocate less frequently when the array is still small.
169 Capacity = Desired * 2 + 100;
170 Use *New = allocHungoffUses(Capacity);
171 Use *Old = OperandList;
172 unsigned Ops = getNumOperands();
173 for (int i(Ops - 1); i >= 0; --i)
174 New[i] = Old[i].get();
176 if (Old) Use::zap(Old, Old + Ops, true);
180 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
183 // Insert a bunch of null values.
188 if (Value *V = OperandList[Idx]) {
189 assert(Ty == V->getType() && "Type mismatch in constant table!");
190 return cast<Constant>(V);
193 // Create and return a placeholder, which will later be RAUW'd.
194 Constant *C = new ConstantPlaceHolder(Ty);
195 OperandList[Idx] = C;
199 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
201 // Insert a bunch of null values.
206 if (Value *V = OperandList[Idx]) {
207 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
211 // No type specified, must be invalid reference.
212 if (Ty == 0) return 0;
214 // Create and return a placeholder, which will later be RAUW'd.
215 Value *V = new Argument(Ty);
216 OperandList[Idx] = V;
220 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
221 /// resolves any forward references. The idea behind this is that we sometimes
222 /// get constants (such as large arrays) which reference *many* forward ref
223 /// constants. Replacing each of these causes a lot of thrashing when
224 /// building/reuniquing the constant. Instead of doing this, we look at all the
225 /// uses and rewrite all the place holders at once for any constant that uses
227 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
228 // Sort the values by-pointer so that they are efficient to look up with a
230 std::sort(ResolveConstants.begin(), ResolveConstants.end());
232 SmallVector<Constant*, 64> NewOps;
234 while (!ResolveConstants.empty()) {
235 Value *RealVal = getOperand(ResolveConstants.back().second);
236 Constant *Placeholder = ResolveConstants.back().first;
237 ResolveConstants.pop_back();
239 // Loop over all users of the placeholder, updating them to reference the
240 // new value. If they reference more than one placeholder, update them all
242 while (!Placeholder->use_empty()) {
243 Value::use_iterator UI = Placeholder->use_begin();
245 // If the using object isn't uniqued, just update the operands. This
246 // handles instructions and initializers for global variables.
247 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
248 UI.getUse().set(RealVal);
252 // Otherwise, we have a constant that uses the placeholder. Replace that
253 // constant with a new constant that has *all* placeholder uses updated.
254 Constant *UserC = cast<Constant>(*UI);
255 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
258 if (!isa<ConstantPlaceHolder>(*I)) {
259 // Not a placeholder reference.
261 } else if (*I == Placeholder) {
262 // Common case is that it just references this one placeholder.
265 // Otherwise, look up the placeholder in ResolveConstants.
266 ResolveConstantsTy::iterator It =
267 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
268 std::pair<Constant*, unsigned>(cast<Constant>(*I),
270 assert(It != ResolveConstants.end() && It->first == *I);
271 NewOp = this->getOperand(It->second);
274 NewOps.push_back(cast<Constant>(NewOp));
277 // Make the new constant.
279 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
280 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
281 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
282 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
283 UserCS->getType()->isPacked());
284 } else if (isa<ConstantVector>(UserC)) {
285 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
287 // Must be a constant expression.
288 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
292 UserC->replaceAllUsesWith(NewC);
293 UserC->destroyConstant();
302 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
303 // If the TypeID is in range, return it.
304 if (ID < TypeList.size())
305 return TypeList[ID].get();
306 if (!isTypeTable) return 0;
308 // The type table allows forward references. Push as many Opaque types as
309 // needed to get up to ID.
310 while (TypeList.size() <= ID)
311 TypeList.push_back(OpaqueType::get());
312 return TypeList.back().get();
315 //===----------------------------------------------------------------------===//
316 // Functions for parsing blocks from the bitcode file
317 //===----------------------------------------------------------------------===//
319 bool BitcodeReader::ParseAttributeBlock() {
320 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
321 return Error("Malformed block record");
323 if (!MAttributes.empty())
324 return Error("Multiple PARAMATTR blocks found!");
326 SmallVector<uint64_t, 64> Record;
328 SmallVector<AttributeWithIndex, 8> Attrs;
330 // Read all the records.
332 unsigned Code = Stream.ReadCode();
333 if (Code == bitc::END_BLOCK) {
334 if (Stream.ReadBlockEnd())
335 return Error("Error at end of PARAMATTR block");
339 if (Code == bitc::ENTER_SUBBLOCK) {
340 // No known subblocks, always skip them.
341 Stream.ReadSubBlockID();
342 if (Stream.SkipBlock())
343 return Error("Malformed block record");
347 if (Code == bitc::DEFINE_ABBREV) {
348 Stream.ReadAbbrevRecord();
354 switch (Stream.ReadRecord(Code, Record)) {
355 default: // Default behavior: ignore.
357 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
358 if (Record.size() & 1)
359 return Error("Invalid ENTRY record");
361 // FIXME : Remove this autoupgrade code in LLVM 3.0.
362 // If Function attributes are using index 0 then transfer them
363 // to index ~0. Index 0 is used for return value attributes but used to be
364 // used for function attributes.
365 Attributes RetAttribute = Attribute::None;
366 Attributes FnAttribute = Attribute::None;
367 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
368 // FIXME: remove in LLVM 3.0
369 // The alignment is stored as a 16-bit raw value from bits 31--16.
370 // We shift the bits above 31 down by 11 bits.
372 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
373 if (Alignment && !isPowerOf2_32(Alignment))
374 return Error("Alignment is not a power of two.");
376 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
378 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
379 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
380 Record[i+1] = ReconstitutedAttr;
383 RetAttribute = Record[i+1];
384 else if (Record[i] == ~0U)
385 FnAttribute = Record[i+1];
388 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
389 Attribute::ReadOnly|Attribute::ReadNone);
391 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
392 (RetAttribute & OldRetAttrs) != 0) {
393 if (FnAttribute == Attribute::None) { // add a slot so they get added.
394 Record.push_back(~0U);
398 FnAttribute |= RetAttribute & OldRetAttrs;
399 RetAttribute &= ~OldRetAttrs;
402 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
403 if (Record[i] == 0) {
404 if (RetAttribute != Attribute::None)
405 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
406 } else if (Record[i] == ~0U) {
407 if (FnAttribute != Attribute::None)
408 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
409 } else if (Record[i+1] != Attribute::None)
410 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
413 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
422 bool BitcodeReader::ParseTypeTable() {
423 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
424 return Error("Malformed block record");
426 if (!TypeList.empty())
427 return Error("Multiple TYPE_BLOCKs found!");
429 SmallVector<uint64_t, 64> Record;
430 unsigned NumRecords = 0;
432 // Read all the records for this type table.
434 unsigned Code = Stream.ReadCode();
435 if (Code == bitc::END_BLOCK) {
436 if (NumRecords != TypeList.size())
437 return Error("Invalid type forward reference in TYPE_BLOCK");
438 if (Stream.ReadBlockEnd())
439 return Error("Error at end of type table block");
443 if (Code == bitc::ENTER_SUBBLOCK) {
444 // No known subblocks, always skip them.
445 Stream.ReadSubBlockID();
446 if (Stream.SkipBlock())
447 return Error("Malformed block record");
451 if (Code == bitc::DEFINE_ABBREV) {
452 Stream.ReadAbbrevRecord();
458 const Type *ResultTy = 0;
459 switch (Stream.ReadRecord(Code, Record)) {
460 default: // Default behavior: unknown type.
463 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
464 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
465 // type list. This allows us to reserve space.
466 if (Record.size() < 1)
467 return Error("Invalid TYPE_CODE_NUMENTRY record");
468 TypeList.reserve(Record[0]);
470 case bitc::TYPE_CODE_VOID: // VOID
471 ResultTy = Type::VoidTy;
473 case bitc::TYPE_CODE_FLOAT: // FLOAT
474 ResultTy = Type::FloatTy;
476 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
477 ResultTy = Type::DoubleTy;
479 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
480 ResultTy = Type::X86_FP80Ty;
482 case bitc::TYPE_CODE_FP128: // FP128
483 ResultTy = Type::FP128Ty;
485 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
486 ResultTy = Type::PPC_FP128Ty;
488 case bitc::TYPE_CODE_LABEL: // LABEL
489 ResultTy = Type::LabelTy;
491 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
494 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
495 if (Record.size() < 1)
496 return Error("Invalid Integer type record");
498 ResultTy = IntegerType::get(Record[0]);
500 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
501 // [pointee type, address space]
502 if (Record.size() < 1)
503 return Error("Invalid POINTER type record");
504 unsigned AddressSpace = 0;
505 if (Record.size() == 2)
506 AddressSpace = Record[1];
507 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
510 case bitc::TYPE_CODE_FUNCTION: {
511 // FIXME: attrid is dead, remove it in LLVM 3.0
512 // FUNCTION: [vararg, attrid, retty, paramty x N]
513 if (Record.size() < 3)
514 return Error("Invalid FUNCTION type record");
515 std::vector<const Type*> ArgTys;
516 for (unsigned i = 3, e = Record.size(); i != e; ++i)
517 ArgTys.push_back(getTypeByID(Record[i], true));
519 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
523 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
524 if (Record.size() < 1)
525 return Error("Invalid STRUCT type record");
526 std::vector<const Type*> EltTys;
527 for (unsigned i = 1, e = Record.size(); i != e; ++i)
528 EltTys.push_back(getTypeByID(Record[i], true));
529 ResultTy = StructType::get(EltTys, Record[0]);
532 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
533 if (Record.size() < 2)
534 return Error("Invalid ARRAY type record");
535 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
537 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
538 if (Record.size() < 2)
539 return Error("Invalid VECTOR type record");
540 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
544 if (NumRecords == TypeList.size()) {
545 // If this is a new type slot, just append it.
546 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
548 } else if (ResultTy == 0) {
549 // Otherwise, this was forward referenced, so an opaque type was created,
550 // but the result type is actually just an opaque. Leave the one we
551 // created previously.
554 // Otherwise, this was forward referenced, so an opaque type was created.
555 // Resolve the opaque type to the real type now.
556 assert(NumRecords < TypeList.size() && "Typelist imbalance");
557 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
559 // Don't directly push the new type on the Tab. Instead we want to replace
560 // the opaque type we previously inserted with the new concrete value. The
561 // refinement from the abstract (opaque) type to the new type causes all
562 // uses of the abstract type to use the concrete type (NewTy). This will
563 // also cause the opaque type to be deleted.
564 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
566 // This should have replaced the old opaque type with the new type in the
567 // value table... or with a preexisting type that was already in the
568 // system. Let's just make sure it did.
569 assert(TypeList[NumRecords-1].get() != OldTy &&
570 "refineAbstractType didn't work!");
576 bool BitcodeReader::ParseTypeSymbolTable() {
577 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
578 return Error("Malformed block record");
580 SmallVector<uint64_t, 64> Record;
582 // Read all the records for this type table.
583 std::string TypeName;
585 unsigned Code = Stream.ReadCode();
586 if (Code == bitc::END_BLOCK) {
587 if (Stream.ReadBlockEnd())
588 return Error("Error at end of type symbol table block");
592 if (Code == bitc::ENTER_SUBBLOCK) {
593 // No known subblocks, always skip them.
594 Stream.ReadSubBlockID();
595 if (Stream.SkipBlock())
596 return Error("Malformed block record");
600 if (Code == bitc::DEFINE_ABBREV) {
601 Stream.ReadAbbrevRecord();
607 switch (Stream.ReadRecord(Code, Record)) {
608 default: // Default behavior: unknown type.
610 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
611 if (ConvertToString(Record, 1, TypeName))
612 return Error("Invalid TST_ENTRY record");
613 unsigned TypeID = Record[0];
614 if (TypeID >= TypeList.size())
615 return Error("Invalid Type ID in TST_ENTRY record");
617 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
624 bool BitcodeReader::ParseValueSymbolTable() {
625 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
626 return Error("Malformed block record");
628 SmallVector<uint64_t, 64> Record;
630 // Read all the records for this value table.
631 SmallString<128> ValueName;
633 unsigned Code = Stream.ReadCode();
634 if (Code == bitc::END_BLOCK) {
635 if (Stream.ReadBlockEnd())
636 return Error("Error at end of value symbol table block");
639 if (Code == bitc::ENTER_SUBBLOCK) {
640 // No known subblocks, always skip them.
641 Stream.ReadSubBlockID();
642 if (Stream.SkipBlock())
643 return Error("Malformed block record");
647 if (Code == bitc::DEFINE_ABBREV) {
648 Stream.ReadAbbrevRecord();
654 switch (Stream.ReadRecord(Code, Record)) {
655 default: // Default behavior: unknown type.
657 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
658 if (ConvertToString(Record, 1, ValueName))
659 return Error("Invalid TST_ENTRY record");
660 unsigned ValueID = Record[0];
661 if (ValueID >= ValueList.size())
662 return Error("Invalid Value ID in VST_ENTRY record");
663 Value *V = ValueList[ValueID];
665 V->setName(&ValueName[0], ValueName.size());
669 case bitc::VST_CODE_BBENTRY: {
670 if (ConvertToString(Record, 1, ValueName))
671 return Error("Invalid VST_BBENTRY record");
672 BasicBlock *BB = getBasicBlock(Record[0]);
674 return Error("Invalid BB ID in VST_BBENTRY record");
676 BB->setName(&ValueName[0], ValueName.size());
684 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
685 /// the LSB for dense VBR encoding.
686 static uint64_t DecodeSignRotatedValue(uint64_t V) {
691 // There is no such thing as -0 with integers. "-0" really means MININT.
695 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
696 /// values and aliases that we can.
697 bool BitcodeReader::ResolveGlobalAndAliasInits() {
698 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
699 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
701 GlobalInitWorklist.swap(GlobalInits);
702 AliasInitWorklist.swap(AliasInits);
704 while (!GlobalInitWorklist.empty()) {
705 unsigned ValID = GlobalInitWorklist.back().second;
706 if (ValID >= ValueList.size()) {
707 // Not ready to resolve this yet, it requires something later in the file.
708 GlobalInits.push_back(GlobalInitWorklist.back());
710 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
711 GlobalInitWorklist.back().first->setInitializer(C);
713 return Error("Global variable initializer is not a constant!");
715 GlobalInitWorklist.pop_back();
718 while (!AliasInitWorklist.empty()) {
719 unsigned ValID = AliasInitWorklist.back().second;
720 if (ValID >= ValueList.size()) {
721 AliasInits.push_back(AliasInitWorklist.back());
723 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
724 AliasInitWorklist.back().first->setAliasee(C);
726 return Error("Alias initializer is not a constant!");
728 AliasInitWorklist.pop_back();
734 bool BitcodeReader::ParseConstants() {
735 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
736 return Error("Malformed block record");
738 SmallVector<uint64_t, 64> Record;
740 // Read all the records for this value table.
741 const Type *CurTy = Type::Int32Ty;
742 unsigned NextCstNo = ValueList.size();
744 unsigned Code = Stream.ReadCode();
745 if (Code == bitc::END_BLOCK)
748 if (Code == bitc::ENTER_SUBBLOCK) {
749 // No known subblocks, always skip them.
750 Stream.ReadSubBlockID();
751 if (Stream.SkipBlock())
752 return Error("Malformed block record");
756 if (Code == bitc::DEFINE_ABBREV) {
757 Stream.ReadAbbrevRecord();
764 switch (Stream.ReadRecord(Code, Record)) {
765 default: // Default behavior: unknown constant
766 case bitc::CST_CODE_UNDEF: // UNDEF
767 V = UndefValue::get(CurTy);
769 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
771 return Error("Malformed CST_SETTYPE record");
772 if (Record[0] >= TypeList.size())
773 return Error("Invalid Type ID in CST_SETTYPE record");
774 CurTy = TypeList[Record[0]];
775 continue; // Skip the ValueList manipulation.
776 case bitc::CST_CODE_NULL: // NULL
777 V = Constant::getNullValue(CurTy);
779 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
780 if (!isa<IntegerType>(CurTy) || Record.empty())
781 return Error("Invalid CST_INTEGER record");
782 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
784 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
785 if (!isa<IntegerType>(CurTy) || Record.empty())
786 return Error("Invalid WIDE_INTEGER record");
788 unsigned NumWords = Record.size();
789 SmallVector<uint64_t, 8> Words;
790 Words.resize(NumWords);
791 for (unsigned i = 0; i != NumWords; ++i)
792 Words[i] = DecodeSignRotatedValue(Record[i]);
793 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
794 NumWords, &Words[0]));
797 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
799 return Error("Invalid FLOAT record");
800 if (CurTy == Type::FloatTy)
801 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
802 else if (CurTy == Type::DoubleTy)
803 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
804 else if (CurTy == Type::X86_FP80Ty) {
805 // Bits are not stored the same way as a normal i80 APInt, compensate.
806 uint64_t Rearrange[2];
807 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
808 Rearrange[1] = Record[0] >> 48;
809 V = ConstantFP::get(APFloat(APInt(80, 2, Rearrange)));
810 } else if (CurTy == Type::FP128Ty)
811 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
812 else if (CurTy == Type::PPC_FP128Ty)
813 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
815 V = UndefValue::get(CurTy);
819 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
821 return Error("Invalid CST_AGGREGATE record");
823 unsigned Size = Record.size();
824 std::vector<Constant*> Elts;
826 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
827 for (unsigned i = 0; i != Size; ++i)
828 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
829 STy->getElementType(i)));
830 V = ConstantStruct::get(STy, Elts);
831 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
832 const Type *EltTy = ATy->getElementType();
833 for (unsigned i = 0; i != Size; ++i)
834 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
835 V = ConstantArray::get(ATy, Elts);
836 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
837 const Type *EltTy = VTy->getElementType();
838 for (unsigned i = 0; i != Size; ++i)
839 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
840 V = ConstantVector::get(Elts);
842 V = UndefValue::get(CurTy);
846 case bitc::CST_CODE_STRING: { // STRING: [values]
848 return Error("Invalid CST_AGGREGATE record");
850 const ArrayType *ATy = cast<ArrayType>(CurTy);
851 const Type *EltTy = ATy->getElementType();
853 unsigned Size = Record.size();
854 std::vector<Constant*> Elts;
855 for (unsigned i = 0; i != Size; ++i)
856 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
857 V = ConstantArray::get(ATy, Elts);
860 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
862 return Error("Invalid CST_AGGREGATE record");
864 const ArrayType *ATy = cast<ArrayType>(CurTy);
865 const Type *EltTy = ATy->getElementType();
867 unsigned Size = Record.size();
868 std::vector<Constant*> Elts;
869 for (unsigned i = 0; i != Size; ++i)
870 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
871 Elts.push_back(Constant::getNullValue(EltTy));
872 V = ConstantArray::get(ATy, Elts);
875 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
876 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
877 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
879 V = UndefValue::get(CurTy); // Unknown binop.
881 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
882 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
883 V = ConstantExpr::get(Opc, LHS, RHS);
887 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
888 if (Record.size() < 3) return Error("Invalid CE_CAST record");
889 int Opc = GetDecodedCastOpcode(Record[0]);
891 V = UndefValue::get(CurTy); // Unknown cast.
893 const Type *OpTy = getTypeByID(Record[1]);
894 if (!OpTy) return Error("Invalid CE_CAST record");
895 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
896 V = ConstantExpr::getCast(Opc, Op, CurTy);
900 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
901 if (Record.size() & 1) return Error("Invalid CE_GEP record");
902 SmallVector<Constant*, 16> Elts;
903 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
904 const Type *ElTy = getTypeByID(Record[i]);
905 if (!ElTy) return Error("Invalid CE_GEP record");
906 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
908 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
911 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
912 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
913 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
915 ValueList.getConstantFwdRef(Record[1],CurTy),
916 ValueList.getConstantFwdRef(Record[2],CurTy));
918 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
919 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
920 const VectorType *OpTy =
921 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
922 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
923 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
924 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
925 V = ConstantExpr::getExtractElement(Op0, Op1);
928 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
929 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
930 if (Record.size() < 3 || OpTy == 0)
931 return Error("Invalid CE_INSERTELT record");
932 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
933 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
934 OpTy->getElementType());
935 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
936 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
939 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
940 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
941 if (Record.size() < 3 || OpTy == 0)
942 return Error("Invalid CE_SHUFFLEVEC record");
943 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
944 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
945 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
946 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
947 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
950 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
951 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
952 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
953 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
954 return Error("Invalid CE_SHUFVEC_EX record");
955 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
956 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
957 const Type *ShufTy=VectorType::get(Type::Int32Ty, RTy->getNumElements());
958 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
959 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
962 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
963 if (Record.size() < 4) return Error("Invalid CE_CMP record");
964 const Type *OpTy = getTypeByID(Record[0]);
965 if (OpTy == 0) return Error("Invalid CE_CMP record");
966 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
967 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
969 if (OpTy->isFloatingPoint())
970 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
971 else if (!isa<VectorType>(OpTy))
972 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
973 else if (OpTy->isFPOrFPVector())
974 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
976 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
979 case bitc::CST_CODE_INLINEASM: {
980 if (Record.size() < 2) return Error("Invalid INLINEASM record");
981 std::string AsmStr, ConstrStr;
982 bool HasSideEffects = Record[0];
983 unsigned AsmStrSize = Record[1];
984 if (2+AsmStrSize >= Record.size())
985 return Error("Invalid INLINEASM record");
986 unsigned ConstStrSize = Record[2+AsmStrSize];
987 if (3+AsmStrSize+ConstStrSize > Record.size())
988 return Error("Invalid INLINEASM record");
990 for (unsigned i = 0; i != AsmStrSize; ++i)
991 AsmStr += (char)Record[2+i];
992 for (unsigned i = 0; i != ConstStrSize; ++i)
993 ConstrStr += (char)Record[3+AsmStrSize+i];
994 const PointerType *PTy = cast<PointerType>(CurTy);
995 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
996 AsmStr, ConstrStr, HasSideEffects);
1001 ValueList.AssignValue(V, NextCstNo);
1005 if (NextCstNo != ValueList.size())
1006 return Error("Invalid constant reference!");
1008 if (Stream.ReadBlockEnd())
1009 return Error("Error at end of constants block");
1011 // Once all the constants have been read, go through and resolve forward
1013 ValueList.ResolveConstantForwardRefs();
1017 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1018 /// remember where it is and then skip it. This lets us lazily deserialize the
1020 bool BitcodeReader::RememberAndSkipFunctionBody() {
1021 // Get the function we are talking about.
1022 if (FunctionsWithBodies.empty())
1023 return Error("Insufficient function protos");
1025 Function *Fn = FunctionsWithBodies.back();
1026 FunctionsWithBodies.pop_back();
1028 // Save the current stream state.
1029 uint64_t CurBit = Stream.GetCurrentBitNo();
1030 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1032 // Set the functions linkage to GhostLinkage so we know it is lazily
1034 Fn->setLinkage(GlobalValue::GhostLinkage);
1036 // Skip over the function block for now.
1037 if (Stream.SkipBlock())
1038 return Error("Malformed block record");
1042 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1043 // Reject multiple MODULE_BLOCK's in a single bitstream.
1045 return Error("Multiple MODULE_BLOCKs in same stream");
1047 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1048 return Error("Malformed block record");
1050 // Otherwise, create the module.
1051 TheModule = new Module(ModuleID);
1053 SmallVector<uint64_t, 64> Record;
1054 std::vector<std::string> SectionTable;
1055 std::vector<std::string> GCTable;
1057 // Read all the records for this module.
1058 while (!Stream.AtEndOfStream()) {
1059 unsigned Code = Stream.ReadCode();
1060 if (Code == bitc::END_BLOCK) {
1061 if (Stream.ReadBlockEnd())
1062 return Error("Error at end of module block");
1064 // Patch the initializers for globals and aliases up.
1065 ResolveGlobalAndAliasInits();
1066 if (!GlobalInits.empty() || !AliasInits.empty())
1067 return Error("Malformed global initializer set");
1068 if (!FunctionsWithBodies.empty())
1069 return Error("Too few function bodies found");
1071 // Look for intrinsic functions which need to be upgraded at some point
1072 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1075 if (UpgradeIntrinsicFunction(FI, NewFn))
1076 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1079 // Force deallocation of memory for these vectors to favor the client that
1080 // want lazy deserialization.
1081 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1082 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1083 std::vector<Function*>().swap(FunctionsWithBodies);
1087 if (Code == bitc::ENTER_SUBBLOCK) {
1088 switch (Stream.ReadSubBlockID()) {
1089 default: // Skip unknown content.
1090 if (Stream.SkipBlock())
1091 return Error("Malformed block record");
1093 case bitc::BLOCKINFO_BLOCK_ID:
1094 if (Stream.ReadBlockInfoBlock())
1095 return Error("Malformed BlockInfoBlock");
1097 case bitc::PARAMATTR_BLOCK_ID:
1098 if (ParseAttributeBlock())
1101 case bitc::TYPE_BLOCK_ID:
1102 if (ParseTypeTable())
1105 case bitc::TYPE_SYMTAB_BLOCK_ID:
1106 if (ParseTypeSymbolTable())
1109 case bitc::VALUE_SYMTAB_BLOCK_ID:
1110 if (ParseValueSymbolTable())
1113 case bitc::CONSTANTS_BLOCK_ID:
1114 if (ParseConstants() || ResolveGlobalAndAliasInits())
1117 case bitc::FUNCTION_BLOCK_ID:
1118 // If this is the first function body we've seen, reverse the
1119 // FunctionsWithBodies list.
1120 if (!HasReversedFunctionsWithBodies) {
1121 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1122 HasReversedFunctionsWithBodies = true;
1125 if (RememberAndSkipFunctionBody())
1132 if (Code == bitc::DEFINE_ABBREV) {
1133 Stream.ReadAbbrevRecord();
1138 switch (Stream.ReadRecord(Code, Record)) {
1139 default: break; // Default behavior, ignore unknown content.
1140 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1141 if (Record.size() < 1)
1142 return Error("Malformed MODULE_CODE_VERSION");
1143 // Only version #0 is supported so far.
1145 return Error("Unknown bitstream version!");
1147 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1149 if (ConvertToString(Record, 0, S))
1150 return Error("Invalid MODULE_CODE_TRIPLE record");
1151 TheModule->setTargetTriple(S);
1154 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1156 if (ConvertToString(Record, 0, S))
1157 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1158 TheModule->setDataLayout(S);
1161 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1163 if (ConvertToString(Record, 0, S))
1164 return Error("Invalid MODULE_CODE_ASM record");
1165 TheModule->setModuleInlineAsm(S);
1168 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1170 if (ConvertToString(Record, 0, S))
1171 return Error("Invalid MODULE_CODE_DEPLIB record");
1172 TheModule->addLibrary(S);
1175 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1177 if (ConvertToString(Record, 0, S))
1178 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1179 SectionTable.push_back(S);
1182 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1184 if (ConvertToString(Record, 0, S))
1185 return Error("Invalid MODULE_CODE_GCNAME record");
1186 GCTable.push_back(S);
1189 // GLOBALVAR: [pointer type, isconst, initid,
1190 // linkage, alignment, section, visibility, threadlocal]
1191 case bitc::MODULE_CODE_GLOBALVAR: {
1192 if (Record.size() < 6)
1193 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1194 const Type *Ty = getTypeByID(Record[0]);
1195 if (!isa<PointerType>(Ty))
1196 return Error("Global not a pointer type!");
1197 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1198 Ty = cast<PointerType>(Ty)->getElementType();
1200 bool isConstant = Record[1];
1201 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1202 unsigned Alignment = (1 << Record[4]) >> 1;
1203 std::string Section;
1205 if (Record[5]-1 >= SectionTable.size())
1206 return Error("Invalid section ID");
1207 Section = SectionTable[Record[5]-1];
1209 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1210 if (Record.size() > 6)
1211 Visibility = GetDecodedVisibility(Record[6]);
1212 bool isThreadLocal = false;
1213 if (Record.size() > 7)
1214 isThreadLocal = Record[7];
1216 GlobalVariable *NewGV =
1217 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1218 isThreadLocal, AddressSpace);
1219 NewGV->setAlignment(Alignment);
1220 if (!Section.empty())
1221 NewGV->setSection(Section);
1222 NewGV->setVisibility(Visibility);
1223 NewGV->setThreadLocal(isThreadLocal);
1225 ValueList.push_back(NewGV);
1227 // Remember which value to use for the global initializer.
1228 if (unsigned InitID = Record[2])
1229 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1232 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1233 // alignment, section, visibility, gc]
1234 case bitc::MODULE_CODE_FUNCTION: {
1235 if (Record.size() < 8)
1236 return Error("Invalid MODULE_CODE_FUNCTION record");
1237 const Type *Ty = getTypeByID(Record[0]);
1238 if (!isa<PointerType>(Ty))
1239 return Error("Function not a pointer type!");
1240 const FunctionType *FTy =
1241 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1243 return Error("Function not a pointer to function type!");
1245 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1248 Func->setCallingConv(Record[1]);
1249 bool isProto = Record[2];
1250 Func->setLinkage(GetDecodedLinkage(Record[3]));
1251 Func->setAttributes(getAttributes(Record[4]));
1253 Func->setAlignment((1 << Record[5]) >> 1);
1255 if (Record[6]-1 >= SectionTable.size())
1256 return Error("Invalid section ID");
1257 Func->setSection(SectionTable[Record[6]-1]);
1259 Func->setVisibility(GetDecodedVisibility(Record[7]));
1260 if (Record.size() > 8 && Record[8]) {
1261 if (Record[8]-1 > GCTable.size())
1262 return Error("Invalid GC ID");
1263 Func->setGC(GCTable[Record[8]-1].c_str());
1265 ValueList.push_back(Func);
1267 // If this is a function with a body, remember the prototype we are
1268 // creating now, so that we can match up the body with them later.
1270 FunctionsWithBodies.push_back(Func);
1273 // ALIAS: [alias type, aliasee val#, linkage]
1274 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1275 case bitc::MODULE_CODE_ALIAS: {
1276 if (Record.size() < 3)
1277 return Error("Invalid MODULE_ALIAS record");
1278 const Type *Ty = getTypeByID(Record[0]);
1279 if (!isa<PointerType>(Ty))
1280 return Error("Function not a pointer type!");
1282 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1284 // Old bitcode files didn't have visibility field.
1285 if (Record.size() > 3)
1286 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1287 ValueList.push_back(NewGA);
1288 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1291 /// MODULE_CODE_PURGEVALS: [numvals]
1292 case bitc::MODULE_CODE_PURGEVALS:
1293 // Trim down the value list to the specified size.
1294 if (Record.size() < 1 || Record[0] > ValueList.size())
1295 return Error("Invalid MODULE_PURGEVALS record");
1296 ValueList.shrinkTo(Record[0]);
1302 return Error("Premature end of bitstream");
1305 /// SkipWrapperHeader - Some systems wrap bc files with a special header for
1306 /// padding or other reasons. The format of this header is:
1308 /// struct bc_header {
1309 /// uint32_t Magic; // 0x0B17C0DE
1310 /// uint32_t Version; // Version, currently always 0.
1311 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1312 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1313 /// ... potentially other gunk ...
1316 /// This function is called when we find a file with a matching magic number.
1317 /// In this case, skip down to the subsection of the file that is actually a BC
1319 static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1321 KnownHeaderSize = 4*4, // Size of header we read.
1322 OffsetField = 2*4, // Offset in bytes to Offset field.
1323 SizeField = 3*4 // Offset in bytes to Size field.
1327 // Must contain the header!
1328 if (BufEnd-BufPtr < KnownHeaderSize) return true;
1330 unsigned Offset = ( BufPtr[OffsetField ] |
1331 (BufPtr[OffsetField+1] << 8) |
1332 (BufPtr[OffsetField+2] << 16) |
1333 (BufPtr[OffsetField+3] << 24));
1334 unsigned Size = ( BufPtr[SizeField ] |
1335 (BufPtr[SizeField +1] << 8) |
1336 (BufPtr[SizeField +2] << 16) |
1337 (BufPtr[SizeField +3] << 24));
1339 // Verify that Offset+Size fits in the file.
1340 if (Offset+Size > unsigned(BufEnd-BufPtr))
1343 BufEnd = BufPtr+Size;
1347 bool BitcodeReader::ParseBitcode() {
1350 if (Buffer->getBufferSize() & 3)
1351 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1353 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1354 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1356 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1357 // The magic number is 0x0B17C0DE stored in little endian.
1358 if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1359 BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1360 if (SkipWrapperHeader(BufPtr, BufEnd))
1361 return Error("Invalid bitcode wrapper header");
1363 Stream.init(BufPtr, BufEnd);
1365 // Sniff for the signature.
1366 if (Stream.Read(8) != 'B' ||
1367 Stream.Read(8) != 'C' ||
1368 Stream.Read(4) != 0x0 ||
1369 Stream.Read(4) != 0xC ||
1370 Stream.Read(4) != 0xE ||
1371 Stream.Read(4) != 0xD)
1372 return Error("Invalid bitcode signature");
1374 // We expect a number of well-defined blocks, though we don't necessarily
1375 // need to understand them all.
1376 while (!Stream.AtEndOfStream()) {
1377 unsigned Code = Stream.ReadCode();
1379 if (Code != bitc::ENTER_SUBBLOCK)
1380 return Error("Invalid record at top-level");
1382 unsigned BlockID = Stream.ReadSubBlockID();
1384 // We only know the MODULE subblock ID.
1386 case bitc::BLOCKINFO_BLOCK_ID:
1387 if (Stream.ReadBlockInfoBlock())
1388 return Error("Malformed BlockInfoBlock");
1390 case bitc::MODULE_BLOCK_ID:
1391 if (ParseModule(Buffer->getBufferIdentifier()))
1395 if (Stream.SkipBlock())
1396 return Error("Malformed block record");
1405 /// ParseFunctionBody - Lazily parse the specified function body block.
1406 bool BitcodeReader::ParseFunctionBody(Function *F) {
1407 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1408 return Error("Malformed block record");
1410 unsigned ModuleValueListSize = ValueList.size();
1412 // Add all the function arguments to the value table.
1413 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1414 ValueList.push_back(I);
1416 unsigned NextValueNo = ValueList.size();
1417 BasicBlock *CurBB = 0;
1418 unsigned CurBBNo = 0;
1420 // Read all the records.
1421 SmallVector<uint64_t, 64> Record;
1423 unsigned Code = Stream.ReadCode();
1424 if (Code == bitc::END_BLOCK) {
1425 if (Stream.ReadBlockEnd())
1426 return Error("Error at end of function block");
1430 if (Code == bitc::ENTER_SUBBLOCK) {
1431 switch (Stream.ReadSubBlockID()) {
1432 default: // Skip unknown content.
1433 if (Stream.SkipBlock())
1434 return Error("Malformed block record");
1436 case bitc::CONSTANTS_BLOCK_ID:
1437 if (ParseConstants()) return true;
1438 NextValueNo = ValueList.size();
1440 case bitc::VALUE_SYMTAB_BLOCK_ID:
1441 if (ParseValueSymbolTable()) return true;
1447 if (Code == bitc::DEFINE_ABBREV) {
1448 Stream.ReadAbbrevRecord();
1455 switch (Stream.ReadRecord(Code, Record)) {
1456 default: // Default behavior: reject
1457 return Error("Unknown instruction");
1458 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1459 if (Record.size() < 1 || Record[0] == 0)
1460 return Error("Invalid DECLAREBLOCKS record");
1461 // Create all the basic blocks for the function.
1462 FunctionBBs.resize(Record[0]);
1463 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1464 FunctionBBs[i] = BasicBlock::Create("", F);
1465 CurBB = FunctionBBs[0];
1468 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1471 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1472 getValue(Record, OpNum, LHS->getType(), RHS) ||
1473 OpNum+1 != Record.size())
1474 return Error("Invalid BINOP record");
1476 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1477 if (Opc == -1) return Error("Invalid BINOP record");
1478 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1481 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1484 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1485 OpNum+2 != Record.size())
1486 return Error("Invalid CAST record");
1488 const Type *ResTy = getTypeByID(Record[OpNum]);
1489 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1490 if (Opc == -1 || ResTy == 0)
1491 return Error("Invalid CAST record");
1492 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1495 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1498 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1499 return Error("Invalid GEP record");
1501 SmallVector<Value*, 16> GEPIdx;
1502 while (OpNum != Record.size()) {
1504 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1505 return Error("Invalid GEP record");
1506 GEPIdx.push_back(Op);
1509 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1513 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1514 // EXTRACTVAL: [opty, opval, n x indices]
1517 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1518 return Error("Invalid EXTRACTVAL record");
1520 SmallVector<unsigned, 4> EXTRACTVALIdx;
1521 for (unsigned RecSize = Record.size();
1522 OpNum != RecSize; ++OpNum) {
1523 uint64_t Index = Record[OpNum];
1524 if ((unsigned)Index != Index)
1525 return Error("Invalid EXTRACTVAL index");
1526 EXTRACTVALIdx.push_back((unsigned)Index);
1529 I = ExtractValueInst::Create(Agg,
1530 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1534 case bitc::FUNC_CODE_INST_INSERTVAL: {
1535 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1538 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1539 return Error("Invalid INSERTVAL record");
1541 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1542 return Error("Invalid INSERTVAL record");
1544 SmallVector<unsigned, 4> INSERTVALIdx;
1545 for (unsigned RecSize = Record.size();
1546 OpNum != RecSize; ++OpNum) {
1547 uint64_t Index = Record[OpNum];
1548 if ((unsigned)Index != Index)
1549 return Error("Invalid INSERTVAL index");
1550 INSERTVALIdx.push_back((unsigned)Index);
1553 I = InsertValueInst::Create(Agg, Val,
1554 INSERTVALIdx.begin(), INSERTVALIdx.end());
1558 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1559 // obsolete form of select
1560 // handles select i1 ... in old bitcode
1562 Value *TrueVal, *FalseVal, *Cond;
1563 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1564 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1565 getValue(Record, OpNum, Type::Int1Ty, Cond))
1566 return Error("Invalid SELECT record");
1568 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1572 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1573 // new form of select
1574 // handles select i1 or select [N x i1]
1576 Value *TrueVal, *FalseVal, *Cond;
1577 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1578 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1579 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1580 return Error("Invalid SELECT record");
1582 // select condition can be either i1 or [N x i1]
1583 if (const VectorType* vector_type =
1584 dyn_cast<const VectorType>(Cond->getType())) {
1586 if (vector_type->getElementType() != Type::Int1Ty)
1587 return Error("Invalid SELECT condition type");
1590 if (Cond->getType() != Type::Int1Ty)
1591 return Error("Invalid SELECT condition type");
1594 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1598 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1601 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1602 getValue(Record, OpNum, Type::Int32Ty, Idx))
1603 return Error("Invalid EXTRACTELT record");
1604 I = new ExtractElementInst(Vec, Idx);
1608 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1610 Value *Vec, *Elt, *Idx;
1611 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1612 getValue(Record, OpNum,
1613 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1614 getValue(Record, OpNum, Type::Int32Ty, Idx))
1615 return Error("Invalid INSERTELT record");
1616 I = InsertElementInst::Create(Vec, Elt, Idx);
1620 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1622 Value *Vec1, *Vec2, *Mask;
1623 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1624 getValue(Record, OpNum, Vec1->getType(), Vec2))
1625 return Error("Invalid SHUFFLEVEC record");
1627 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1628 return Error("Invalid SHUFFLEVEC record");
1629 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1633 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1635 // or old form of ICmp/FCmp returning bool
1638 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1639 getValue(Record, OpNum, LHS->getType(), RHS) ||
1640 OpNum+1 != Record.size())
1641 return Error("Invalid CMP record");
1643 if (LHS->getType()->isFloatingPoint())
1644 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1645 else if (!isa<VectorType>(LHS->getType()))
1646 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1647 else if (LHS->getType()->isFPOrFPVector())
1648 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1650 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1653 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1654 // Fcmp/ICmp returning bool or vector of bool
1657 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1658 getValue(Record, OpNum, LHS->getType(), RHS) ||
1659 OpNum+1 != Record.size())
1660 return Error("Invalid CMP2 record");
1662 if (LHS->getType()->isFPOrFPVector())
1663 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1665 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1668 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1669 if (Record.size() != 2)
1670 return Error("Invalid GETRESULT record");
1673 getValueTypePair(Record, OpNum, NextValueNo, Op);
1674 unsigned Index = Record[1];
1675 I = ExtractValueInst::Create(Op, Index);
1679 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1681 unsigned Size = Record.size();
1683 I = ReturnInst::Create();
1688 SmallVector<Value *,4> Vs;
1691 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1692 return Error("Invalid RET record");
1694 } while(OpNum != Record.size());
1696 const Type *ReturnType = F->getReturnType();
1697 if (Vs.size() > 1 ||
1698 (isa<StructType>(ReturnType) &&
1699 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1700 Value *RV = UndefValue::get(ReturnType);
1701 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1702 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1703 CurBB->getInstList().push_back(I);
1704 ValueList.AssignValue(I, NextValueNo++);
1707 I = ReturnInst::Create(RV);
1711 I = ReturnInst::Create(Vs[0]);
1714 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1715 if (Record.size() != 1 && Record.size() != 3)
1716 return Error("Invalid BR record");
1717 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1719 return Error("Invalid BR record");
1721 if (Record.size() == 1)
1722 I = BranchInst::Create(TrueDest);
1724 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1725 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1726 if (FalseDest == 0 || Cond == 0)
1727 return Error("Invalid BR record");
1728 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1732 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1733 if (Record.size() < 3 || (Record.size() & 1) == 0)
1734 return Error("Invalid SWITCH record");
1735 const Type *OpTy = getTypeByID(Record[0]);
1736 Value *Cond = getFnValueByID(Record[1], OpTy);
1737 BasicBlock *Default = getBasicBlock(Record[2]);
1738 if (OpTy == 0 || Cond == 0 || Default == 0)
1739 return Error("Invalid SWITCH record");
1740 unsigned NumCases = (Record.size()-3)/2;
1741 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1742 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1743 ConstantInt *CaseVal =
1744 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1745 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1746 if (CaseVal == 0 || DestBB == 0) {
1748 return Error("Invalid SWITCH record!");
1750 SI->addCase(CaseVal, DestBB);
1756 case bitc::FUNC_CODE_INST_INVOKE: {
1757 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1758 if (Record.size() < 4) return Error("Invalid INVOKE record");
1759 AttrListPtr PAL = getAttributes(Record[0]);
1760 unsigned CCInfo = Record[1];
1761 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1762 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1766 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1767 return Error("Invalid INVOKE record");
1769 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1770 const FunctionType *FTy = !CalleeTy ? 0 :
1771 dyn_cast<FunctionType>(CalleeTy->getElementType());
1773 // Check that the right number of fixed parameters are here.
1774 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1775 Record.size() < OpNum+FTy->getNumParams())
1776 return Error("Invalid INVOKE record");
1778 SmallVector<Value*, 16> Ops;
1779 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1780 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1781 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1784 if (!FTy->isVarArg()) {
1785 if (Record.size() != OpNum)
1786 return Error("Invalid INVOKE record");
1788 // Read type/value pairs for varargs params.
1789 while (OpNum != Record.size()) {
1791 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1792 return Error("Invalid INVOKE record");
1797 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1798 Ops.begin(), Ops.end());
1799 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1800 cast<InvokeInst>(I)->setAttributes(PAL);
1803 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1804 I = new UnwindInst();
1806 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1807 I = new UnreachableInst();
1809 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1810 if (Record.size() < 1 || ((Record.size()-1)&1))
1811 return Error("Invalid PHI record");
1812 const Type *Ty = getTypeByID(Record[0]);
1813 if (!Ty) return Error("Invalid PHI record");
1815 PHINode *PN = PHINode::Create(Ty);
1816 PN->reserveOperandSpace((Record.size()-1)/2);
1818 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1819 Value *V = getFnValueByID(Record[1+i], Ty);
1820 BasicBlock *BB = getBasicBlock(Record[2+i]);
1821 if (!V || !BB) return Error("Invalid PHI record");
1822 PN->addIncoming(V, BB);
1828 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1829 if (Record.size() < 3)
1830 return Error("Invalid MALLOC record");
1831 const PointerType *Ty =
1832 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1833 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1834 unsigned Align = Record[2];
1835 if (!Ty || !Size) return Error("Invalid MALLOC record");
1836 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1839 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1842 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1843 OpNum != Record.size())
1844 return Error("Invalid FREE record");
1845 I = new FreeInst(Op);
1848 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1849 if (Record.size() < 3)
1850 return Error("Invalid ALLOCA record");
1851 const PointerType *Ty =
1852 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1853 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1854 unsigned Align = Record[2];
1855 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1856 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1859 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1862 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1863 OpNum+2 != Record.size())
1864 return Error("Invalid LOAD record");
1866 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1869 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1872 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1873 getValue(Record, OpNum,
1874 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1875 OpNum+2 != Record.size())
1876 return Error("Invalid STORE record");
1878 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1881 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1882 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1885 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1886 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1887 OpNum+2 != Record.size())
1888 return Error("Invalid STORE record");
1890 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1893 case bitc::FUNC_CODE_INST_CALL: {
1894 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1895 if (Record.size() < 3)
1896 return Error("Invalid CALL record");
1898 AttrListPtr PAL = getAttributes(Record[0]);
1899 unsigned CCInfo = Record[1];
1903 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1904 return Error("Invalid CALL record");
1906 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1907 const FunctionType *FTy = 0;
1908 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1909 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1910 return Error("Invalid CALL record");
1912 SmallVector<Value*, 16> Args;
1913 // Read the fixed params.
1914 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1915 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1916 Args.push_back(getBasicBlock(Record[OpNum]));
1918 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1919 if (Args.back() == 0) return Error("Invalid CALL record");
1922 // Read type/value pairs for varargs params.
1923 if (!FTy->isVarArg()) {
1924 if (OpNum != Record.size())
1925 return Error("Invalid CALL record");
1927 while (OpNum != Record.size()) {
1929 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1930 return Error("Invalid CALL record");
1935 I = CallInst::Create(Callee, Args.begin(), Args.end());
1936 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1937 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1938 cast<CallInst>(I)->setAttributes(PAL);
1941 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1942 if (Record.size() < 3)
1943 return Error("Invalid VAARG record");
1944 const Type *OpTy = getTypeByID(Record[0]);
1945 Value *Op = getFnValueByID(Record[1], OpTy);
1946 const Type *ResTy = getTypeByID(Record[2]);
1947 if (!OpTy || !Op || !ResTy)
1948 return Error("Invalid VAARG record");
1949 I = new VAArgInst(Op, ResTy);
1954 // Add instruction to end of current BB. If there is no current BB, reject
1958 return Error("Invalid instruction with no BB");
1960 CurBB->getInstList().push_back(I);
1962 // If this was a terminator instruction, move to the next block.
1963 if (isa<TerminatorInst>(I)) {
1965 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1968 // Non-void values get registered in the value table for future use.
1969 if (I && I->getType() != Type::VoidTy)
1970 ValueList.AssignValue(I, NextValueNo++);
1973 // Check the function list for unresolved values.
1974 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1975 if (A->getParent() == 0) {
1976 // We found at least one unresolved value. Nuke them all to avoid leaks.
1977 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1978 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1979 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1983 return Error("Never resolved value found in function!");
1987 // Trim the value list down to the size it was before we parsed this function.
1988 ValueList.shrinkTo(ModuleValueListSize);
1989 std::vector<BasicBlock*>().swap(FunctionBBs);
1994 //===----------------------------------------------------------------------===//
1995 // ModuleProvider implementation
1996 //===----------------------------------------------------------------------===//
1999 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2000 // If it already is material, ignore the request.
2001 if (!F->hasNotBeenReadFromBitcode()) return false;
2003 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2004 DeferredFunctionInfo.find(F);
2005 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2007 // Move the bit stream to the saved position of the deferred function body and
2008 // restore the real linkage type for the function.
2009 Stream.JumpToBit(DFII->second.first);
2010 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2012 if (ParseFunctionBody(F)) {
2013 if (ErrInfo) *ErrInfo = ErrorString;
2017 // Upgrade any old intrinsic calls in the function.
2018 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2019 E = UpgradedIntrinsics.end(); I != E; ++I) {
2020 if (I->first != I->second) {
2021 for (Value::use_iterator UI = I->first->use_begin(),
2022 UE = I->first->use_end(); UI != UE; ) {
2023 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2024 UpgradeIntrinsicCall(CI, I->second);
2032 void BitcodeReader::dematerializeFunction(Function *F) {
2033 // If this function isn't materialized, or if it is a proto, this is a noop.
2034 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2037 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2039 // Just forget the function body, we can remat it later.
2041 F->setLinkage(GlobalValue::GhostLinkage);
2045 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2046 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
2047 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
2049 Function *F = I->first;
2050 if (F->hasNotBeenReadFromBitcode() &&
2051 materializeFunction(F, ErrInfo))
2055 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2056 // delete the old functions to clean up. We can't do this unless the entire
2057 // module is materialized because there could always be another function body
2058 // with calls to the old function.
2059 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2060 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2061 if (I->first != I->second) {
2062 for (Value::use_iterator UI = I->first->use_begin(),
2063 UE = I->first->use_end(); UI != UE; ) {
2064 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2065 UpgradeIntrinsicCall(CI, I->second);
2067 ValueList.replaceUsesOfWith(I->first, I->second);
2068 I->first->eraseFromParent();
2071 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2077 /// This method is provided by the parent ModuleProvde class and overriden
2078 /// here. It simply releases the module from its provided and frees up our
2080 /// @brief Release our hold on the generated module
2081 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2082 // Since we're losing control of this Module, we must hand it back complete
2083 Module *M = ModuleProvider::releaseModule(ErrInfo);
2089 //===----------------------------------------------------------------------===//
2090 // External interface
2091 //===----------------------------------------------------------------------===//
2093 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2095 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2096 std::string *ErrMsg) {
2097 BitcodeReader *R = new BitcodeReader(Buffer);
2098 if (R->ParseBitcode()) {
2100 *ErrMsg = R->getErrorString();
2102 // Don't let the BitcodeReader dtor delete 'Buffer'.
2103 R->releaseMemoryBuffer();
2110 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2111 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2112 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2114 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2117 // Read in the entire module.
2118 Module *M = R->materializeModule(ErrMsg);
2120 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2121 // there was an error.
2122 R->releaseMemoryBuffer();
2124 // If there was no error, tell ModuleProvider not to delete it when its dtor
2127 M = R->releaseModule(ErrMsg);