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 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/InlineAsm.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/OperandTraits.h"
21 #include "llvm/IR/Operator.h"
22 #include "llvm/Support/DataStream.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/MemoryBuffer.h"
28 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
31 void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
38 void BitcodeReader::FreeState() {
42 std::vector<Type*>().swap(TypeList);
46 std::vector<AttributeSet>().swap(MAttributes);
47 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
52 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
55 //===----------------------------------------------------------------------===//
56 // Helper functions to implement forward reference resolution, etc.
57 //===----------------------------------------------------------------------===//
59 /// ConvertToString - Convert a string from a record into an std::string, return
61 template<typename StrTy>
62 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
64 if (Idx > Record.size())
67 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
68 Result += (char)Record[i];
72 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
74 default: // Map unknown/new linkages to external
75 case 0: return GlobalValue::ExternalLinkage;
76 case 1: return GlobalValue::WeakAnyLinkage;
77 case 2: return GlobalValue::AppendingLinkage;
78 case 3: return GlobalValue::InternalLinkage;
79 case 4: return GlobalValue::LinkOnceAnyLinkage;
80 case 5: return GlobalValue::DLLImportLinkage;
81 case 6: return GlobalValue::DLLExportLinkage;
82 case 7: return GlobalValue::ExternalWeakLinkage;
83 case 8: return GlobalValue::CommonLinkage;
84 case 9: return GlobalValue::PrivateLinkage;
85 case 10: return GlobalValue::WeakODRLinkage;
86 case 11: return GlobalValue::LinkOnceODRLinkage;
87 case 12: return GlobalValue::AvailableExternallyLinkage;
88 case 13: return GlobalValue::LinkerPrivateLinkage;
89 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
90 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
94 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
96 default: // Map unknown visibilities to default.
97 case 0: return GlobalValue::DefaultVisibility;
98 case 1: return GlobalValue::HiddenVisibility;
99 case 2: return GlobalValue::ProtectedVisibility;
103 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
105 case 0: return GlobalVariable::NotThreadLocal;
106 default: // Map unknown non-zero value to general dynamic.
107 case 1: return GlobalVariable::GeneralDynamicTLSModel;
108 case 2: return GlobalVariable::LocalDynamicTLSModel;
109 case 3: return GlobalVariable::InitialExecTLSModel;
110 case 4: return GlobalVariable::LocalExecTLSModel;
114 static int GetDecodedCastOpcode(unsigned Val) {
117 case bitc::CAST_TRUNC : return Instruction::Trunc;
118 case bitc::CAST_ZEXT : return Instruction::ZExt;
119 case bitc::CAST_SEXT : return Instruction::SExt;
120 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
121 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
122 case bitc::CAST_UITOFP : return Instruction::UIToFP;
123 case bitc::CAST_SITOFP : return Instruction::SIToFP;
124 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
125 case bitc::CAST_FPEXT : return Instruction::FPExt;
126 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
127 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
128 case bitc::CAST_BITCAST : return Instruction::BitCast;
131 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
134 case bitc::BINOP_ADD:
135 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
136 case bitc::BINOP_SUB:
137 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
138 case bitc::BINOP_MUL:
139 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
140 case bitc::BINOP_UDIV: return Instruction::UDiv;
141 case bitc::BINOP_SDIV:
142 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
143 case bitc::BINOP_UREM: return Instruction::URem;
144 case bitc::BINOP_SREM:
145 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
146 case bitc::BINOP_SHL: return Instruction::Shl;
147 case bitc::BINOP_LSHR: return Instruction::LShr;
148 case bitc::BINOP_ASHR: return Instruction::AShr;
149 case bitc::BINOP_AND: return Instruction::And;
150 case bitc::BINOP_OR: return Instruction::Or;
151 case bitc::BINOP_XOR: return Instruction::Xor;
155 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
157 default: return AtomicRMWInst::BAD_BINOP;
158 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
159 case bitc::RMW_ADD: return AtomicRMWInst::Add;
160 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
161 case bitc::RMW_AND: return AtomicRMWInst::And;
162 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
163 case bitc::RMW_OR: return AtomicRMWInst::Or;
164 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
165 case bitc::RMW_MAX: return AtomicRMWInst::Max;
166 case bitc::RMW_MIN: return AtomicRMWInst::Min;
167 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
168 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
172 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
174 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
175 case bitc::ORDERING_UNORDERED: return Unordered;
176 case bitc::ORDERING_MONOTONIC: return Monotonic;
177 case bitc::ORDERING_ACQUIRE: return Acquire;
178 case bitc::ORDERING_RELEASE: return Release;
179 case bitc::ORDERING_ACQREL: return AcquireRelease;
180 default: // Map unknown orderings to sequentially-consistent.
181 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
185 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
187 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
188 default: // Map unknown scopes to cross-thread.
189 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
195 /// @brief A class for maintaining the slot number definition
196 /// as a placeholder for the actual definition for forward constants defs.
197 class ConstantPlaceHolder : public ConstantExpr {
198 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
200 // allocate space for exactly one operand
201 void *operator new(size_t s) {
202 return User::operator new(s, 1);
204 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
205 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
206 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
209 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
210 static bool classof(const Value *V) {
211 return isa<ConstantExpr>(V) &&
212 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
216 /// Provide fast operand accessors
217 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
221 // FIXME: can we inherit this from ConstantExpr?
223 struct OperandTraits<ConstantPlaceHolder> :
224 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
229 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
238 WeakVH &OldV = ValuePtrs[Idx];
244 // Handle constants and non-constants (e.g. instrs) differently for
246 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
247 ResolveConstants.push_back(std::make_pair(PHC, Idx));
250 // If there was a forward reference to this value, replace it.
251 Value *PrevVal = OldV;
252 OldV->replaceAllUsesWith(V);
258 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
263 if (Value *V = ValuePtrs[Idx]) {
264 assert(Ty == V->getType() && "Type mismatch in constant table!");
265 return cast<Constant>(V);
268 // Create and return a placeholder, which will later be RAUW'd.
269 Constant *C = new ConstantPlaceHolder(Ty, Context);
274 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
278 if (Value *V = ValuePtrs[Idx]) {
279 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
283 // No type specified, must be invalid reference.
284 if (Ty == 0) return 0;
286 // Create and return a placeholder, which will later be RAUW'd.
287 Value *V = new Argument(Ty);
292 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
293 /// resolves any forward references. The idea behind this is that we sometimes
294 /// get constants (such as large arrays) which reference *many* forward ref
295 /// constants. Replacing each of these causes a lot of thrashing when
296 /// building/reuniquing the constant. Instead of doing this, we look at all the
297 /// uses and rewrite all the place holders at once for any constant that uses
299 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
300 // Sort the values by-pointer so that they are efficient to look up with a
302 std::sort(ResolveConstants.begin(), ResolveConstants.end());
304 SmallVector<Constant*, 64> NewOps;
306 while (!ResolveConstants.empty()) {
307 Value *RealVal = operator[](ResolveConstants.back().second);
308 Constant *Placeholder = ResolveConstants.back().first;
309 ResolveConstants.pop_back();
311 // Loop over all users of the placeholder, updating them to reference the
312 // new value. If they reference more than one placeholder, update them all
314 while (!Placeholder->use_empty()) {
315 Value::use_iterator UI = Placeholder->use_begin();
318 // If the using object isn't uniqued, just update the operands. This
319 // handles instructions and initializers for global variables.
320 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
321 UI.getUse().set(RealVal);
325 // Otherwise, we have a constant that uses the placeholder. Replace that
326 // constant with a new constant that has *all* placeholder uses updated.
327 Constant *UserC = cast<Constant>(U);
328 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
331 if (!isa<ConstantPlaceHolder>(*I)) {
332 // Not a placeholder reference.
334 } else if (*I == Placeholder) {
335 // Common case is that it just references this one placeholder.
338 // Otherwise, look up the placeholder in ResolveConstants.
339 ResolveConstantsTy::iterator It =
340 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
341 std::pair<Constant*, unsigned>(cast<Constant>(*I),
343 assert(It != ResolveConstants.end() && It->first == *I);
344 NewOp = operator[](It->second);
347 NewOps.push_back(cast<Constant>(NewOp));
350 // Make the new constant.
352 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
353 NewC = ConstantArray::get(UserCA->getType(), NewOps);
354 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
355 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
356 } else if (isa<ConstantVector>(UserC)) {
357 NewC = ConstantVector::get(NewOps);
359 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
360 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
363 UserC->replaceAllUsesWith(NewC);
364 UserC->destroyConstant();
368 // Update all ValueHandles, they should be the only users at this point.
369 Placeholder->replaceAllUsesWith(RealVal);
374 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
383 WeakVH &OldV = MDValuePtrs[Idx];
389 // If there was a forward reference to this value, replace it.
390 MDNode *PrevVal = cast<MDNode>(OldV);
391 OldV->replaceAllUsesWith(V);
392 MDNode::deleteTemporary(PrevVal);
393 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
395 MDValuePtrs[Idx] = V;
398 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
402 if (Value *V = MDValuePtrs[Idx]) {
403 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
407 // Create and return a placeholder, which will later be RAUW'd.
408 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
409 MDValuePtrs[Idx] = V;
413 Type *BitcodeReader::getTypeByID(unsigned ID) {
414 // The type table size is always specified correctly.
415 if (ID >= TypeList.size())
418 if (Type *Ty = TypeList[ID])
421 // If we have a forward reference, the only possible case is when it is to a
422 // named struct. Just create a placeholder for now.
423 return TypeList[ID] = StructType::create(Context);
427 //===----------------------------------------------------------------------===//
428 // Functions for parsing blocks from the bitcode file
429 //===----------------------------------------------------------------------===//
431 bool BitcodeReader::ParseAttributeBlock() {
432 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
433 return Error("Malformed block record");
435 if (!MAttributes.empty())
436 return Error("Multiple PARAMATTR blocks found!");
438 SmallVector<uint64_t, 64> Record;
440 SmallVector<AttributeWithIndex, 8> Attrs;
442 // Read all the records.
444 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
446 switch (Entry.Kind) {
447 case BitstreamEntry::SubBlock: // Handled for us already.
448 case BitstreamEntry::Error:
449 return Error("Error at end of PARAMATTR block");
450 case BitstreamEntry::EndBlock:
452 case BitstreamEntry::Record:
453 // The interesting case.
459 switch (Stream.readRecord(Entry.ID, Record)) {
460 default: // Default behavior: ignore.
462 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
463 if (Record.size() & 1)
464 return Error("Invalid ENTRY record");
466 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
467 Attribute ReconstitutedAttr =
468 Attribute::decodeLLVMAttributesForBitcode(Context, Record[i+1]);
469 Record[i+1] = ReconstitutedAttr.Raw();
472 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
473 AttrBuilder B(Record[i+1]);
474 if (B.hasAttributes())
475 Attrs.push_back(AttributeWithIndex::get(Record[i],
476 Attribute::get(Context, B)));
479 MAttributes.push_back(AttributeSet::get(Context, Attrs));
487 bool BitcodeReader::ParseTypeTable() {
488 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
489 return Error("Malformed block record");
491 return ParseTypeTableBody();
494 bool BitcodeReader::ParseTypeTableBody() {
495 if (!TypeList.empty())
496 return Error("Multiple TYPE_BLOCKs found!");
498 SmallVector<uint64_t, 64> Record;
499 unsigned NumRecords = 0;
501 SmallString<64> TypeName;
503 // Read all the records for this type table.
505 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
507 switch (Entry.Kind) {
508 case BitstreamEntry::SubBlock: // Handled for us already.
509 case BitstreamEntry::Error:
510 Error("Error in the type table block");
512 case BitstreamEntry::EndBlock:
513 if (NumRecords != TypeList.size())
514 return Error("Invalid type forward reference in TYPE_BLOCK");
516 case BitstreamEntry::Record:
517 // The interesting case.
524 switch (Stream.readRecord(Entry.ID, Record)) {
525 default: return Error("unknown type in type table");
526 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
527 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
528 // type list. This allows us to reserve space.
529 if (Record.size() < 1)
530 return Error("Invalid TYPE_CODE_NUMENTRY record");
531 TypeList.resize(Record[0]);
533 case bitc::TYPE_CODE_VOID: // VOID
534 ResultTy = Type::getVoidTy(Context);
536 case bitc::TYPE_CODE_HALF: // HALF
537 ResultTy = Type::getHalfTy(Context);
539 case bitc::TYPE_CODE_FLOAT: // FLOAT
540 ResultTy = Type::getFloatTy(Context);
542 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
543 ResultTy = Type::getDoubleTy(Context);
545 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
546 ResultTy = Type::getX86_FP80Ty(Context);
548 case bitc::TYPE_CODE_FP128: // FP128
549 ResultTy = Type::getFP128Ty(Context);
551 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
552 ResultTy = Type::getPPC_FP128Ty(Context);
554 case bitc::TYPE_CODE_LABEL: // LABEL
555 ResultTy = Type::getLabelTy(Context);
557 case bitc::TYPE_CODE_METADATA: // METADATA
558 ResultTy = Type::getMetadataTy(Context);
560 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
561 ResultTy = Type::getX86_MMXTy(Context);
563 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
564 if (Record.size() < 1)
565 return Error("Invalid Integer type record");
567 ResultTy = IntegerType::get(Context, Record[0]);
569 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
570 // [pointee type, address space]
571 if (Record.size() < 1)
572 return Error("Invalid POINTER type record");
573 unsigned AddressSpace = 0;
574 if (Record.size() == 2)
575 AddressSpace = Record[1];
576 ResultTy = getTypeByID(Record[0]);
577 if (ResultTy == 0) return Error("invalid element type in pointer type");
578 ResultTy = PointerType::get(ResultTy, AddressSpace);
581 case bitc::TYPE_CODE_FUNCTION_OLD: {
582 // FIXME: attrid is dead, remove it in LLVM 4.0
583 // FUNCTION: [vararg, attrid, retty, paramty x N]
584 if (Record.size() < 3)
585 return Error("Invalid FUNCTION type record");
586 SmallVector<Type*, 8> ArgTys;
587 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
588 if (Type *T = getTypeByID(Record[i]))
594 ResultTy = getTypeByID(Record[2]);
595 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
596 return Error("invalid type in function type");
598 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
601 case bitc::TYPE_CODE_FUNCTION: {
602 // FUNCTION: [vararg, retty, paramty x N]
603 if (Record.size() < 2)
604 return Error("Invalid FUNCTION type record");
605 SmallVector<Type*, 8> ArgTys;
606 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
607 if (Type *T = getTypeByID(Record[i]))
613 ResultTy = getTypeByID(Record[1]);
614 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
615 return Error("invalid type in function type");
617 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
620 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
621 if (Record.size() < 1)
622 return Error("Invalid STRUCT type record");
623 SmallVector<Type*, 8> EltTys;
624 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
625 if (Type *T = getTypeByID(Record[i]))
630 if (EltTys.size() != Record.size()-1)
631 return Error("invalid type in struct type");
632 ResultTy = StructType::get(Context, EltTys, Record[0]);
635 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
636 if (ConvertToString(Record, 0, TypeName))
637 return Error("Invalid STRUCT_NAME record");
640 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
641 if (Record.size() < 1)
642 return Error("Invalid STRUCT type record");
644 if (NumRecords >= TypeList.size())
645 return Error("invalid TYPE table");
647 // Check to see if this was forward referenced, if so fill in the temp.
648 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
650 Res->setName(TypeName);
651 TypeList[NumRecords] = 0;
652 } else // Otherwise, create a new struct.
653 Res = StructType::create(Context, TypeName);
656 SmallVector<Type*, 8> EltTys;
657 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
658 if (Type *T = getTypeByID(Record[i]))
663 if (EltTys.size() != Record.size()-1)
664 return Error("invalid STRUCT type record");
665 Res->setBody(EltTys, Record[0]);
669 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
670 if (Record.size() != 1)
671 return Error("Invalid OPAQUE type record");
673 if (NumRecords >= TypeList.size())
674 return Error("invalid TYPE table");
676 // Check to see if this was forward referenced, if so fill in the temp.
677 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
679 Res->setName(TypeName);
680 TypeList[NumRecords] = 0;
681 } else // Otherwise, create a new struct with no body.
682 Res = StructType::create(Context, TypeName);
687 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
688 if (Record.size() < 2)
689 return Error("Invalid ARRAY type record");
690 if ((ResultTy = getTypeByID(Record[1])))
691 ResultTy = ArrayType::get(ResultTy, Record[0]);
693 return Error("Invalid ARRAY type element");
695 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
696 if (Record.size() < 2)
697 return Error("Invalid VECTOR type record");
698 if ((ResultTy = getTypeByID(Record[1])))
699 ResultTy = VectorType::get(ResultTy, Record[0]);
701 return Error("Invalid ARRAY type element");
705 if (NumRecords >= TypeList.size())
706 return Error("invalid TYPE table");
707 assert(ResultTy && "Didn't read a type?");
708 assert(TypeList[NumRecords] == 0 && "Already read type?");
709 TypeList[NumRecords++] = ResultTy;
713 bool BitcodeReader::ParseValueSymbolTable() {
714 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
715 return Error("Malformed block record");
717 SmallVector<uint64_t, 64> Record;
719 // Read all the records for this value table.
720 SmallString<128> ValueName;
722 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
724 switch (Entry.Kind) {
725 case BitstreamEntry::SubBlock: // Handled for us already.
726 case BitstreamEntry::Error:
727 return Error("malformed value symbol table block");
728 case BitstreamEntry::EndBlock:
730 case BitstreamEntry::Record:
731 // The interesting case.
737 switch (Stream.readRecord(Entry.ID, Record)) {
738 default: // Default behavior: unknown type.
740 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
741 if (ConvertToString(Record, 1, ValueName))
742 return Error("Invalid VST_ENTRY record");
743 unsigned ValueID = Record[0];
744 if (ValueID >= ValueList.size())
745 return Error("Invalid Value ID in VST_ENTRY record");
746 Value *V = ValueList[ValueID];
748 V->setName(StringRef(ValueName.data(), ValueName.size()));
752 case bitc::VST_CODE_BBENTRY: {
753 if (ConvertToString(Record, 1, ValueName))
754 return Error("Invalid VST_BBENTRY record");
755 BasicBlock *BB = getBasicBlock(Record[0]);
757 return Error("Invalid BB ID in VST_BBENTRY record");
759 BB->setName(StringRef(ValueName.data(), ValueName.size()));
767 bool BitcodeReader::ParseMetadata() {
768 unsigned NextMDValueNo = MDValueList.size();
770 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
771 return Error("Malformed block record");
773 SmallVector<uint64_t, 64> Record;
775 // Read all the records.
777 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
779 switch (Entry.Kind) {
780 case BitstreamEntry::SubBlock: // Handled for us already.
781 case BitstreamEntry::Error:
782 Error("malformed metadata block");
784 case BitstreamEntry::EndBlock:
786 case BitstreamEntry::Record:
787 // The interesting case.
791 bool IsFunctionLocal = false;
794 unsigned Code = Stream.readRecord(Entry.ID, Record);
796 default: // Default behavior: ignore.
798 case bitc::METADATA_NAME: {
799 // Read name of the named metadata.
800 SmallString<8> Name(Record.begin(), Record.end());
802 Code = Stream.ReadCode();
804 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
805 unsigned NextBitCode = Stream.readRecord(Code, Record);
806 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
808 // Read named metadata elements.
809 unsigned Size = Record.size();
810 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
811 for (unsigned i = 0; i != Size; ++i) {
812 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
814 return Error("Malformed metadata record");
819 case bitc::METADATA_FN_NODE:
820 IsFunctionLocal = true;
822 case bitc::METADATA_NODE: {
823 if (Record.size() % 2 == 1)
824 return Error("Invalid METADATA_NODE record");
826 unsigned Size = Record.size();
827 SmallVector<Value*, 8> Elts;
828 for (unsigned i = 0; i != Size; i += 2) {
829 Type *Ty = getTypeByID(Record[i]);
830 if (!Ty) return Error("Invalid METADATA_NODE record");
831 if (Ty->isMetadataTy())
832 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
833 else if (!Ty->isVoidTy())
834 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
836 Elts.push_back(NULL);
838 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
839 IsFunctionLocal = false;
840 MDValueList.AssignValue(V, NextMDValueNo++);
843 case bitc::METADATA_STRING: {
844 SmallString<8> String(Record.begin(), Record.end());
845 Value *V = MDString::get(Context, String);
846 MDValueList.AssignValue(V, NextMDValueNo++);
849 case bitc::METADATA_KIND: {
850 if (Record.size() < 2)
851 return Error("Invalid METADATA_KIND record");
853 unsigned Kind = Record[0];
854 SmallString<8> Name(Record.begin()+1, Record.end());
856 unsigned NewKind = TheModule->getMDKindID(Name.str());
857 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
858 return Error("Conflicting METADATA_KIND records");
865 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
866 /// the LSB for dense VBR encoding.
867 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
872 // There is no such thing as -0 with integers. "-0" really means MININT.
876 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
877 /// values and aliases that we can.
878 bool BitcodeReader::ResolveGlobalAndAliasInits() {
879 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
880 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
882 GlobalInitWorklist.swap(GlobalInits);
883 AliasInitWorklist.swap(AliasInits);
885 while (!GlobalInitWorklist.empty()) {
886 unsigned ValID = GlobalInitWorklist.back().second;
887 if (ValID >= ValueList.size()) {
888 // Not ready to resolve this yet, it requires something later in the file.
889 GlobalInits.push_back(GlobalInitWorklist.back());
891 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
892 GlobalInitWorklist.back().first->setInitializer(C);
894 return Error("Global variable initializer is not a constant!");
896 GlobalInitWorklist.pop_back();
899 while (!AliasInitWorklist.empty()) {
900 unsigned ValID = AliasInitWorklist.back().second;
901 if (ValID >= ValueList.size()) {
902 AliasInits.push_back(AliasInitWorklist.back());
904 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
905 AliasInitWorklist.back().first->setAliasee(C);
907 return Error("Alias initializer is not a constant!");
909 AliasInitWorklist.pop_back();
914 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
915 SmallVector<uint64_t, 8> Words(Vals.size());
916 std::transform(Vals.begin(), Vals.end(), Words.begin(),
917 BitcodeReader::decodeSignRotatedValue);
919 return APInt(TypeBits, Words);
922 bool BitcodeReader::ParseConstants() {
923 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
924 return Error("Malformed block record");
926 SmallVector<uint64_t, 64> Record;
928 // Read all the records for this value table.
929 Type *CurTy = Type::getInt32Ty(Context);
930 unsigned NextCstNo = ValueList.size();
932 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
934 switch (Entry.Kind) {
935 case BitstreamEntry::SubBlock: // Handled for us already.
936 case BitstreamEntry::Error:
937 return Error("malformed block record in AST file");
938 case BitstreamEntry::EndBlock:
939 if (NextCstNo != ValueList.size())
940 return Error("Invalid constant reference!");
942 // Once all the constants have been read, go through and resolve forward
944 ValueList.ResolveConstantForwardRefs();
946 case BitstreamEntry::Record:
947 // The interesting case.
954 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
956 default: // Default behavior: unknown constant
957 case bitc::CST_CODE_UNDEF: // UNDEF
958 V = UndefValue::get(CurTy);
960 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
962 return Error("Malformed CST_SETTYPE record");
963 if (Record[0] >= TypeList.size())
964 return Error("Invalid Type ID in CST_SETTYPE record");
965 CurTy = TypeList[Record[0]];
966 continue; // Skip the ValueList manipulation.
967 case bitc::CST_CODE_NULL: // NULL
968 V = Constant::getNullValue(CurTy);
970 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
971 if (!CurTy->isIntegerTy() || Record.empty())
972 return Error("Invalid CST_INTEGER record");
973 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
975 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
976 if (!CurTy->isIntegerTy() || Record.empty())
977 return Error("Invalid WIDE_INTEGER record");
979 APInt VInt = ReadWideAPInt(Record,
980 cast<IntegerType>(CurTy)->getBitWidth());
981 V = ConstantInt::get(Context, VInt);
985 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
987 return Error("Invalid FLOAT record");
988 if (CurTy->isHalfTy())
989 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
990 APInt(16, (uint16_t)Record[0])));
991 else if (CurTy->isFloatTy())
992 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
993 APInt(32, (uint32_t)Record[0])));
994 else if (CurTy->isDoubleTy())
995 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
996 APInt(64, Record[0])));
997 else if (CurTy->isX86_FP80Ty()) {
998 // Bits are not stored the same way as a normal i80 APInt, compensate.
999 uint64_t Rearrange[2];
1000 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1001 Rearrange[1] = Record[0] >> 48;
1002 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1003 APInt(80, Rearrange)));
1004 } else if (CurTy->isFP128Ty())
1005 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1006 APInt(128, Record)));
1007 else if (CurTy->isPPC_FP128Ty())
1008 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1009 APInt(128, Record)));
1011 V = UndefValue::get(CurTy);
1015 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1017 return Error("Invalid CST_AGGREGATE record");
1019 unsigned Size = Record.size();
1020 SmallVector<Constant*, 16> Elts;
1022 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1023 for (unsigned i = 0; i != Size; ++i)
1024 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1025 STy->getElementType(i)));
1026 V = ConstantStruct::get(STy, Elts);
1027 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1028 Type *EltTy = ATy->getElementType();
1029 for (unsigned i = 0; i != Size; ++i)
1030 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1031 V = ConstantArray::get(ATy, Elts);
1032 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1033 Type *EltTy = VTy->getElementType();
1034 for (unsigned i = 0; i != Size; ++i)
1035 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1036 V = ConstantVector::get(Elts);
1038 V = UndefValue::get(CurTy);
1042 case bitc::CST_CODE_STRING: // STRING: [values]
1043 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1045 return Error("Invalid CST_STRING record");
1047 SmallString<16> Elts(Record.begin(), Record.end());
1048 V = ConstantDataArray::getString(Context, Elts,
1049 BitCode == bitc::CST_CODE_CSTRING);
1052 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1054 return Error("Invalid CST_DATA record");
1056 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1057 unsigned Size = Record.size();
1059 if (EltTy->isIntegerTy(8)) {
1060 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1061 if (isa<VectorType>(CurTy))
1062 V = ConstantDataVector::get(Context, Elts);
1064 V = ConstantDataArray::get(Context, Elts);
1065 } else if (EltTy->isIntegerTy(16)) {
1066 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1067 if (isa<VectorType>(CurTy))
1068 V = ConstantDataVector::get(Context, Elts);
1070 V = ConstantDataArray::get(Context, Elts);
1071 } else if (EltTy->isIntegerTy(32)) {
1072 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1073 if (isa<VectorType>(CurTy))
1074 V = ConstantDataVector::get(Context, Elts);
1076 V = ConstantDataArray::get(Context, Elts);
1077 } else if (EltTy->isIntegerTy(64)) {
1078 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1079 if (isa<VectorType>(CurTy))
1080 V = ConstantDataVector::get(Context, Elts);
1082 V = ConstantDataArray::get(Context, Elts);
1083 } else if (EltTy->isFloatTy()) {
1084 SmallVector<float, 16> Elts(Size);
1085 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1086 if (isa<VectorType>(CurTy))
1087 V = ConstantDataVector::get(Context, Elts);
1089 V = ConstantDataArray::get(Context, Elts);
1090 } else if (EltTy->isDoubleTy()) {
1091 SmallVector<double, 16> Elts(Size);
1092 std::transform(Record.begin(), Record.end(), Elts.begin(),
1094 if (isa<VectorType>(CurTy))
1095 V = ConstantDataVector::get(Context, Elts);
1097 V = ConstantDataArray::get(Context, Elts);
1099 return Error("Unknown element type in CE_DATA");
1104 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1105 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1106 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1108 V = UndefValue::get(CurTy); // Unknown binop.
1110 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1111 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1113 if (Record.size() >= 4) {
1114 if (Opc == Instruction::Add ||
1115 Opc == Instruction::Sub ||
1116 Opc == Instruction::Mul ||
1117 Opc == Instruction::Shl) {
1118 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1119 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1120 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1121 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1122 } else if (Opc == Instruction::SDiv ||
1123 Opc == Instruction::UDiv ||
1124 Opc == Instruction::LShr ||
1125 Opc == Instruction::AShr) {
1126 if (Record[3] & (1 << bitc::PEO_EXACT))
1127 Flags |= SDivOperator::IsExact;
1130 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1134 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1135 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1136 int Opc = GetDecodedCastOpcode(Record[0]);
1138 V = UndefValue::get(CurTy); // Unknown cast.
1140 Type *OpTy = getTypeByID(Record[1]);
1141 if (!OpTy) return Error("Invalid CE_CAST record");
1142 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1143 V = ConstantExpr::getCast(Opc, Op, CurTy);
1147 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1148 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1149 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1150 SmallVector<Constant*, 16> Elts;
1151 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1152 Type *ElTy = getTypeByID(Record[i]);
1153 if (!ElTy) return Error("Invalid CE_GEP record");
1154 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1156 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1157 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1159 bitc::CST_CODE_CE_INBOUNDS_GEP);
1162 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1163 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1164 V = ConstantExpr::getSelect(
1165 ValueList.getConstantFwdRef(Record[0],
1166 Type::getInt1Ty(Context)),
1167 ValueList.getConstantFwdRef(Record[1],CurTy),
1168 ValueList.getConstantFwdRef(Record[2],CurTy));
1170 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1171 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1173 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1174 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1175 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1176 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1177 Type::getInt32Ty(Context));
1178 V = ConstantExpr::getExtractElement(Op0, Op1);
1181 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1182 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1183 if (Record.size() < 3 || OpTy == 0)
1184 return Error("Invalid CE_INSERTELT record");
1185 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1186 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1187 OpTy->getElementType());
1188 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1189 Type::getInt32Ty(Context));
1190 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1193 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1194 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1195 if (Record.size() < 3 || OpTy == 0)
1196 return Error("Invalid CE_SHUFFLEVEC record");
1197 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1198 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1199 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1200 OpTy->getNumElements());
1201 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1202 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1205 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1206 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1208 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1209 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1210 return Error("Invalid CE_SHUFVEC_EX record");
1211 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1212 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1213 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1214 RTy->getNumElements());
1215 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1216 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1219 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1220 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1221 Type *OpTy = getTypeByID(Record[0]);
1222 if (OpTy == 0) return Error("Invalid CE_CMP record");
1223 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1224 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1226 if (OpTy->isFPOrFPVectorTy())
1227 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1229 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1232 // This maintains backward compatibility, pre-asm dialect keywords.
1233 // FIXME: Remove with the 4.0 release.
1234 case bitc::CST_CODE_INLINEASM_OLD: {
1235 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1236 std::string AsmStr, ConstrStr;
1237 bool HasSideEffects = Record[0] & 1;
1238 bool IsAlignStack = Record[0] >> 1;
1239 unsigned AsmStrSize = Record[1];
1240 if (2+AsmStrSize >= Record.size())
1241 return Error("Invalid INLINEASM record");
1242 unsigned ConstStrSize = Record[2+AsmStrSize];
1243 if (3+AsmStrSize+ConstStrSize > Record.size())
1244 return Error("Invalid INLINEASM record");
1246 for (unsigned i = 0; i != AsmStrSize; ++i)
1247 AsmStr += (char)Record[2+i];
1248 for (unsigned i = 0; i != ConstStrSize; ++i)
1249 ConstrStr += (char)Record[3+AsmStrSize+i];
1250 PointerType *PTy = cast<PointerType>(CurTy);
1251 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1252 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1255 // This version adds support for the asm dialect keywords (e.g.,
1257 case bitc::CST_CODE_INLINEASM: {
1258 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1259 std::string AsmStr, ConstrStr;
1260 bool HasSideEffects = Record[0] & 1;
1261 bool IsAlignStack = (Record[0] >> 1) & 1;
1262 unsigned AsmDialect = Record[0] >> 2;
1263 unsigned AsmStrSize = Record[1];
1264 if (2+AsmStrSize >= Record.size())
1265 return Error("Invalid INLINEASM record");
1266 unsigned ConstStrSize = Record[2+AsmStrSize];
1267 if (3+AsmStrSize+ConstStrSize > Record.size())
1268 return Error("Invalid INLINEASM record");
1270 for (unsigned i = 0; i != AsmStrSize; ++i)
1271 AsmStr += (char)Record[2+i];
1272 for (unsigned i = 0; i != ConstStrSize; ++i)
1273 ConstrStr += (char)Record[3+AsmStrSize+i];
1274 PointerType *PTy = cast<PointerType>(CurTy);
1275 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1276 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1277 InlineAsm::AsmDialect(AsmDialect));
1280 case bitc::CST_CODE_BLOCKADDRESS:{
1281 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1282 Type *FnTy = getTypeByID(Record[0]);
1283 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1285 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1286 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1288 // If the function is already parsed we can insert the block address right
1291 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1292 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1294 return Error("Invalid blockaddress block #");
1297 V = BlockAddress::get(Fn, BBI);
1299 // Otherwise insert a placeholder and remember it so it can be inserted
1300 // when the function is parsed.
1301 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1302 Type::getInt8Ty(Context),
1303 false, GlobalValue::InternalLinkage,
1305 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1312 ValueList.AssignValue(V, NextCstNo);
1317 bool BitcodeReader::ParseUseLists() {
1318 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1319 return Error("Malformed block record");
1321 SmallVector<uint64_t, 64> Record;
1323 // Read all the records.
1325 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1327 switch (Entry.Kind) {
1328 case BitstreamEntry::SubBlock: // Handled for us already.
1329 case BitstreamEntry::Error:
1330 return Error("malformed use list block");
1331 case BitstreamEntry::EndBlock:
1333 case BitstreamEntry::Record:
1334 // The interesting case.
1338 // Read a use list record.
1340 switch (Stream.readRecord(Entry.ID, Record)) {
1341 default: // Default behavior: unknown type.
1343 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1344 unsigned RecordLength = Record.size();
1345 if (RecordLength < 1)
1346 return Error ("Invalid UseList reader!");
1347 UseListRecords.push_back(Record);
1354 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1355 /// remember where it is and then skip it. This lets us lazily deserialize the
1357 bool BitcodeReader::RememberAndSkipFunctionBody() {
1358 // Get the function we are talking about.
1359 if (FunctionsWithBodies.empty())
1360 return Error("Insufficient function protos");
1362 Function *Fn = FunctionsWithBodies.back();
1363 FunctionsWithBodies.pop_back();
1365 // Save the current stream state.
1366 uint64_t CurBit = Stream.GetCurrentBitNo();
1367 DeferredFunctionInfo[Fn] = CurBit;
1369 // Skip over the function block for now.
1370 if (Stream.SkipBlock())
1371 return Error("Malformed block record");
1375 bool BitcodeReader::GlobalCleanup() {
1376 // Patch the initializers for globals and aliases up.
1377 ResolveGlobalAndAliasInits();
1378 if (!GlobalInits.empty() || !AliasInits.empty())
1379 return Error("Malformed global initializer set");
1381 // Look for intrinsic functions which need to be upgraded at some point
1382 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1385 if (UpgradeIntrinsicFunction(FI, NewFn))
1386 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1389 // Look for global variables which need to be renamed.
1390 for (Module::global_iterator
1391 GI = TheModule->global_begin(), GE = TheModule->global_end();
1393 UpgradeGlobalVariable(GI);
1394 // Force deallocation of memory for these vectors to favor the client that
1395 // want lazy deserialization.
1396 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1397 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1401 bool BitcodeReader::ParseModule(bool Resume) {
1403 Stream.JumpToBit(NextUnreadBit);
1404 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1405 return Error("Malformed block record");
1407 SmallVector<uint64_t, 64> Record;
1408 std::vector<std::string> SectionTable;
1409 std::vector<std::string> GCTable;
1411 // Read all the records for this module.
1413 BitstreamEntry Entry = Stream.advance();
1415 switch (Entry.Kind) {
1416 case BitstreamEntry::Error:
1417 Error("malformed module block");
1419 case BitstreamEntry::EndBlock:
1420 return GlobalCleanup();
1422 case BitstreamEntry::SubBlock:
1424 default: // Skip unknown content.
1425 if (Stream.SkipBlock())
1426 return Error("Malformed block record");
1428 case bitc::BLOCKINFO_BLOCK_ID:
1429 if (Stream.ReadBlockInfoBlock())
1430 return Error("Malformed BlockInfoBlock");
1432 case bitc::PARAMATTR_BLOCK_ID:
1433 if (ParseAttributeBlock())
1436 case bitc::TYPE_BLOCK_ID_NEW:
1437 if (ParseTypeTable())
1440 case bitc::VALUE_SYMTAB_BLOCK_ID:
1441 if (ParseValueSymbolTable())
1443 SeenValueSymbolTable = true;
1445 case bitc::CONSTANTS_BLOCK_ID:
1446 if (ParseConstants() || ResolveGlobalAndAliasInits())
1449 case bitc::METADATA_BLOCK_ID:
1450 if (ParseMetadata())
1453 case bitc::FUNCTION_BLOCK_ID:
1454 // If this is the first function body we've seen, reverse the
1455 // FunctionsWithBodies list.
1456 if (!SeenFirstFunctionBody) {
1457 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1458 if (GlobalCleanup())
1460 SeenFirstFunctionBody = true;
1463 if (RememberAndSkipFunctionBody())
1465 // For streaming bitcode, suspend parsing when we reach the function
1466 // bodies. Subsequent materialization calls will resume it when
1467 // necessary. For streaming, the function bodies must be at the end of
1468 // the bitcode. If the bitcode file is old, the symbol table will be
1469 // at the end instead and will not have been seen yet. In this case,
1470 // just finish the parse now.
1471 if (LazyStreamer && SeenValueSymbolTable) {
1472 NextUnreadBit = Stream.GetCurrentBitNo();
1476 case bitc::USELIST_BLOCK_ID:
1477 if (ParseUseLists())
1483 case BitstreamEntry::Record:
1484 // The interesting case.
1490 switch (Stream.readRecord(Entry.ID, Record)) {
1491 default: break; // Default behavior, ignore unknown content.
1492 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1493 if (Record.size() < 1)
1494 return Error("Malformed MODULE_CODE_VERSION");
1495 // Only version #0 and #1 are supported so far.
1496 unsigned module_version = Record[0];
1497 switch (module_version) {
1498 default: return Error("Unknown bitstream version!");
1500 UseRelativeIDs = false;
1503 UseRelativeIDs = true;
1508 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1510 if (ConvertToString(Record, 0, S))
1511 return Error("Invalid MODULE_CODE_TRIPLE record");
1512 TheModule->setTargetTriple(S);
1515 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1517 if (ConvertToString(Record, 0, S))
1518 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1519 TheModule->setDataLayout(S);
1522 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1524 if (ConvertToString(Record, 0, S))
1525 return Error("Invalid MODULE_CODE_ASM record");
1526 TheModule->setModuleInlineAsm(S);
1529 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1530 // FIXME: Remove in 4.0.
1532 if (ConvertToString(Record, 0, S))
1533 return Error("Invalid MODULE_CODE_DEPLIB record");
1537 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1539 if (ConvertToString(Record, 0, S))
1540 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1541 SectionTable.push_back(S);
1544 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1546 if (ConvertToString(Record, 0, S))
1547 return Error("Invalid MODULE_CODE_GCNAME record");
1548 GCTable.push_back(S);
1551 // GLOBALVAR: [pointer type, isconst, initid,
1552 // linkage, alignment, section, visibility, threadlocal,
1554 case bitc::MODULE_CODE_GLOBALVAR: {
1555 if (Record.size() < 6)
1556 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1557 Type *Ty = getTypeByID(Record[0]);
1558 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1559 if (!Ty->isPointerTy())
1560 return Error("Global not a pointer type!");
1561 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1562 Ty = cast<PointerType>(Ty)->getElementType();
1564 bool isConstant = Record[1];
1565 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1566 unsigned Alignment = (1 << Record[4]) >> 1;
1567 std::string Section;
1569 if (Record[5]-1 >= SectionTable.size())
1570 return Error("Invalid section ID");
1571 Section = SectionTable[Record[5]-1];
1573 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1574 if (Record.size() > 6)
1575 Visibility = GetDecodedVisibility(Record[6]);
1577 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1578 if (Record.size() > 7)
1579 TLM = GetDecodedThreadLocalMode(Record[7]);
1581 bool UnnamedAddr = false;
1582 if (Record.size() > 8)
1583 UnnamedAddr = Record[8];
1585 GlobalVariable *NewGV =
1586 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1588 NewGV->setAlignment(Alignment);
1589 if (!Section.empty())
1590 NewGV->setSection(Section);
1591 NewGV->setVisibility(Visibility);
1592 NewGV->setUnnamedAddr(UnnamedAddr);
1594 ValueList.push_back(NewGV);
1596 // Remember which value to use for the global initializer.
1597 if (unsigned InitID = Record[2])
1598 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1601 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1602 // alignment, section, visibility, gc, unnamed_addr]
1603 case bitc::MODULE_CODE_FUNCTION: {
1604 if (Record.size() < 8)
1605 return Error("Invalid MODULE_CODE_FUNCTION record");
1606 Type *Ty = getTypeByID(Record[0]);
1607 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1608 if (!Ty->isPointerTy())
1609 return Error("Function not a pointer type!");
1611 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1613 return Error("Function not a pointer to function type!");
1615 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1618 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1619 bool isProto = Record[2];
1620 Func->setLinkage(GetDecodedLinkage(Record[3]));
1621 Func->setAttributes(getAttributes(Record[4]));
1623 Func->setAlignment((1 << Record[5]) >> 1);
1625 if (Record[6]-1 >= SectionTable.size())
1626 return Error("Invalid section ID");
1627 Func->setSection(SectionTable[Record[6]-1]);
1629 Func->setVisibility(GetDecodedVisibility(Record[7]));
1630 if (Record.size() > 8 && Record[8]) {
1631 if (Record[8]-1 > GCTable.size())
1632 return Error("Invalid GC ID");
1633 Func->setGC(GCTable[Record[8]-1].c_str());
1635 bool UnnamedAddr = false;
1636 if (Record.size() > 9)
1637 UnnamedAddr = Record[9];
1638 Func->setUnnamedAddr(UnnamedAddr);
1639 ValueList.push_back(Func);
1641 // If this is a function with a body, remember the prototype we are
1642 // creating now, so that we can match up the body with them later.
1644 FunctionsWithBodies.push_back(Func);
1645 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1649 // ALIAS: [alias type, aliasee val#, linkage]
1650 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1651 case bitc::MODULE_CODE_ALIAS: {
1652 if (Record.size() < 3)
1653 return Error("Invalid MODULE_ALIAS record");
1654 Type *Ty = getTypeByID(Record[0]);
1655 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1656 if (!Ty->isPointerTy())
1657 return Error("Function not a pointer type!");
1659 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1661 // Old bitcode files didn't have visibility field.
1662 if (Record.size() > 3)
1663 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1664 ValueList.push_back(NewGA);
1665 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1668 /// MODULE_CODE_PURGEVALS: [numvals]
1669 case bitc::MODULE_CODE_PURGEVALS:
1670 // Trim down the value list to the specified size.
1671 if (Record.size() < 1 || Record[0] > ValueList.size())
1672 return Error("Invalid MODULE_PURGEVALS record");
1673 ValueList.shrinkTo(Record[0]);
1680 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1683 if (InitStream()) return true;
1685 // Sniff for the signature.
1686 if (Stream.Read(8) != 'B' ||
1687 Stream.Read(8) != 'C' ||
1688 Stream.Read(4) != 0x0 ||
1689 Stream.Read(4) != 0xC ||
1690 Stream.Read(4) != 0xE ||
1691 Stream.Read(4) != 0xD)
1692 return Error("Invalid bitcode signature");
1694 // We expect a number of well-defined blocks, though we don't necessarily
1695 // need to understand them all.
1697 if (Stream.AtEndOfStream())
1700 BitstreamEntry Entry =
1701 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1703 switch (Entry.Kind) {
1704 case BitstreamEntry::Error:
1705 Error("malformed module file");
1707 case BitstreamEntry::EndBlock:
1710 case BitstreamEntry::SubBlock:
1712 case bitc::BLOCKINFO_BLOCK_ID:
1713 if (Stream.ReadBlockInfoBlock())
1714 return Error("Malformed BlockInfoBlock");
1716 case bitc::MODULE_BLOCK_ID:
1717 // Reject multiple MODULE_BLOCK's in a single bitstream.
1719 return Error("Multiple MODULE_BLOCKs in same stream");
1721 if (ParseModule(false))
1723 if (LazyStreamer) return false;
1726 if (Stream.SkipBlock())
1727 return Error("Malformed block record");
1731 case BitstreamEntry::Record:
1732 // There should be no records in the top-level of blocks.
1734 // The ranlib in Xcode 4 will align archive members by appending newlines
1735 // to the end of them. If this file size is a multiple of 4 but not 8, we
1736 // have to read and ignore these final 4 bytes :-(
1737 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1738 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1739 Stream.AtEndOfStream())
1742 return Error("Invalid record at top-level");
1747 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1748 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1749 return Error("Malformed block record");
1751 SmallVector<uint64_t, 64> Record;
1753 // Read all the records for this module.
1755 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1757 switch (Entry.Kind) {
1758 case BitstreamEntry::SubBlock: // Handled for us already.
1759 case BitstreamEntry::Error:
1760 return Error("malformed module block");
1761 case BitstreamEntry::EndBlock:
1763 case BitstreamEntry::Record:
1764 // The interesting case.
1769 switch (Stream.readRecord(Entry.ID, Record)) {
1770 default: break; // Default behavior, ignore unknown content.
1771 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1773 if (ConvertToString(Record, 0, S))
1774 return Error("Invalid MODULE_CODE_TRIPLE record");
1783 bool BitcodeReader::ParseTriple(std::string &Triple) {
1784 if (InitStream()) return true;
1786 // Sniff for the signature.
1787 if (Stream.Read(8) != 'B' ||
1788 Stream.Read(8) != 'C' ||
1789 Stream.Read(4) != 0x0 ||
1790 Stream.Read(4) != 0xC ||
1791 Stream.Read(4) != 0xE ||
1792 Stream.Read(4) != 0xD)
1793 return Error("Invalid bitcode signature");
1795 // We expect a number of well-defined blocks, though we don't necessarily
1796 // need to understand them all.
1798 BitstreamEntry Entry = Stream.advance();
1800 switch (Entry.Kind) {
1801 case BitstreamEntry::Error:
1802 Error("malformed module file");
1804 case BitstreamEntry::EndBlock:
1807 case BitstreamEntry::SubBlock:
1808 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1809 return ParseModuleTriple(Triple);
1811 // Ignore other sub-blocks.
1812 if (Stream.SkipBlock()) {
1813 Error("malformed block record in AST file");
1818 case BitstreamEntry::Record:
1819 Stream.skipRecord(Entry.ID);
1825 /// ParseMetadataAttachment - Parse metadata attachments.
1826 bool BitcodeReader::ParseMetadataAttachment() {
1827 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1828 return Error("Malformed block record");
1830 SmallVector<uint64_t, 64> Record;
1832 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1834 switch (Entry.Kind) {
1835 case BitstreamEntry::SubBlock: // Handled for us already.
1836 case BitstreamEntry::Error:
1837 return Error("malformed metadata block");
1838 case BitstreamEntry::EndBlock:
1840 case BitstreamEntry::Record:
1841 // The interesting case.
1845 // Read a metadata attachment record.
1847 switch (Stream.readRecord(Entry.ID, Record)) {
1848 default: // Default behavior: ignore.
1850 case bitc::METADATA_ATTACHMENT: {
1851 unsigned RecordLength = Record.size();
1852 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1853 return Error ("Invalid METADATA_ATTACHMENT reader!");
1854 Instruction *Inst = InstructionList[Record[0]];
1855 for (unsigned i = 1; i != RecordLength; i = i+2) {
1856 unsigned Kind = Record[i];
1857 DenseMap<unsigned, unsigned>::iterator I =
1858 MDKindMap.find(Kind);
1859 if (I == MDKindMap.end())
1860 return Error("Invalid metadata kind ID");
1861 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1862 Inst->setMetadata(I->second, cast<MDNode>(Node));
1870 /// ParseFunctionBody - Lazily parse the specified function body block.
1871 bool BitcodeReader::ParseFunctionBody(Function *F) {
1872 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1873 return Error("Malformed block record");
1875 InstructionList.clear();
1876 unsigned ModuleValueListSize = ValueList.size();
1877 unsigned ModuleMDValueListSize = MDValueList.size();
1879 // Add all the function arguments to the value table.
1880 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1881 ValueList.push_back(I);
1883 unsigned NextValueNo = ValueList.size();
1884 BasicBlock *CurBB = 0;
1885 unsigned CurBBNo = 0;
1889 // Read all the records.
1890 SmallVector<uint64_t, 64> Record;
1892 BitstreamEntry Entry = Stream.advance();
1894 switch (Entry.Kind) {
1895 case BitstreamEntry::Error:
1896 return Error("Bitcode error in function block");
1897 case BitstreamEntry::EndBlock:
1898 goto OutOfRecordLoop;
1900 case BitstreamEntry::SubBlock:
1902 default: // Skip unknown content.
1903 if (Stream.SkipBlock())
1904 return Error("Malformed block record");
1906 case bitc::CONSTANTS_BLOCK_ID:
1907 if (ParseConstants()) return true;
1908 NextValueNo = ValueList.size();
1910 case bitc::VALUE_SYMTAB_BLOCK_ID:
1911 if (ParseValueSymbolTable()) return true;
1913 case bitc::METADATA_ATTACHMENT_ID:
1914 if (ParseMetadataAttachment()) return true;
1916 case bitc::METADATA_BLOCK_ID:
1917 if (ParseMetadata()) return true;
1922 case BitstreamEntry::Record:
1923 // The interesting case.
1930 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1932 default: // Default behavior: reject
1933 return Error("Unknown instruction");
1934 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1935 if (Record.size() < 1 || Record[0] == 0)
1936 return Error("Invalid DECLAREBLOCKS record");
1937 // Create all the basic blocks for the function.
1938 FunctionBBs.resize(Record[0]);
1939 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1940 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1941 CurBB = FunctionBBs[0];
1944 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1945 // This record indicates that the last instruction is at the same
1946 // location as the previous instruction with a location.
1949 // Get the last instruction emitted.
1950 if (CurBB && !CurBB->empty())
1952 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1953 !FunctionBBs[CurBBNo-1]->empty())
1954 I = &FunctionBBs[CurBBNo-1]->back();
1956 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1957 I->setDebugLoc(LastLoc);
1961 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
1962 I = 0; // Get the last instruction emitted.
1963 if (CurBB && !CurBB->empty())
1965 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1966 !FunctionBBs[CurBBNo-1]->empty())
1967 I = &FunctionBBs[CurBBNo-1]->back();
1968 if (I == 0 || Record.size() < 4)
1969 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1971 unsigned Line = Record[0], Col = Record[1];
1972 unsigned ScopeID = Record[2], IAID = Record[3];
1974 MDNode *Scope = 0, *IA = 0;
1975 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1976 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1977 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1978 I->setDebugLoc(LastLoc);
1983 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1986 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1987 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
1988 OpNum+1 > Record.size())
1989 return Error("Invalid BINOP record");
1991 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1992 if (Opc == -1) return Error("Invalid BINOP record");
1993 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1994 InstructionList.push_back(I);
1995 if (OpNum < Record.size()) {
1996 if (Opc == Instruction::Add ||
1997 Opc == Instruction::Sub ||
1998 Opc == Instruction::Mul ||
1999 Opc == Instruction::Shl) {
2000 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2001 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2002 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2003 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2004 } else if (Opc == Instruction::SDiv ||
2005 Opc == Instruction::UDiv ||
2006 Opc == Instruction::LShr ||
2007 Opc == Instruction::AShr) {
2008 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2009 cast<BinaryOperator>(I)->setIsExact(true);
2010 } else if (isa<FPMathOperator>(I)) {
2012 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2013 FMF.setUnsafeAlgebra();
2014 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2016 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2018 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2019 FMF.setNoSignedZeros();
2020 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2021 FMF.setAllowReciprocal();
2023 I->setFastMathFlags(FMF);
2029 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2032 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2033 OpNum+2 != Record.size())
2034 return Error("Invalid CAST record");
2036 Type *ResTy = getTypeByID(Record[OpNum]);
2037 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2038 if (Opc == -1 || ResTy == 0)
2039 return Error("Invalid CAST record");
2040 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2041 InstructionList.push_back(I);
2044 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2045 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2048 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2049 return Error("Invalid GEP record");
2051 SmallVector<Value*, 16> GEPIdx;
2052 while (OpNum != Record.size()) {
2054 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2055 return Error("Invalid GEP record");
2056 GEPIdx.push_back(Op);
2059 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2060 InstructionList.push_back(I);
2061 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2062 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2066 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2067 // EXTRACTVAL: [opty, opval, n x indices]
2070 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2071 return Error("Invalid EXTRACTVAL record");
2073 SmallVector<unsigned, 4> EXTRACTVALIdx;
2074 for (unsigned RecSize = Record.size();
2075 OpNum != RecSize; ++OpNum) {
2076 uint64_t Index = Record[OpNum];
2077 if ((unsigned)Index != Index)
2078 return Error("Invalid EXTRACTVAL index");
2079 EXTRACTVALIdx.push_back((unsigned)Index);
2082 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2083 InstructionList.push_back(I);
2087 case bitc::FUNC_CODE_INST_INSERTVAL: {
2088 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2091 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2092 return Error("Invalid INSERTVAL record");
2094 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2095 return Error("Invalid INSERTVAL record");
2097 SmallVector<unsigned, 4> INSERTVALIdx;
2098 for (unsigned RecSize = Record.size();
2099 OpNum != RecSize; ++OpNum) {
2100 uint64_t Index = Record[OpNum];
2101 if ((unsigned)Index != Index)
2102 return Error("Invalid INSERTVAL index");
2103 INSERTVALIdx.push_back((unsigned)Index);
2106 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2107 InstructionList.push_back(I);
2111 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2112 // obsolete form of select
2113 // handles select i1 ... in old bitcode
2115 Value *TrueVal, *FalseVal, *Cond;
2116 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2117 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2118 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2119 return Error("Invalid SELECT record");
2121 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2122 InstructionList.push_back(I);
2126 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2127 // new form of select
2128 // handles select i1 or select [N x i1]
2130 Value *TrueVal, *FalseVal, *Cond;
2131 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2132 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2133 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2134 return Error("Invalid SELECT record");
2136 // select condition can be either i1 or [N x i1]
2137 if (VectorType* vector_type =
2138 dyn_cast<VectorType>(Cond->getType())) {
2140 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2141 return Error("Invalid SELECT condition type");
2144 if (Cond->getType() != Type::getInt1Ty(Context))
2145 return Error("Invalid SELECT condition type");
2148 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2149 InstructionList.push_back(I);
2153 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2156 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2157 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2158 return Error("Invalid EXTRACTELT record");
2159 I = ExtractElementInst::Create(Vec, Idx);
2160 InstructionList.push_back(I);
2164 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2166 Value *Vec, *Elt, *Idx;
2167 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2168 popValue(Record, OpNum, NextValueNo,
2169 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2170 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2171 return Error("Invalid INSERTELT record");
2172 I = InsertElementInst::Create(Vec, Elt, Idx);
2173 InstructionList.push_back(I);
2177 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2179 Value *Vec1, *Vec2, *Mask;
2180 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2181 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2182 return Error("Invalid SHUFFLEVEC record");
2184 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2185 return Error("Invalid SHUFFLEVEC record");
2186 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2187 InstructionList.push_back(I);
2191 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2192 // Old form of ICmp/FCmp returning bool
2193 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2194 // both legal on vectors but had different behaviour.
2195 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2196 // FCmp/ICmp returning bool or vector of bool
2200 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2201 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2202 OpNum+1 != Record.size())
2203 return Error("Invalid CMP record");
2205 if (LHS->getType()->isFPOrFPVectorTy())
2206 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2208 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2209 InstructionList.push_back(I);
2213 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2215 unsigned Size = Record.size();
2217 I = ReturnInst::Create(Context);
2218 InstructionList.push_back(I);
2224 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2225 return Error("Invalid RET record");
2226 if (OpNum != Record.size())
2227 return Error("Invalid RET record");
2229 I = ReturnInst::Create(Context, Op);
2230 InstructionList.push_back(I);
2233 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2234 if (Record.size() != 1 && Record.size() != 3)
2235 return Error("Invalid BR record");
2236 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2238 return Error("Invalid BR record");
2240 if (Record.size() == 1) {
2241 I = BranchInst::Create(TrueDest);
2242 InstructionList.push_back(I);
2245 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2246 Value *Cond = getValue(Record, 2, NextValueNo,
2247 Type::getInt1Ty(Context));
2248 if (FalseDest == 0 || Cond == 0)
2249 return Error("Invalid BR record");
2250 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2251 InstructionList.push_back(I);
2255 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2257 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2258 // New SwitchInst format with case ranges.
2260 Type *OpTy = getTypeByID(Record[1]);
2261 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2263 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2264 BasicBlock *Default = getBasicBlock(Record[3]);
2265 if (OpTy == 0 || Cond == 0 || Default == 0)
2266 return Error("Invalid SWITCH record");
2268 unsigned NumCases = Record[4];
2270 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2271 InstructionList.push_back(SI);
2273 unsigned CurIdx = 5;
2274 for (unsigned i = 0; i != NumCases; ++i) {
2275 IntegersSubsetToBB CaseBuilder;
2276 unsigned NumItems = Record[CurIdx++];
2277 for (unsigned ci = 0; ci != NumItems; ++ci) {
2278 bool isSingleNumber = Record[CurIdx++];
2281 unsigned ActiveWords = 1;
2282 if (ValueBitWidth > 64)
2283 ActiveWords = Record[CurIdx++];
2284 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2286 CurIdx += ActiveWords;
2288 if (!isSingleNumber) {
2290 if (ValueBitWidth > 64)
2291 ActiveWords = Record[CurIdx++];
2293 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2296 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2297 IntItem::fromType(OpTy, High));
2298 CurIdx += ActiveWords;
2300 CaseBuilder.add(IntItem::fromType(OpTy, Low));
2302 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2303 IntegersSubset Case = CaseBuilder.getCase();
2304 SI->addCase(Case, DestBB);
2306 uint16_t Hash = SI->hash();
2307 if (Hash != (Record[0] & 0xFFFF))
2308 return Error("Invalid SWITCH record");
2313 // Old SwitchInst format without case ranges.
2315 if (Record.size() < 3 || (Record.size() & 1) == 0)
2316 return Error("Invalid SWITCH record");
2317 Type *OpTy = getTypeByID(Record[0]);
2318 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2319 BasicBlock *Default = getBasicBlock(Record[2]);
2320 if (OpTy == 0 || Cond == 0 || Default == 0)
2321 return Error("Invalid SWITCH record");
2322 unsigned NumCases = (Record.size()-3)/2;
2323 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2324 InstructionList.push_back(SI);
2325 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2326 ConstantInt *CaseVal =
2327 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2328 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2329 if (CaseVal == 0 || DestBB == 0) {
2331 return Error("Invalid SWITCH record!");
2333 SI->addCase(CaseVal, DestBB);
2338 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2339 if (Record.size() < 2)
2340 return Error("Invalid INDIRECTBR record");
2341 Type *OpTy = getTypeByID(Record[0]);
2342 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2343 if (OpTy == 0 || Address == 0)
2344 return Error("Invalid INDIRECTBR record");
2345 unsigned NumDests = Record.size()-2;
2346 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2347 InstructionList.push_back(IBI);
2348 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2349 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2350 IBI->addDestination(DestBB);
2353 return Error("Invalid INDIRECTBR record!");
2360 case bitc::FUNC_CODE_INST_INVOKE: {
2361 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2362 if (Record.size() < 4) return Error("Invalid INVOKE record");
2363 AttributeSet PAL = getAttributes(Record[0]);
2364 unsigned CCInfo = Record[1];
2365 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2366 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2370 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2371 return Error("Invalid INVOKE record");
2373 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2374 FunctionType *FTy = !CalleeTy ? 0 :
2375 dyn_cast<FunctionType>(CalleeTy->getElementType());
2377 // Check that the right number of fixed parameters are here.
2378 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2379 Record.size() < OpNum+FTy->getNumParams())
2380 return Error("Invalid INVOKE record");
2382 SmallVector<Value*, 16> Ops;
2383 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2384 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2385 FTy->getParamType(i)));
2386 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2389 if (!FTy->isVarArg()) {
2390 if (Record.size() != OpNum)
2391 return Error("Invalid INVOKE record");
2393 // Read type/value pairs for varargs params.
2394 while (OpNum != Record.size()) {
2396 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2397 return Error("Invalid INVOKE record");
2402 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2403 InstructionList.push_back(I);
2404 cast<InvokeInst>(I)->setCallingConv(
2405 static_cast<CallingConv::ID>(CCInfo));
2406 cast<InvokeInst>(I)->setAttributes(PAL);
2409 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2412 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2413 return Error("Invalid RESUME record");
2414 I = ResumeInst::Create(Val);
2415 InstructionList.push_back(I);
2418 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2419 I = new UnreachableInst(Context);
2420 InstructionList.push_back(I);
2422 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2423 if (Record.size() < 1 || ((Record.size()-1)&1))
2424 return Error("Invalid PHI record");
2425 Type *Ty = getTypeByID(Record[0]);
2426 if (!Ty) return Error("Invalid PHI record");
2428 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2429 InstructionList.push_back(PN);
2431 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2433 // With the new function encoding, it is possible that operands have
2434 // negative IDs (for forward references). Use a signed VBR
2435 // representation to keep the encoding small.
2437 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2439 V = getValue(Record, 1+i, NextValueNo, Ty);
2440 BasicBlock *BB = getBasicBlock(Record[2+i]);
2441 if (!V || !BB) return Error("Invalid PHI record");
2442 PN->addIncoming(V, BB);
2448 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2449 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2451 if (Record.size() < 4)
2452 return Error("Invalid LANDINGPAD record");
2453 Type *Ty = getTypeByID(Record[Idx++]);
2454 if (!Ty) return Error("Invalid LANDINGPAD record");
2456 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2457 return Error("Invalid LANDINGPAD record");
2459 bool IsCleanup = !!Record[Idx++];
2460 unsigned NumClauses = Record[Idx++];
2461 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2462 LP->setCleanup(IsCleanup);
2463 for (unsigned J = 0; J != NumClauses; ++J) {
2464 LandingPadInst::ClauseType CT =
2465 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2468 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2470 return Error("Invalid LANDINGPAD record");
2473 assert((CT != LandingPadInst::Catch ||
2474 !isa<ArrayType>(Val->getType())) &&
2475 "Catch clause has a invalid type!");
2476 assert((CT != LandingPadInst::Filter ||
2477 isa<ArrayType>(Val->getType())) &&
2478 "Filter clause has invalid type!");
2483 InstructionList.push_back(I);
2487 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2488 if (Record.size() != 4)
2489 return Error("Invalid ALLOCA record");
2491 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2492 Type *OpTy = getTypeByID(Record[1]);
2493 Value *Size = getFnValueByID(Record[2], OpTy);
2494 unsigned Align = Record[3];
2495 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2496 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2497 InstructionList.push_back(I);
2500 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2503 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2504 OpNum+2 != Record.size())
2505 return Error("Invalid LOAD record");
2507 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2508 InstructionList.push_back(I);
2511 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2512 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2515 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2516 OpNum+4 != Record.size())
2517 return Error("Invalid LOADATOMIC record");
2520 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2521 if (Ordering == NotAtomic || Ordering == Release ||
2522 Ordering == AcquireRelease)
2523 return Error("Invalid LOADATOMIC record");
2524 if (Ordering != NotAtomic && Record[OpNum] == 0)
2525 return Error("Invalid LOADATOMIC record");
2526 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2528 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2529 Ordering, SynchScope);
2530 InstructionList.push_back(I);
2533 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2536 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2537 popValue(Record, OpNum, NextValueNo,
2538 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2539 OpNum+2 != Record.size())
2540 return Error("Invalid STORE record");
2542 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2543 InstructionList.push_back(I);
2546 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2547 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2550 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2551 popValue(Record, OpNum, NextValueNo,
2552 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2553 OpNum+4 != Record.size())
2554 return Error("Invalid STOREATOMIC record");
2556 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2557 if (Ordering == NotAtomic || Ordering == Acquire ||
2558 Ordering == AcquireRelease)
2559 return Error("Invalid STOREATOMIC record");
2560 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2561 if (Ordering != NotAtomic && Record[OpNum] == 0)
2562 return Error("Invalid STOREATOMIC record");
2564 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2565 Ordering, SynchScope);
2566 InstructionList.push_back(I);
2569 case bitc::FUNC_CODE_INST_CMPXCHG: {
2570 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2572 Value *Ptr, *Cmp, *New;
2573 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2574 popValue(Record, OpNum, NextValueNo,
2575 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2576 popValue(Record, OpNum, NextValueNo,
2577 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2578 OpNum+3 != Record.size())
2579 return Error("Invalid CMPXCHG record");
2580 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2581 if (Ordering == NotAtomic || Ordering == Unordered)
2582 return Error("Invalid CMPXCHG record");
2583 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2584 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2585 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2586 InstructionList.push_back(I);
2589 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2590 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2593 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2594 popValue(Record, OpNum, NextValueNo,
2595 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2596 OpNum+4 != Record.size())
2597 return Error("Invalid ATOMICRMW record");
2598 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2599 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2600 Operation > AtomicRMWInst::LAST_BINOP)
2601 return Error("Invalid ATOMICRMW record");
2602 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2603 if (Ordering == NotAtomic || Ordering == Unordered)
2604 return Error("Invalid ATOMICRMW record");
2605 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2606 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2607 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2608 InstructionList.push_back(I);
2611 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2612 if (2 != Record.size())
2613 return Error("Invalid FENCE record");
2614 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2615 if (Ordering == NotAtomic || Ordering == Unordered ||
2616 Ordering == Monotonic)
2617 return Error("Invalid FENCE record");
2618 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2619 I = new FenceInst(Context, Ordering, SynchScope);
2620 InstructionList.push_back(I);
2623 case bitc::FUNC_CODE_INST_CALL: {
2624 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2625 if (Record.size() < 3)
2626 return Error("Invalid CALL record");
2628 AttributeSet PAL = getAttributes(Record[0]);
2629 unsigned CCInfo = Record[1];
2633 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2634 return Error("Invalid CALL record");
2636 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2637 FunctionType *FTy = 0;
2638 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2639 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2640 return Error("Invalid CALL record");
2642 SmallVector<Value*, 16> Args;
2643 // Read the fixed params.
2644 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2645 if (FTy->getParamType(i)->isLabelTy())
2646 Args.push_back(getBasicBlock(Record[OpNum]));
2648 Args.push_back(getValue(Record, OpNum, NextValueNo,
2649 FTy->getParamType(i)));
2650 if (Args.back() == 0) return Error("Invalid CALL record");
2653 // Read type/value pairs for varargs params.
2654 if (!FTy->isVarArg()) {
2655 if (OpNum != Record.size())
2656 return Error("Invalid CALL record");
2658 while (OpNum != Record.size()) {
2660 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2661 return Error("Invalid CALL record");
2666 I = CallInst::Create(Callee, Args);
2667 InstructionList.push_back(I);
2668 cast<CallInst>(I)->setCallingConv(
2669 static_cast<CallingConv::ID>(CCInfo>>1));
2670 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2671 cast<CallInst>(I)->setAttributes(PAL);
2674 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2675 if (Record.size() < 3)
2676 return Error("Invalid VAARG record");
2677 Type *OpTy = getTypeByID(Record[0]);
2678 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2679 Type *ResTy = getTypeByID(Record[2]);
2680 if (!OpTy || !Op || !ResTy)
2681 return Error("Invalid VAARG record");
2682 I = new VAArgInst(Op, ResTy);
2683 InstructionList.push_back(I);
2688 // Add instruction to end of current BB. If there is no current BB, reject
2692 return Error("Invalid instruction with no BB");
2694 CurBB->getInstList().push_back(I);
2696 // If this was a terminator instruction, move to the next block.
2697 if (isa<TerminatorInst>(I)) {
2699 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2702 // Non-void values get registered in the value table for future use.
2703 if (I && !I->getType()->isVoidTy())
2704 ValueList.AssignValue(I, NextValueNo++);
2709 // Check the function list for unresolved values.
2710 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2711 if (A->getParent() == 0) {
2712 // We found at least one unresolved value. Nuke them all to avoid leaks.
2713 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2714 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2715 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2719 return Error("Never resolved value found in function!");
2723 // FIXME: Check for unresolved forward-declared metadata references
2724 // and clean up leaks.
2726 // See if anything took the address of blocks in this function. If so,
2727 // resolve them now.
2728 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2729 BlockAddrFwdRefs.find(F);
2730 if (BAFRI != BlockAddrFwdRefs.end()) {
2731 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2732 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2733 unsigned BlockIdx = RefList[i].first;
2734 if (BlockIdx >= FunctionBBs.size())
2735 return Error("Invalid blockaddress block #");
2737 GlobalVariable *FwdRef = RefList[i].second;
2738 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2739 FwdRef->eraseFromParent();
2742 BlockAddrFwdRefs.erase(BAFRI);
2745 // Trim the value list down to the size it was before we parsed this function.
2746 ValueList.shrinkTo(ModuleValueListSize);
2747 MDValueList.shrinkTo(ModuleMDValueListSize);
2748 std::vector<BasicBlock*>().swap(FunctionBBs);
2752 /// FindFunctionInStream - Find the function body in the bitcode stream
2753 bool BitcodeReader::FindFunctionInStream(Function *F,
2754 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2755 while (DeferredFunctionInfoIterator->second == 0) {
2756 if (Stream.AtEndOfStream())
2757 return Error("Could not find Function in stream");
2758 // ParseModule will parse the next body in the stream and set its
2759 // position in the DeferredFunctionInfo map.
2760 if (ParseModule(true)) return true;
2765 //===----------------------------------------------------------------------===//
2766 // GVMaterializer implementation
2767 //===----------------------------------------------------------------------===//
2770 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2771 if (const Function *F = dyn_cast<Function>(GV)) {
2772 return F->isDeclaration() &&
2773 DeferredFunctionInfo.count(const_cast<Function*>(F));
2778 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2779 Function *F = dyn_cast<Function>(GV);
2780 // If it's not a function or is already material, ignore the request.
2781 if (!F || !F->isMaterializable()) return false;
2783 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2784 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2785 // If its position is recorded as 0, its body is somewhere in the stream
2786 // but we haven't seen it yet.
2787 if (DFII->second == 0)
2788 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2790 // Move the bit stream to the saved position of the deferred function body.
2791 Stream.JumpToBit(DFII->second);
2793 if (ParseFunctionBody(F)) {
2794 if (ErrInfo) *ErrInfo = ErrorString;
2798 // Upgrade any old intrinsic calls in the function.
2799 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2800 E = UpgradedIntrinsics.end(); I != E; ++I) {
2801 if (I->first != I->second) {
2802 for (Value::use_iterator UI = I->first->use_begin(),
2803 UE = I->first->use_end(); UI != UE; ) {
2804 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2805 UpgradeIntrinsicCall(CI, I->second);
2813 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2814 const Function *F = dyn_cast<Function>(GV);
2815 if (!F || F->isDeclaration())
2817 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2820 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2821 Function *F = dyn_cast<Function>(GV);
2822 // If this function isn't dematerializable, this is a noop.
2823 if (!F || !isDematerializable(F))
2826 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2828 // Just forget the function body, we can remat it later.
2833 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2834 assert(M == TheModule &&
2835 "Can only Materialize the Module this BitcodeReader is attached to.");
2836 // Iterate over the module, deserializing any functions that are still on
2838 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2840 if (F->isMaterializable() &&
2841 Materialize(F, ErrInfo))
2844 // At this point, if there are any function bodies, the current bit is
2845 // pointing to the END_BLOCK record after them. Now make sure the rest
2846 // of the bits in the module have been read.
2850 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2851 // delete the old functions to clean up. We can't do this unless the entire
2852 // module is materialized because there could always be another function body
2853 // with calls to the old function.
2854 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2855 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2856 if (I->first != I->second) {
2857 for (Value::use_iterator UI = I->first->use_begin(),
2858 UE = I->first->use_end(); UI != UE; ) {
2859 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2860 UpgradeIntrinsicCall(CI, I->second);
2862 if (!I->first->use_empty())
2863 I->first->replaceAllUsesWith(I->second);
2864 I->first->eraseFromParent();
2867 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2872 bool BitcodeReader::InitStream() {
2873 if (LazyStreamer) return InitLazyStream();
2874 return InitStreamFromBuffer();
2877 bool BitcodeReader::InitStreamFromBuffer() {
2878 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
2879 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2881 if (Buffer->getBufferSize() & 3) {
2882 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2883 return Error("Invalid bitcode signature");
2885 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2888 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2889 // The magic number is 0x0B17C0DE stored in little endian.
2890 if (isBitcodeWrapper(BufPtr, BufEnd))
2891 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2892 return Error("Invalid bitcode wrapper header");
2894 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2895 Stream.init(*StreamFile);
2900 bool BitcodeReader::InitLazyStream() {
2901 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2903 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2904 StreamFile.reset(new BitstreamReader(Bytes));
2905 Stream.init(*StreamFile);
2907 unsigned char buf[16];
2908 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2909 return Error("Bitcode stream must be at least 16 bytes in length");
2911 if (!isBitcode(buf, buf + 16))
2912 return Error("Invalid bitcode signature");
2914 if (isBitcodeWrapper(buf, buf + 4)) {
2915 const unsigned char *bitcodeStart = buf;
2916 const unsigned char *bitcodeEnd = buf + 16;
2917 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2918 Bytes->dropLeadingBytes(bitcodeStart - buf);
2919 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2924 //===----------------------------------------------------------------------===//
2925 // External interface
2926 //===----------------------------------------------------------------------===//
2928 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2930 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2931 LLVMContext& Context,
2932 std::string *ErrMsg) {
2933 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2934 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2935 M->setMaterializer(R);
2936 if (R->ParseBitcodeInto(M)) {
2938 *ErrMsg = R->getErrorString();
2940 delete M; // Also deletes R.
2943 // Have the BitcodeReader dtor delete 'Buffer'.
2944 R->setBufferOwned(true);
2946 R->materializeForwardReferencedFunctions();
2952 Module *llvm::getStreamedBitcodeModule(const std::string &name,
2953 DataStreamer *streamer,
2954 LLVMContext &Context,
2955 std::string *ErrMsg) {
2956 Module *M = new Module(name, Context);
2957 BitcodeReader *R = new BitcodeReader(streamer, Context);
2958 M->setMaterializer(R);
2959 if (R->ParseBitcodeInto(M)) {
2961 *ErrMsg = R->getErrorString();
2962 delete M; // Also deletes R.
2965 R->setBufferOwned(false); // no buffer to delete
2969 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2970 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2971 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2972 std::string *ErrMsg){
2973 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2976 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2977 // there was an error.
2978 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2980 // Read in the entire module, and destroy the BitcodeReader.
2981 if (M->MaterializeAllPermanently(ErrMsg)) {
2986 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2987 // written. We must defer until the Module has been fully materialized.
2992 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2993 LLVMContext& Context,
2994 std::string *ErrMsg) {
2995 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2996 // Don't let the BitcodeReader dtor delete 'Buffer'.
2997 R->setBufferOwned(false);
2999 std::string Triple("");
3000 if (R->ParseTriple(Triple))
3002 *ErrMsg = R->getErrorString();