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/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
41 void BitcodeReader::FreeState() {
45 std::vector<Type*>().swap(TypeList);
49 std::vector<AttributeSet>().swap(MAttributes);
50 std::vector<BasicBlock*>().swap(FunctionBBs);
51 std::vector<Function*>().swap(FunctionsWithBodies);
52 DeferredFunctionInfo.clear();
55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
58 //===----------------------------------------------------------------------===//
59 // Helper functions to implement forward reference resolution, etc.
60 //===----------------------------------------------------------------------===//
62 /// ConvertToString - Convert a string from a record into an std::string, return
64 template<typename StrTy>
65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
67 if (Idx > Record.size())
70 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71 Result += (char)Record[i];
75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 default: // Map unknown/new linkages to external
78 case 0: return GlobalValue::ExternalLinkage;
79 case 1: return GlobalValue::WeakAnyLinkage;
80 case 2: return GlobalValue::AppendingLinkage;
81 case 3: return GlobalValue::InternalLinkage;
82 case 4: return GlobalValue::LinkOnceAnyLinkage;
83 case 5: return GlobalValue::DLLImportLinkage;
84 case 6: return GlobalValue::DLLExportLinkage;
85 case 7: return GlobalValue::ExternalWeakLinkage;
86 case 8: return GlobalValue::CommonLinkage;
87 case 9: return GlobalValue::PrivateLinkage;
88 case 10: return GlobalValue::WeakODRLinkage;
89 case 11: return GlobalValue::LinkOnceODRLinkage;
90 case 12: return GlobalValue::AvailableExternallyLinkage;
91 case 13: return GlobalValue::LinkerPrivateLinkage;
92 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
96 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
101 case 2: return GlobalValue::ProtectedVisibility;
105 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
107 case 0: return GlobalVariable::NotThreadLocal;
108 default: // Map unknown non-zero value to general dynamic.
109 case 1: return GlobalVariable::GeneralDynamicTLSModel;
110 case 2: return GlobalVariable::LocalDynamicTLSModel;
111 case 3: return GlobalVariable::InitialExecTLSModel;
112 case 4: return GlobalVariable::LocalExecTLSModel;
116 static int GetDecodedCastOpcode(unsigned Val) {
119 case bitc::CAST_TRUNC : return Instruction::Trunc;
120 case bitc::CAST_ZEXT : return Instruction::ZExt;
121 case bitc::CAST_SEXT : return Instruction::SExt;
122 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
123 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
124 case bitc::CAST_UITOFP : return Instruction::UIToFP;
125 case bitc::CAST_SITOFP : return Instruction::SIToFP;
126 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
127 case bitc::CAST_FPEXT : return Instruction::FPExt;
128 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
129 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
130 case bitc::CAST_BITCAST : return Instruction::BitCast;
133 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
136 case bitc::BINOP_ADD:
137 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
138 case bitc::BINOP_SUB:
139 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
140 case bitc::BINOP_MUL:
141 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
142 case bitc::BINOP_UDIV: return Instruction::UDiv;
143 case bitc::BINOP_SDIV:
144 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
145 case bitc::BINOP_UREM: return Instruction::URem;
146 case bitc::BINOP_SREM:
147 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
148 case bitc::BINOP_SHL: return Instruction::Shl;
149 case bitc::BINOP_LSHR: return Instruction::LShr;
150 case bitc::BINOP_ASHR: return Instruction::AShr;
151 case bitc::BINOP_AND: return Instruction::And;
152 case bitc::BINOP_OR: return Instruction::Or;
153 case bitc::BINOP_XOR: return Instruction::Xor;
157 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
159 default: return AtomicRMWInst::BAD_BINOP;
160 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
161 case bitc::RMW_ADD: return AtomicRMWInst::Add;
162 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
163 case bitc::RMW_AND: return AtomicRMWInst::And;
164 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
165 case bitc::RMW_OR: return AtomicRMWInst::Or;
166 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
167 case bitc::RMW_MAX: return AtomicRMWInst::Max;
168 case bitc::RMW_MIN: return AtomicRMWInst::Min;
169 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
170 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
174 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
176 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
177 case bitc::ORDERING_UNORDERED: return Unordered;
178 case bitc::ORDERING_MONOTONIC: return Monotonic;
179 case bitc::ORDERING_ACQUIRE: return Acquire;
180 case bitc::ORDERING_RELEASE: return Release;
181 case bitc::ORDERING_ACQREL: return AcquireRelease;
182 default: // Map unknown orderings to sequentially-consistent.
183 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
187 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
189 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
190 default: // Map unknown scopes to cross-thread.
191 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
197 /// @brief A class for maintaining the slot number definition
198 /// as a placeholder for the actual definition for forward constants defs.
199 class ConstantPlaceHolder : public ConstantExpr {
200 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
202 // allocate space for exactly one operand
203 void *operator new(size_t s) {
204 return User::operator new(s, 1);
206 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
207 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
208 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
211 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
212 static bool classof(const Value *V) {
213 return isa<ConstantExpr>(V) &&
214 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
218 /// Provide fast operand accessors
219 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
223 // FIXME: can we inherit this from ConstantExpr?
225 struct OperandTraits<ConstantPlaceHolder> :
226 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
231 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
240 WeakVH &OldV = ValuePtrs[Idx];
246 // Handle constants and non-constants (e.g. instrs) differently for
248 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
249 ResolveConstants.push_back(std::make_pair(PHC, Idx));
252 // If there was a forward reference to this value, replace it.
253 Value *PrevVal = OldV;
254 OldV->replaceAllUsesWith(V);
260 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
265 if (Value *V = ValuePtrs[Idx]) {
266 assert(Ty == V->getType() && "Type mismatch in constant table!");
267 return cast<Constant>(V);
270 // Create and return a placeholder, which will later be RAUW'd.
271 Constant *C = new ConstantPlaceHolder(Ty, Context);
276 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
280 if (Value *V = ValuePtrs[Idx]) {
281 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
285 // No type specified, must be invalid reference.
286 if (Ty == 0) return 0;
288 // Create and return a placeholder, which will later be RAUW'd.
289 Value *V = new Argument(Ty);
294 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
295 /// resolves any forward references. The idea behind this is that we sometimes
296 /// get constants (such as large arrays) which reference *many* forward ref
297 /// constants. Replacing each of these causes a lot of thrashing when
298 /// building/reuniquing the constant. Instead of doing this, we look at all the
299 /// uses and rewrite all the place holders at once for any constant that uses
301 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
302 // Sort the values by-pointer so that they are efficient to look up with a
304 std::sort(ResolveConstants.begin(), ResolveConstants.end());
306 SmallVector<Constant*, 64> NewOps;
308 while (!ResolveConstants.empty()) {
309 Value *RealVal = operator[](ResolveConstants.back().second);
310 Constant *Placeholder = ResolveConstants.back().first;
311 ResolveConstants.pop_back();
313 // Loop over all users of the placeholder, updating them to reference the
314 // new value. If they reference more than one placeholder, update them all
316 while (!Placeholder->use_empty()) {
317 Value::use_iterator UI = Placeholder->use_begin();
320 // If the using object isn't uniqued, just update the operands. This
321 // handles instructions and initializers for global variables.
322 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
323 UI.getUse().set(RealVal);
327 // Otherwise, we have a constant that uses the placeholder. Replace that
328 // constant with a new constant that has *all* placeholder uses updated.
329 Constant *UserC = cast<Constant>(U);
330 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
333 if (!isa<ConstantPlaceHolder>(*I)) {
334 // Not a placeholder reference.
336 } else if (*I == Placeholder) {
337 // Common case is that it just references this one placeholder.
340 // Otherwise, look up the placeholder in ResolveConstants.
341 ResolveConstantsTy::iterator It =
342 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
343 std::pair<Constant*, unsigned>(cast<Constant>(*I),
345 assert(It != ResolveConstants.end() && It->first == *I);
346 NewOp = operator[](It->second);
349 NewOps.push_back(cast<Constant>(NewOp));
352 // Make the new constant.
354 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
355 NewC = ConstantArray::get(UserCA->getType(), NewOps);
356 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
357 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
358 } else if (isa<ConstantVector>(UserC)) {
359 NewC = ConstantVector::get(NewOps);
361 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
362 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
365 UserC->replaceAllUsesWith(NewC);
366 UserC->destroyConstant();
370 // Update all ValueHandles, they should be the only users at this point.
371 Placeholder->replaceAllUsesWith(RealVal);
376 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
385 WeakVH &OldV = MDValuePtrs[Idx];
391 // If there was a forward reference to this value, replace it.
392 MDNode *PrevVal = cast<MDNode>(OldV);
393 OldV->replaceAllUsesWith(V);
394 MDNode::deleteTemporary(PrevVal);
395 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
397 MDValuePtrs[Idx] = V;
400 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
404 if (Value *V = MDValuePtrs[Idx]) {
405 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
409 // Create and return a placeholder, which will later be RAUW'd.
410 Value *V = MDNode::getTemporary(Context, None);
411 MDValuePtrs[Idx] = V;
415 Type *BitcodeReader::getTypeByID(unsigned ID) {
416 // The type table size is always specified correctly.
417 if (ID >= TypeList.size())
420 if (Type *Ty = TypeList[ID])
423 // If we have a forward reference, the only possible case is when it is to a
424 // named struct. Just create a placeholder for now.
425 return TypeList[ID] = StructType::create(Context);
429 //===----------------------------------------------------------------------===//
430 // Functions for parsing blocks from the bitcode file
431 //===----------------------------------------------------------------------===//
434 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
435 /// been decoded from the given integer. This function must stay in sync with
436 /// 'encodeLLVMAttributesForBitcode'.
437 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
438 uint64_t EncodedAttrs) {
439 // FIXME: Remove in 4.0.
441 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
442 // the bits above 31 down by 11 bits.
443 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
444 assert((!Alignment || isPowerOf2_32(Alignment)) &&
445 "Alignment must be a power of two.");
448 B.addAlignmentAttr(Alignment);
449 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
450 (EncodedAttrs & 0xffff));
453 error_code BitcodeReader::ParseAttributeBlock() {
454 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
455 return Error(InvalidRecord);
457 if (!MAttributes.empty())
458 return Error(InvalidMultipleBlocks);
460 SmallVector<uint64_t, 64> Record;
462 SmallVector<AttributeSet, 8> Attrs;
464 // Read all the records.
466 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
468 switch (Entry.Kind) {
469 case BitstreamEntry::SubBlock: // Handled for us already.
470 case BitstreamEntry::Error:
471 return Error(MalformedBlock);
472 case BitstreamEntry::EndBlock:
473 return error_code::success();
474 case BitstreamEntry::Record:
475 // The interesting case.
481 switch (Stream.readRecord(Entry.ID, Record)) {
482 default: // Default behavior: ignore.
484 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
485 // FIXME: Remove in 4.0.
486 if (Record.size() & 1)
487 return Error(InvalidRecord);
489 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
491 decodeLLVMAttributesForBitcode(B, Record[i+1]);
492 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
495 MAttributes.push_back(AttributeSet::get(Context, Attrs));
499 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
500 for (unsigned i = 0, e = Record.size(); i != e; ++i)
501 Attrs.push_back(MAttributeGroups[Record[i]]);
503 MAttributes.push_back(AttributeSet::get(Context, Attrs));
511 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
512 Attribute::AttrKind *Kind) {
514 case bitc::ATTR_KIND_ALIGNMENT:
515 *Kind = Attribute::Alignment;
516 return error_code::success();
517 case bitc::ATTR_KIND_ALWAYS_INLINE:
518 *Kind = Attribute::AlwaysInline;
519 return error_code::success();
520 case bitc::ATTR_KIND_BUILTIN:
521 *Kind = Attribute::Builtin;
522 return error_code::success();
523 case bitc::ATTR_KIND_BY_VAL:
524 *Kind = Attribute::ByVal;
525 return error_code::success();
526 case bitc::ATTR_KIND_COLD:
527 *Kind = Attribute::Cold;
528 return error_code::success();
529 case bitc::ATTR_KIND_INLINE_HINT:
530 *Kind = Attribute::InlineHint;
531 return error_code::success();
532 case bitc::ATTR_KIND_IN_REG:
533 *Kind = Attribute::InReg;
534 return error_code::success();
535 case bitc::ATTR_KIND_MIN_SIZE:
536 *Kind = Attribute::MinSize;
537 return error_code::success();
538 case bitc::ATTR_KIND_NAKED:
539 *Kind = Attribute::Naked;
540 return error_code::success();
541 case bitc::ATTR_KIND_NEST:
542 *Kind = Attribute::Nest;
543 return error_code::success();
544 case bitc::ATTR_KIND_NO_ALIAS:
545 *Kind = Attribute::NoAlias;
546 return error_code::success();
547 case bitc::ATTR_KIND_NO_BUILTIN:
548 *Kind = Attribute::NoBuiltin;
549 return error_code::success();
550 case bitc::ATTR_KIND_NO_CAPTURE:
551 *Kind = Attribute::NoCapture;
552 return error_code::success();
553 case bitc::ATTR_KIND_NO_DUPLICATE:
554 *Kind = Attribute::NoDuplicate;
555 return error_code::success();
556 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
557 *Kind = Attribute::NoImplicitFloat;
558 return error_code::success();
559 case bitc::ATTR_KIND_NO_INLINE:
560 *Kind = Attribute::NoInline;
561 return error_code::success();
562 case bitc::ATTR_KIND_NON_LAZY_BIND:
563 *Kind = Attribute::NonLazyBind;
564 return error_code::success();
565 case bitc::ATTR_KIND_NO_RED_ZONE:
566 *Kind = Attribute::NoRedZone;
567 return error_code::success();
568 case bitc::ATTR_KIND_NO_RETURN:
569 *Kind = Attribute::NoReturn;
570 return error_code::success();
571 case bitc::ATTR_KIND_NO_UNWIND:
572 *Kind = Attribute::NoUnwind;
573 return error_code::success();
574 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
575 *Kind = Attribute::OptimizeForSize;
576 return error_code::success();
577 case bitc::ATTR_KIND_OPTIMIZE_NONE:
578 *Kind = Attribute::OptimizeNone;
579 return error_code::success();
580 case bitc::ATTR_KIND_READ_NONE:
581 *Kind = Attribute::ReadNone;
582 return error_code::success();
583 case bitc::ATTR_KIND_READ_ONLY:
584 *Kind = Attribute::ReadOnly;
585 return error_code::success();
586 case bitc::ATTR_KIND_RETURNED:
587 *Kind = Attribute::Returned;
588 return error_code::success();
589 case bitc::ATTR_KIND_RETURNS_TWICE:
590 *Kind = Attribute::ReturnsTwice;
591 return error_code::success();
592 case bitc::ATTR_KIND_S_EXT:
593 *Kind = Attribute::SExt;
594 return error_code::success();
595 case bitc::ATTR_KIND_STACK_ALIGNMENT:
596 *Kind = Attribute::StackAlignment;
597 return error_code::success();
598 case bitc::ATTR_KIND_STACK_PROTECT:
599 *Kind = Attribute::StackProtect;
600 return error_code::success();
601 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
602 *Kind = Attribute::StackProtectReq;
603 return error_code::success();
604 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
605 *Kind = Attribute::StackProtectStrong;
606 return error_code::success();
607 case bitc::ATTR_KIND_STRUCT_RET:
608 *Kind = Attribute::StructRet;
609 return error_code::success();
610 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
611 *Kind = Attribute::SanitizeAddress;
612 return error_code::success();
613 case bitc::ATTR_KIND_SANITIZE_THREAD:
614 *Kind = Attribute::SanitizeThread;
615 return error_code::success();
616 case bitc::ATTR_KIND_SANITIZE_MEMORY:
617 *Kind = Attribute::SanitizeMemory;
618 return error_code::success();
619 case bitc::ATTR_KIND_UW_TABLE:
620 *Kind = Attribute::UWTable;
621 return error_code::success();
622 case bitc::ATTR_KIND_Z_EXT:
623 *Kind = Attribute::ZExt;
624 return error_code::success();
626 return Error(InvalidValue);
630 error_code BitcodeReader::ParseAttributeGroupBlock() {
631 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
632 return Error(InvalidRecord);
634 if (!MAttributeGroups.empty())
635 return Error(InvalidMultipleBlocks);
637 SmallVector<uint64_t, 64> Record;
639 // Read all the records.
641 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
643 switch (Entry.Kind) {
644 case BitstreamEntry::SubBlock: // Handled for us already.
645 case BitstreamEntry::Error:
646 return Error(MalformedBlock);
647 case BitstreamEntry::EndBlock:
648 return error_code::success();
649 case BitstreamEntry::Record:
650 // The interesting case.
656 switch (Stream.readRecord(Entry.ID, Record)) {
657 default: // Default behavior: ignore.
659 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
660 if (Record.size() < 3)
661 return Error(InvalidRecord);
663 uint64_t GrpID = Record[0];
664 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
667 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
668 if (Record[i] == 0) { // Enum attribute
669 Attribute::AttrKind Kind;
670 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
673 B.addAttribute(Kind);
674 } else if (Record[i] == 1) { // Align attribute
675 Attribute::AttrKind Kind;
676 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
678 if (Kind == Attribute::Alignment)
679 B.addAlignmentAttr(Record[++i]);
681 B.addStackAlignmentAttr(Record[++i]);
682 } else { // String attribute
683 assert((Record[i] == 3 || Record[i] == 4) &&
684 "Invalid attribute group entry");
685 bool HasValue = (Record[i++] == 4);
686 SmallString<64> KindStr;
687 SmallString<64> ValStr;
689 while (Record[i] != 0 && i != e)
690 KindStr += Record[i++];
691 assert(Record[i] == 0 && "Kind string not null terminated");
694 // Has a value associated with it.
695 ++i; // Skip the '0' that terminates the "kind" string.
696 while (Record[i] != 0 && i != e)
697 ValStr += Record[i++];
698 assert(Record[i] == 0 && "Value string not null terminated");
701 B.addAttribute(KindStr.str(), ValStr.str());
705 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
712 error_code BitcodeReader::ParseTypeTable() {
713 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
714 return Error(InvalidRecord);
716 return ParseTypeTableBody();
719 error_code BitcodeReader::ParseTypeTableBody() {
720 if (!TypeList.empty())
721 return Error(InvalidMultipleBlocks);
723 SmallVector<uint64_t, 64> Record;
724 unsigned NumRecords = 0;
726 SmallString<64> TypeName;
728 // Read all the records for this type table.
730 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
732 switch (Entry.Kind) {
733 case BitstreamEntry::SubBlock: // Handled for us already.
734 case BitstreamEntry::Error:
735 return Error(MalformedBlock);
736 case BitstreamEntry::EndBlock:
737 if (NumRecords != TypeList.size())
738 return Error(MalformedBlock);
739 return error_code::success();
740 case BitstreamEntry::Record:
741 // The interesting case.
748 switch (Stream.readRecord(Entry.ID, Record)) {
750 return Error(InvalidValue);
751 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
752 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
753 // type list. This allows us to reserve space.
754 if (Record.size() < 1)
755 return Error(InvalidRecord);
756 TypeList.resize(Record[0]);
758 case bitc::TYPE_CODE_VOID: // VOID
759 ResultTy = Type::getVoidTy(Context);
761 case bitc::TYPE_CODE_HALF: // HALF
762 ResultTy = Type::getHalfTy(Context);
764 case bitc::TYPE_CODE_FLOAT: // FLOAT
765 ResultTy = Type::getFloatTy(Context);
767 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
768 ResultTy = Type::getDoubleTy(Context);
770 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
771 ResultTy = Type::getX86_FP80Ty(Context);
773 case bitc::TYPE_CODE_FP128: // FP128
774 ResultTy = Type::getFP128Ty(Context);
776 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
777 ResultTy = Type::getPPC_FP128Ty(Context);
779 case bitc::TYPE_CODE_LABEL: // LABEL
780 ResultTy = Type::getLabelTy(Context);
782 case bitc::TYPE_CODE_METADATA: // METADATA
783 ResultTy = Type::getMetadataTy(Context);
785 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
786 ResultTy = Type::getX86_MMXTy(Context);
788 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
789 if (Record.size() < 1)
790 return Error(InvalidRecord);
792 ResultTy = IntegerType::get(Context, Record[0]);
794 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
795 // [pointee type, address space]
796 if (Record.size() < 1)
797 return Error(InvalidRecord);
798 unsigned AddressSpace = 0;
799 if (Record.size() == 2)
800 AddressSpace = Record[1];
801 ResultTy = getTypeByID(Record[0]);
803 return Error(InvalidType);
804 ResultTy = PointerType::get(ResultTy, AddressSpace);
807 case bitc::TYPE_CODE_FUNCTION_OLD: {
808 // FIXME: attrid is dead, remove it in LLVM 4.0
809 // FUNCTION: [vararg, attrid, retty, paramty x N]
810 if (Record.size() < 3)
811 return Error(InvalidRecord);
812 SmallVector<Type*, 8> ArgTys;
813 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
814 if (Type *T = getTypeByID(Record[i]))
820 ResultTy = getTypeByID(Record[2]);
821 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
822 return Error(InvalidType);
824 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
827 case bitc::TYPE_CODE_FUNCTION: {
828 // FUNCTION: [vararg, retty, paramty x N]
829 if (Record.size() < 2)
830 return Error(InvalidRecord);
831 SmallVector<Type*, 8> ArgTys;
832 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
833 if (Type *T = getTypeByID(Record[i]))
839 ResultTy = getTypeByID(Record[1]);
840 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
841 return Error(InvalidType);
843 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
846 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
847 if (Record.size() < 1)
848 return Error(InvalidRecord);
849 SmallVector<Type*, 8> EltTys;
850 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
851 if (Type *T = getTypeByID(Record[i]))
856 if (EltTys.size() != Record.size()-1)
857 return Error(InvalidType);
858 ResultTy = StructType::get(Context, EltTys, Record[0]);
861 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
862 if (ConvertToString(Record, 0, TypeName))
863 return Error(InvalidRecord);
866 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
867 if (Record.size() < 1)
868 return Error(InvalidRecord);
870 if (NumRecords >= TypeList.size())
871 return Error(InvalidTYPETable);
873 // Check to see if this was forward referenced, if so fill in the temp.
874 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
876 Res->setName(TypeName);
877 TypeList[NumRecords] = 0;
878 } else // Otherwise, create a new struct.
879 Res = StructType::create(Context, TypeName);
882 SmallVector<Type*, 8> EltTys;
883 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
884 if (Type *T = getTypeByID(Record[i]))
889 if (EltTys.size() != Record.size()-1)
890 return Error(InvalidRecord);
891 Res->setBody(EltTys, Record[0]);
895 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
896 if (Record.size() != 1)
897 return Error(InvalidRecord);
899 if (NumRecords >= TypeList.size())
900 return Error(InvalidTYPETable);
902 // Check to see if this was forward referenced, if so fill in the temp.
903 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
905 Res->setName(TypeName);
906 TypeList[NumRecords] = 0;
907 } else // Otherwise, create a new struct with no body.
908 Res = StructType::create(Context, TypeName);
913 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
914 if (Record.size() < 2)
915 return Error(InvalidRecord);
916 if ((ResultTy = getTypeByID(Record[1])))
917 ResultTy = ArrayType::get(ResultTy, Record[0]);
919 return Error(InvalidType);
921 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
922 if (Record.size() < 2)
923 return Error(InvalidRecord);
924 if ((ResultTy = getTypeByID(Record[1])))
925 ResultTy = VectorType::get(ResultTy, Record[0]);
927 return Error(InvalidType);
931 if (NumRecords >= TypeList.size())
932 return Error(InvalidTYPETable);
933 assert(ResultTy && "Didn't read a type?");
934 assert(TypeList[NumRecords] == 0 && "Already read type?");
935 TypeList[NumRecords++] = ResultTy;
939 error_code BitcodeReader::ParseValueSymbolTable() {
940 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
941 return Error(InvalidRecord);
943 SmallVector<uint64_t, 64> Record;
945 // Read all the records for this value table.
946 SmallString<128> ValueName;
948 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
950 switch (Entry.Kind) {
951 case BitstreamEntry::SubBlock: // Handled for us already.
952 case BitstreamEntry::Error:
953 return Error(MalformedBlock);
954 case BitstreamEntry::EndBlock:
955 return error_code::success();
956 case BitstreamEntry::Record:
957 // The interesting case.
963 switch (Stream.readRecord(Entry.ID, Record)) {
964 default: // Default behavior: unknown type.
966 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
967 if (ConvertToString(Record, 1, ValueName))
968 return Error(InvalidRecord);
969 unsigned ValueID = Record[0];
970 if (ValueID >= ValueList.size())
971 return Error(InvalidRecord);
972 Value *V = ValueList[ValueID];
974 V->setName(StringRef(ValueName.data(), ValueName.size()));
978 case bitc::VST_CODE_BBENTRY: {
979 if (ConvertToString(Record, 1, ValueName))
980 return Error(InvalidRecord);
981 BasicBlock *BB = getBasicBlock(Record[0]);
983 return Error(InvalidRecord);
985 BB->setName(StringRef(ValueName.data(), ValueName.size()));
993 error_code BitcodeReader::ParseMetadata() {
994 unsigned NextMDValueNo = MDValueList.size();
996 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
997 return Error(InvalidRecord);
999 SmallVector<uint64_t, 64> Record;
1001 // Read all the records.
1003 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1005 switch (Entry.Kind) {
1006 case BitstreamEntry::SubBlock: // Handled for us already.
1007 case BitstreamEntry::Error:
1008 return Error(MalformedBlock);
1009 case BitstreamEntry::EndBlock:
1010 return error_code::success();
1011 case BitstreamEntry::Record:
1012 // The interesting case.
1016 bool IsFunctionLocal = false;
1019 unsigned Code = Stream.readRecord(Entry.ID, Record);
1021 default: // Default behavior: ignore.
1023 case bitc::METADATA_NAME: {
1024 // Read name of the named metadata.
1025 SmallString<8> Name(Record.begin(), Record.end());
1027 Code = Stream.ReadCode();
1029 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1030 unsigned NextBitCode = Stream.readRecord(Code, Record);
1031 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1033 // Read named metadata elements.
1034 unsigned Size = Record.size();
1035 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1036 for (unsigned i = 0; i != Size; ++i) {
1037 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1039 return Error(InvalidRecord);
1040 NMD->addOperand(MD);
1044 case bitc::METADATA_FN_NODE:
1045 IsFunctionLocal = true;
1047 case bitc::METADATA_NODE: {
1048 if (Record.size() % 2 == 1)
1049 return Error(InvalidRecord);
1051 unsigned Size = Record.size();
1052 SmallVector<Value*, 8> Elts;
1053 for (unsigned i = 0; i != Size; i += 2) {
1054 Type *Ty = getTypeByID(Record[i]);
1056 return Error(InvalidRecord);
1057 if (Ty->isMetadataTy())
1058 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1059 else if (!Ty->isVoidTy())
1060 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1062 Elts.push_back(NULL);
1064 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1065 IsFunctionLocal = false;
1066 MDValueList.AssignValue(V, NextMDValueNo++);
1069 case bitc::METADATA_STRING: {
1070 SmallString<8> String(Record.begin(), Record.end());
1071 Value *V = MDString::get(Context, String);
1072 MDValueList.AssignValue(V, NextMDValueNo++);
1075 case bitc::METADATA_KIND: {
1076 if (Record.size() < 2)
1077 return Error(InvalidRecord);
1079 unsigned Kind = Record[0];
1080 SmallString<8> Name(Record.begin()+1, Record.end());
1082 unsigned NewKind = TheModule->getMDKindID(Name.str());
1083 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1084 return Error(ConflictingMETADATA_KINDRecords);
1091 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1092 /// the LSB for dense VBR encoding.
1093 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1098 // There is no such thing as -0 with integers. "-0" really means MININT.
1102 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1103 /// values and aliases that we can.
1104 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1105 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1106 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1107 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1109 GlobalInitWorklist.swap(GlobalInits);
1110 AliasInitWorklist.swap(AliasInits);
1111 FunctionPrefixWorklist.swap(FunctionPrefixes);
1113 while (!GlobalInitWorklist.empty()) {
1114 unsigned ValID = GlobalInitWorklist.back().second;
1115 if (ValID >= ValueList.size()) {
1116 // Not ready to resolve this yet, it requires something later in the file.
1117 GlobalInits.push_back(GlobalInitWorklist.back());
1119 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1120 GlobalInitWorklist.back().first->setInitializer(C);
1122 return Error(ExpectedConstant);
1124 GlobalInitWorklist.pop_back();
1127 while (!AliasInitWorklist.empty()) {
1128 unsigned ValID = AliasInitWorklist.back().second;
1129 if (ValID >= ValueList.size()) {
1130 AliasInits.push_back(AliasInitWorklist.back());
1132 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1133 AliasInitWorklist.back().first->setAliasee(C);
1135 return Error(ExpectedConstant);
1137 AliasInitWorklist.pop_back();
1140 while (!FunctionPrefixWorklist.empty()) {
1141 unsigned ValID = FunctionPrefixWorklist.back().second;
1142 if (ValID >= ValueList.size()) {
1143 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1145 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1146 FunctionPrefixWorklist.back().first->setPrefixData(C);
1148 return Error(ExpectedConstant);
1150 FunctionPrefixWorklist.pop_back();
1153 return error_code::success();
1156 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1157 SmallVector<uint64_t, 8> Words(Vals.size());
1158 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1159 BitcodeReader::decodeSignRotatedValue);
1161 return APInt(TypeBits, Words);
1164 error_code BitcodeReader::ParseConstants() {
1165 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1166 return Error(InvalidRecord);
1168 SmallVector<uint64_t, 64> Record;
1170 // Read all the records for this value table.
1171 Type *CurTy = Type::getInt32Ty(Context);
1172 unsigned NextCstNo = ValueList.size();
1174 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1176 switch (Entry.Kind) {
1177 case BitstreamEntry::SubBlock: // Handled for us already.
1178 case BitstreamEntry::Error:
1179 return Error(MalformedBlock);
1180 case BitstreamEntry::EndBlock:
1181 if (NextCstNo != ValueList.size())
1182 return Error(InvalidConstantReference);
1184 // Once all the constants have been read, go through and resolve forward
1186 ValueList.ResolveConstantForwardRefs();
1187 return error_code::success();
1188 case BitstreamEntry::Record:
1189 // The interesting case.
1196 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1198 default: // Default behavior: unknown constant
1199 case bitc::CST_CODE_UNDEF: // UNDEF
1200 V = UndefValue::get(CurTy);
1202 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1204 return Error(InvalidRecord);
1205 if (Record[0] >= TypeList.size())
1206 return Error(InvalidRecord);
1207 CurTy = TypeList[Record[0]];
1208 continue; // Skip the ValueList manipulation.
1209 case bitc::CST_CODE_NULL: // NULL
1210 V = Constant::getNullValue(CurTy);
1212 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1213 if (!CurTy->isIntegerTy() || Record.empty())
1214 return Error(InvalidRecord);
1215 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1217 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1218 if (!CurTy->isIntegerTy() || Record.empty())
1219 return Error(InvalidRecord);
1221 APInt VInt = ReadWideAPInt(Record,
1222 cast<IntegerType>(CurTy)->getBitWidth());
1223 V = ConstantInt::get(Context, VInt);
1227 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1229 return Error(InvalidRecord);
1230 if (CurTy->isHalfTy())
1231 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1232 APInt(16, (uint16_t)Record[0])));
1233 else if (CurTy->isFloatTy())
1234 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1235 APInt(32, (uint32_t)Record[0])));
1236 else if (CurTy->isDoubleTy())
1237 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1238 APInt(64, Record[0])));
1239 else if (CurTy->isX86_FP80Ty()) {
1240 // Bits are not stored the same way as a normal i80 APInt, compensate.
1241 uint64_t Rearrange[2];
1242 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1243 Rearrange[1] = Record[0] >> 48;
1244 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1245 APInt(80, Rearrange)));
1246 } else if (CurTy->isFP128Ty())
1247 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1248 APInt(128, Record)));
1249 else if (CurTy->isPPC_FP128Ty())
1250 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1251 APInt(128, Record)));
1253 V = UndefValue::get(CurTy);
1257 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1259 return Error(InvalidRecord);
1261 unsigned Size = Record.size();
1262 SmallVector<Constant*, 16> Elts;
1264 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1265 for (unsigned i = 0; i != Size; ++i)
1266 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1267 STy->getElementType(i)));
1268 V = ConstantStruct::get(STy, Elts);
1269 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1270 Type *EltTy = ATy->getElementType();
1271 for (unsigned i = 0; i != Size; ++i)
1272 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1273 V = ConstantArray::get(ATy, Elts);
1274 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1275 Type *EltTy = VTy->getElementType();
1276 for (unsigned i = 0; i != Size; ++i)
1277 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1278 V = ConstantVector::get(Elts);
1280 V = UndefValue::get(CurTy);
1284 case bitc::CST_CODE_STRING: // STRING: [values]
1285 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1287 return Error(InvalidRecord);
1289 SmallString<16> Elts(Record.begin(), Record.end());
1290 V = ConstantDataArray::getString(Context, Elts,
1291 BitCode == bitc::CST_CODE_CSTRING);
1294 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1296 return Error(InvalidRecord);
1298 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1299 unsigned Size = Record.size();
1301 if (EltTy->isIntegerTy(8)) {
1302 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1303 if (isa<VectorType>(CurTy))
1304 V = ConstantDataVector::get(Context, Elts);
1306 V = ConstantDataArray::get(Context, Elts);
1307 } else if (EltTy->isIntegerTy(16)) {
1308 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1309 if (isa<VectorType>(CurTy))
1310 V = ConstantDataVector::get(Context, Elts);
1312 V = ConstantDataArray::get(Context, Elts);
1313 } else if (EltTy->isIntegerTy(32)) {
1314 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1315 if (isa<VectorType>(CurTy))
1316 V = ConstantDataVector::get(Context, Elts);
1318 V = ConstantDataArray::get(Context, Elts);
1319 } else if (EltTy->isIntegerTy(64)) {
1320 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1321 if (isa<VectorType>(CurTy))
1322 V = ConstantDataVector::get(Context, Elts);
1324 V = ConstantDataArray::get(Context, Elts);
1325 } else if (EltTy->isFloatTy()) {
1326 SmallVector<float, 16> Elts(Size);
1327 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1328 if (isa<VectorType>(CurTy))
1329 V = ConstantDataVector::get(Context, Elts);
1331 V = ConstantDataArray::get(Context, Elts);
1332 } else if (EltTy->isDoubleTy()) {
1333 SmallVector<double, 16> Elts(Size);
1334 std::transform(Record.begin(), Record.end(), Elts.begin(),
1336 if (isa<VectorType>(CurTy))
1337 V = ConstantDataVector::get(Context, Elts);
1339 V = ConstantDataArray::get(Context, Elts);
1341 return Error(InvalidTypeForValue);
1346 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1347 if (Record.size() < 3)
1348 return Error(InvalidRecord);
1349 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1351 V = UndefValue::get(CurTy); // Unknown binop.
1353 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1354 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1356 if (Record.size() >= 4) {
1357 if (Opc == Instruction::Add ||
1358 Opc == Instruction::Sub ||
1359 Opc == Instruction::Mul ||
1360 Opc == Instruction::Shl) {
1361 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1362 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1363 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1364 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1365 } else if (Opc == Instruction::SDiv ||
1366 Opc == Instruction::UDiv ||
1367 Opc == Instruction::LShr ||
1368 Opc == Instruction::AShr) {
1369 if (Record[3] & (1 << bitc::PEO_EXACT))
1370 Flags |= SDivOperator::IsExact;
1373 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1377 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1378 if (Record.size() < 3)
1379 return Error(InvalidRecord);
1380 int Opc = GetDecodedCastOpcode(Record[0]);
1382 V = UndefValue::get(CurTy); // Unknown cast.
1384 Type *OpTy = getTypeByID(Record[1]);
1386 return Error(InvalidRecord);
1387 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1388 V = ConstantExpr::getCast(Opc, Op, CurTy);
1392 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1393 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1394 if (Record.size() & 1)
1395 return Error(InvalidRecord);
1396 SmallVector<Constant*, 16> Elts;
1397 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1398 Type *ElTy = getTypeByID(Record[i]);
1400 return Error(InvalidRecord);
1401 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1403 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1404 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1406 bitc::CST_CODE_CE_INBOUNDS_GEP);
1409 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1410 if (Record.size() < 3)
1411 return Error(InvalidRecord);
1413 Type *SelectorTy = Type::getInt1Ty(Context);
1415 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1416 // vector. Otherwise, it must be a single bit.
1417 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1418 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1419 VTy->getNumElements());
1421 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1423 ValueList.getConstantFwdRef(Record[1],CurTy),
1424 ValueList.getConstantFwdRef(Record[2],CurTy));
1427 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1428 if (Record.size() < 3)
1429 return Error(InvalidRecord);
1431 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1433 return Error(InvalidRecord);
1434 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1435 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1436 Type::getInt32Ty(Context));
1437 V = ConstantExpr::getExtractElement(Op0, Op1);
1440 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1441 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1442 if (Record.size() < 3 || OpTy == 0)
1443 return Error(InvalidRecord);
1444 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1445 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1446 OpTy->getElementType());
1447 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1448 Type::getInt32Ty(Context));
1449 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1452 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1453 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1454 if (Record.size() < 3 || OpTy == 0)
1455 return Error(InvalidRecord);
1456 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1457 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1458 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1459 OpTy->getNumElements());
1460 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1461 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1464 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1465 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1467 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1468 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1469 return Error(InvalidRecord);
1470 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1471 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1472 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1473 RTy->getNumElements());
1474 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1475 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1478 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1479 if (Record.size() < 4)
1480 return Error(InvalidRecord);
1481 Type *OpTy = getTypeByID(Record[0]);
1483 return Error(InvalidRecord);
1484 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1485 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1487 if (OpTy->isFPOrFPVectorTy())
1488 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1490 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1493 // This maintains backward compatibility, pre-asm dialect keywords.
1494 // FIXME: Remove with the 4.0 release.
1495 case bitc::CST_CODE_INLINEASM_OLD: {
1496 if (Record.size() < 2)
1497 return Error(InvalidRecord);
1498 std::string AsmStr, ConstrStr;
1499 bool HasSideEffects = Record[0] & 1;
1500 bool IsAlignStack = Record[0] >> 1;
1501 unsigned AsmStrSize = Record[1];
1502 if (2+AsmStrSize >= Record.size())
1503 return Error(InvalidRecord);
1504 unsigned ConstStrSize = Record[2+AsmStrSize];
1505 if (3+AsmStrSize+ConstStrSize > Record.size())
1506 return Error(InvalidRecord);
1508 for (unsigned i = 0; i != AsmStrSize; ++i)
1509 AsmStr += (char)Record[2+i];
1510 for (unsigned i = 0; i != ConstStrSize; ++i)
1511 ConstrStr += (char)Record[3+AsmStrSize+i];
1512 PointerType *PTy = cast<PointerType>(CurTy);
1513 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1514 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1517 // This version adds support for the asm dialect keywords (e.g.,
1519 case bitc::CST_CODE_INLINEASM: {
1520 if (Record.size() < 2)
1521 return Error(InvalidRecord);
1522 std::string AsmStr, ConstrStr;
1523 bool HasSideEffects = Record[0] & 1;
1524 bool IsAlignStack = (Record[0] >> 1) & 1;
1525 unsigned AsmDialect = Record[0] >> 2;
1526 unsigned AsmStrSize = Record[1];
1527 if (2+AsmStrSize >= Record.size())
1528 return Error(InvalidRecord);
1529 unsigned ConstStrSize = Record[2+AsmStrSize];
1530 if (3+AsmStrSize+ConstStrSize > Record.size())
1531 return Error(InvalidRecord);
1533 for (unsigned i = 0; i != AsmStrSize; ++i)
1534 AsmStr += (char)Record[2+i];
1535 for (unsigned i = 0; i != ConstStrSize; ++i)
1536 ConstrStr += (char)Record[3+AsmStrSize+i];
1537 PointerType *PTy = cast<PointerType>(CurTy);
1538 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1539 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1540 InlineAsm::AsmDialect(AsmDialect));
1543 case bitc::CST_CODE_BLOCKADDRESS:{
1544 if (Record.size() < 3)
1545 return Error(InvalidRecord);
1546 Type *FnTy = getTypeByID(Record[0]);
1548 return Error(InvalidRecord);
1550 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1552 return Error(InvalidRecord);
1554 // If the function is already parsed we can insert the block address right
1557 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1558 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1560 return Error(InvalidID);
1563 V = BlockAddress::get(Fn, BBI);
1565 // Otherwise insert a placeholder and remember it so it can be inserted
1566 // when the function is parsed.
1567 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1568 Type::getInt8Ty(Context),
1569 false, GlobalValue::InternalLinkage,
1571 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1578 ValueList.AssignValue(V, NextCstNo);
1583 error_code BitcodeReader::ParseUseLists() {
1584 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1585 return Error(InvalidRecord);
1587 SmallVector<uint64_t, 64> Record;
1589 // Read all the records.
1591 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1593 switch (Entry.Kind) {
1594 case BitstreamEntry::SubBlock: // Handled for us already.
1595 case BitstreamEntry::Error:
1596 return Error(MalformedBlock);
1597 case BitstreamEntry::EndBlock:
1598 return error_code::success();
1599 case BitstreamEntry::Record:
1600 // The interesting case.
1604 // Read a use list record.
1606 switch (Stream.readRecord(Entry.ID, Record)) {
1607 default: // Default behavior: unknown type.
1609 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1610 unsigned RecordLength = Record.size();
1611 if (RecordLength < 1)
1612 return Error(InvalidRecord);
1613 UseListRecords.push_back(Record);
1620 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1621 /// remember where it is and then skip it. This lets us lazily deserialize the
1623 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1624 // Get the function we are talking about.
1625 if (FunctionsWithBodies.empty())
1626 return Error(InsufficientFunctionProtos);
1628 Function *Fn = FunctionsWithBodies.back();
1629 FunctionsWithBodies.pop_back();
1631 // Save the current stream state.
1632 uint64_t CurBit = Stream.GetCurrentBitNo();
1633 DeferredFunctionInfo[Fn] = CurBit;
1635 // Skip over the function block for now.
1636 if (Stream.SkipBlock())
1637 return Error(InvalidRecord);
1638 return error_code::success();
1641 error_code BitcodeReader::GlobalCleanup() {
1642 // Patch the initializers for globals and aliases up.
1643 ResolveGlobalAndAliasInits();
1644 if (!GlobalInits.empty() || !AliasInits.empty())
1645 return Error(MalformedGlobalInitializerSet);
1647 // Look for intrinsic functions which need to be upgraded at some point
1648 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1651 if (UpgradeIntrinsicFunction(FI, NewFn))
1652 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1655 // Look for global variables which need to be renamed.
1656 for (Module::global_iterator
1657 GI = TheModule->global_begin(), GE = TheModule->global_end();
1659 UpgradeGlobalVariable(GI);
1660 // Force deallocation of memory for these vectors to favor the client that
1661 // want lazy deserialization.
1662 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1663 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1664 return error_code::success();
1667 error_code BitcodeReader::ParseModule(bool Resume) {
1669 Stream.JumpToBit(NextUnreadBit);
1670 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1671 return Error(InvalidRecord);
1673 SmallVector<uint64_t, 64> Record;
1674 std::vector<std::string> SectionTable;
1675 std::vector<std::string> GCTable;
1677 // Read all the records for this module.
1679 BitstreamEntry Entry = Stream.advance();
1681 switch (Entry.Kind) {
1682 case BitstreamEntry::Error:
1683 return Error(MalformedBlock);
1684 case BitstreamEntry::EndBlock:
1685 return GlobalCleanup();
1687 case BitstreamEntry::SubBlock:
1689 default: // Skip unknown content.
1690 if (Stream.SkipBlock())
1691 return Error(InvalidRecord);
1693 case bitc::BLOCKINFO_BLOCK_ID:
1694 if (Stream.ReadBlockInfoBlock())
1695 return Error(MalformedBlock);
1697 case bitc::PARAMATTR_BLOCK_ID:
1698 if (error_code EC = ParseAttributeBlock())
1701 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1702 if (error_code EC = ParseAttributeGroupBlock())
1705 case bitc::TYPE_BLOCK_ID_NEW:
1706 if (error_code EC = ParseTypeTable())
1709 case bitc::VALUE_SYMTAB_BLOCK_ID:
1710 if (error_code EC = ParseValueSymbolTable())
1712 SeenValueSymbolTable = true;
1714 case bitc::CONSTANTS_BLOCK_ID:
1715 if (error_code EC = ParseConstants())
1717 if (error_code EC = ResolveGlobalAndAliasInits())
1720 case bitc::METADATA_BLOCK_ID:
1721 if (error_code EC = ParseMetadata())
1724 case bitc::FUNCTION_BLOCK_ID:
1725 // If this is the first function body we've seen, reverse the
1726 // FunctionsWithBodies list.
1727 if (!SeenFirstFunctionBody) {
1728 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1729 if (error_code EC = GlobalCleanup())
1731 SeenFirstFunctionBody = true;
1734 if (error_code EC = RememberAndSkipFunctionBody())
1736 // For streaming bitcode, suspend parsing when we reach the function
1737 // bodies. Subsequent materialization calls will resume it when
1738 // necessary. For streaming, the function bodies must be at the end of
1739 // the bitcode. If the bitcode file is old, the symbol table will be
1740 // at the end instead and will not have been seen yet. In this case,
1741 // just finish the parse now.
1742 if (LazyStreamer && SeenValueSymbolTable) {
1743 NextUnreadBit = Stream.GetCurrentBitNo();
1744 return error_code::success();
1747 case bitc::USELIST_BLOCK_ID:
1748 if (error_code EC = ParseUseLists())
1754 case BitstreamEntry::Record:
1755 // The interesting case.
1761 switch (Stream.readRecord(Entry.ID, Record)) {
1762 default: break; // Default behavior, ignore unknown content.
1763 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1764 if (Record.size() < 1)
1765 return Error(InvalidRecord);
1766 // Only version #0 and #1 are supported so far.
1767 unsigned module_version = Record[0];
1768 switch (module_version) {
1770 return Error(InvalidValue);
1772 UseRelativeIDs = false;
1775 UseRelativeIDs = true;
1780 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1782 if (ConvertToString(Record, 0, S))
1783 return Error(InvalidRecord);
1784 TheModule->setTargetTriple(S);
1787 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1789 if (ConvertToString(Record, 0, S))
1790 return Error(InvalidRecord);
1791 TheModule->setDataLayout(S);
1794 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1796 if (ConvertToString(Record, 0, S))
1797 return Error(InvalidRecord);
1798 TheModule->setModuleInlineAsm(S);
1801 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1802 // FIXME: Remove in 4.0.
1804 if (ConvertToString(Record, 0, S))
1805 return Error(InvalidRecord);
1809 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1811 if (ConvertToString(Record, 0, S))
1812 return Error(InvalidRecord);
1813 SectionTable.push_back(S);
1816 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1818 if (ConvertToString(Record, 0, S))
1819 return Error(InvalidRecord);
1820 GCTable.push_back(S);
1823 // GLOBALVAR: [pointer type, isconst, initid,
1824 // linkage, alignment, section, visibility, threadlocal,
1826 case bitc::MODULE_CODE_GLOBALVAR: {
1827 if (Record.size() < 6)
1828 return Error(InvalidRecord);
1829 Type *Ty = getTypeByID(Record[0]);
1831 return Error(InvalidRecord);
1832 if (!Ty->isPointerTy())
1833 return Error(InvalidTypeForValue);
1834 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1835 Ty = cast<PointerType>(Ty)->getElementType();
1837 bool isConstant = Record[1];
1838 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1839 unsigned Alignment = (1 << Record[4]) >> 1;
1840 std::string Section;
1842 if (Record[5]-1 >= SectionTable.size())
1843 return Error(InvalidID);
1844 Section = SectionTable[Record[5]-1];
1846 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1847 if (Record.size() > 6)
1848 Visibility = GetDecodedVisibility(Record[6]);
1850 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1851 if (Record.size() > 7)
1852 TLM = GetDecodedThreadLocalMode(Record[7]);
1854 bool UnnamedAddr = false;
1855 if (Record.size() > 8)
1856 UnnamedAddr = Record[8];
1858 bool ExternallyInitialized = false;
1859 if (Record.size() > 9)
1860 ExternallyInitialized = Record[9];
1862 GlobalVariable *NewGV =
1863 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1864 TLM, AddressSpace, ExternallyInitialized);
1865 NewGV->setAlignment(Alignment);
1866 if (!Section.empty())
1867 NewGV->setSection(Section);
1868 NewGV->setVisibility(Visibility);
1869 NewGV->setUnnamedAddr(UnnamedAddr);
1871 ValueList.push_back(NewGV);
1873 // Remember which value to use for the global initializer.
1874 if (unsigned InitID = Record[2])
1875 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1878 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1879 // alignment, section, visibility, gc, unnamed_addr]
1880 case bitc::MODULE_CODE_FUNCTION: {
1881 if (Record.size() < 8)
1882 return Error(InvalidRecord);
1883 Type *Ty = getTypeByID(Record[0]);
1885 return Error(InvalidRecord);
1886 if (!Ty->isPointerTy())
1887 return Error(InvalidTypeForValue);
1889 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1891 return Error(InvalidTypeForValue);
1893 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1896 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1897 bool isProto = Record[2];
1898 Func->setLinkage(GetDecodedLinkage(Record[3]));
1899 Func->setAttributes(getAttributes(Record[4]));
1901 Func->setAlignment((1 << Record[5]) >> 1);
1903 if (Record[6]-1 >= SectionTable.size())
1904 return Error(InvalidID);
1905 Func->setSection(SectionTable[Record[6]-1]);
1907 Func->setVisibility(GetDecodedVisibility(Record[7]));
1908 if (Record.size() > 8 && Record[8]) {
1909 if (Record[8]-1 > GCTable.size())
1910 return Error(InvalidID);
1911 Func->setGC(GCTable[Record[8]-1].c_str());
1913 bool UnnamedAddr = false;
1914 if (Record.size() > 9)
1915 UnnamedAddr = Record[9];
1916 Func->setUnnamedAddr(UnnamedAddr);
1917 if (Record.size() > 10 && Record[10] != 0)
1918 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1919 ValueList.push_back(Func);
1921 // If this is a function with a body, remember the prototype we are
1922 // creating now, so that we can match up the body with them later.
1924 FunctionsWithBodies.push_back(Func);
1925 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1929 // ALIAS: [alias type, aliasee val#, linkage]
1930 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1931 case bitc::MODULE_CODE_ALIAS: {
1932 if (Record.size() < 3)
1933 return Error(InvalidRecord);
1934 Type *Ty = getTypeByID(Record[0]);
1936 return Error(InvalidRecord);
1937 if (!Ty->isPointerTy())
1938 return Error(InvalidTypeForValue);
1940 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1942 // Old bitcode files didn't have visibility field.
1943 if (Record.size() > 3)
1944 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1945 ValueList.push_back(NewGA);
1946 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1949 /// MODULE_CODE_PURGEVALS: [numvals]
1950 case bitc::MODULE_CODE_PURGEVALS:
1951 // Trim down the value list to the specified size.
1952 if (Record.size() < 1 || Record[0] > ValueList.size())
1953 return Error(InvalidRecord);
1954 ValueList.shrinkTo(Record[0]);
1961 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
1964 if (error_code EC = InitStream())
1967 // Sniff for the signature.
1968 if (Stream.Read(8) != 'B' ||
1969 Stream.Read(8) != 'C' ||
1970 Stream.Read(4) != 0x0 ||
1971 Stream.Read(4) != 0xC ||
1972 Stream.Read(4) != 0xE ||
1973 Stream.Read(4) != 0xD)
1974 return Error(InvalidBitcodeSignature);
1976 // We expect a number of well-defined blocks, though we don't necessarily
1977 // need to understand them all.
1979 if (Stream.AtEndOfStream())
1980 return error_code::success();
1982 BitstreamEntry Entry =
1983 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1985 switch (Entry.Kind) {
1986 case BitstreamEntry::Error:
1987 return Error(MalformedBlock);
1988 case BitstreamEntry::EndBlock:
1989 return error_code::success();
1991 case BitstreamEntry::SubBlock:
1993 case bitc::BLOCKINFO_BLOCK_ID:
1994 if (Stream.ReadBlockInfoBlock())
1995 return Error(MalformedBlock);
1997 case bitc::MODULE_BLOCK_ID:
1998 // Reject multiple MODULE_BLOCK's in a single bitstream.
2000 return Error(InvalidMultipleBlocks);
2002 if (error_code EC = ParseModule(false))
2005 return error_code::success();
2008 if (Stream.SkipBlock())
2009 return Error(InvalidRecord);
2013 case BitstreamEntry::Record:
2014 // There should be no records in the top-level of blocks.
2016 // The ranlib in Xcode 4 will align archive members by appending newlines
2017 // to the end of them. If this file size is a multiple of 4 but not 8, we
2018 // have to read and ignore these final 4 bytes :-(
2019 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2020 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2021 Stream.AtEndOfStream())
2022 return error_code::success();
2024 return Error(InvalidRecord);
2029 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2030 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2031 return Error(InvalidRecord);
2033 SmallVector<uint64_t, 64> Record;
2035 // Read all the records for this module.
2037 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2039 switch (Entry.Kind) {
2040 case BitstreamEntry::SubBlock: // Handled for us already.
2041 case BitstreamEntry::Error:
2042 return Error(MalformedBlock);
2043 case BitstreamEntry::EndBlock:
2044 return error_code::success();
2045 case BitstreamEntry::Record:
2046 // The interesting case.
2051 switch (Stream.readRecord(Entry.ID, Record)) {
2052 default: break; // Default behavior, ignore unknown content.
2053 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2055 if (ConvertToString(Record, 0, S))
2056 return Error(InvalidRecord);
2065 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2066 if (error_code EC = InitStream())
2069 // Sniff for the signature.
2070 if (Stream.Read(8) != 'B' ||
2071 Stream.Read(8) != 'C' ||
2072 Stream.Read(4) != 0x0 ||
2073 Stream.Read(4) != 0xC ||
2074 Stream.Read(4) != 0xE ||
2075 Stream.Read(4) != 0xD)
2076 return Error(InvalidBitcodeSignature);
2078 // We expect a number of well-defined blocks, though we don't necessarily
2079 // need to understand them all.
2081 BitstreamEntry Entry = Stream.advance();
2083 switch (Entry.Kind) {
2084 case BitstreamEntry::Error:
2085 return Error(MalformedBlock);
2086 case BitstreamEntry::EndBlock:
2087 return error_code::success();
2089 case BitstreamEntry::SubBlock:
2090 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2091 return ParseModuleTriple(Triple);
2093 // Ignore other sub-blocks.
2094 if (Stream.SkipBlock())
2095 return Error(MalformedBlock);
2098 case BitstreamEntry::Record:
2099 Stream.skipRecord(Entry.ID);
2105 /// ParseMetadataAttachment - Parse metadata attachments.
2106 error_code BitcodeReader::ParseMetadataAttachment() {
2107 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2108 return Error(InvalidRecord);
2110 SmallVector<uint64_t, 64> Record;
2112 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2114 switch (Entry.Kind) {
2115 case BitstreamEntry::SubBlock: // Handled for us already.
2116 case BitstreamEntry::Error:
2117 return Error(MalformedBlock);
2118 case BitstreamEntry::EndBlock:
2119 return error_code::success();
2120 case BitstreamEntry::Record:
2121 // The interesting case.
2125 // Read a metadata attachment record.
2127 switch (Stream.readRecord(Entry.ID, Record)) {
2128 default: // Default behavior: ignore.
2130 case bitc::METADATA_ATTACHMENT: {
2131 unsigned RecordLength = Record.size();
2132 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2133 return Error(InvalidRecord);
2134 Instruction *Inst = InstructionList[Record[0]];
2135 for (unsigned i = 1; i != RecordLength; i = i+2) {
2136 unsigned Kind = Record[i];
2137 DenseMap<unsigned, unsigned>::iterator I =
2138 MDKindMap.find(Kind);
2139 if (I == MDKindMap.end())
2140 return Error(InvalidID);
2141 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2142 Inst->setMetadata(I->second, cast<MDNode>(Node));
2143 if (I->second == LLVMContext::MD_tbaa)
2144 InstsWithTBAATag.push_back(Inst);
2152 /// ParseFunctionBody - Lazily parse the specified function body block.
2153 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2154 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2155 return Error(InvalidRecord);
2157 InstructionList.clear();
2158 unsigned ModuleValueListSize = ValueList.size();
2159 unsigned ModuleMDValueListSize = MDValueList.size();
2161 // Add all the function arguments to the value table.
2162 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2163 ValueList.push_back(I);
2165 unsigned NextValueNo = ValueList.size();
2166 BasicBlock *CurBB = 0;
2167 unsigned CurBBNo = 0;
2171 // Read all the records.
2172 SmallVector<uint64_t, 64> Record;
2174 BitstreamEntry Entry = Stream.advance();
2176 switch (Entry.Kind) {
2177 case BitstreamEntry::Error:
2178 return Error(MalformedBlock);
2179 case BitstreamEntry::EndBlock:
2180 goto OutOfRecordLoop;
2182 case BitstreamEntry::SubBlock:
2184 default: // Skip unknown content.
2185 if (Stream.SkipBlock())
2186 return Error(InvalidRecord);
2188 case bitc::CONSTANTS_BLOCK_ID:
2189 if (error_code EC = ParseConstants())
2191 NextValueNo = ValueList.size();
2193 case bitc::VALUE_SYMTAB_BLOCK_ID:
2194 if (error_code EC = ParseValueSymbolTable())
2197 case bitc::METADATA_ATTACHMENT_ID:
2198 if (error_code EC = ParseMetadataAttachment())
2201 case bitc::METADATA_BLOCK_ID:
2202 if (error_code EC = ParseMetadata())
2208 case BitstreamEntry::Record:
2209 // The interesting case.
2216 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2218 default: // Default behavior: reject
2219 return Error(InvalidValue);
2220 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2221 if (Record.size() < 1 || Record[0] == 0)
2222 return Error(InvalidRecord);
2223 // Create all the basic blocks for the function.
2224 FunctionBBs.resize(Record[0]);
2225 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2226 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2227 CurBB = FunctionBBs[0];
2230 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2231 // This record indicates that the last instruction is at the same
2232 // location as the previous instruction with a location.
2235 // Get the last instruction emitted.
2236 if (CurBB && !CurBB->empty())
2238 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2239 !FunctionBBs[CurBBNo-1]->empty())
2240 I = &FunctionBBs[CurBBNo-1]->back();
2243 return Error(InvalidRecord);
2244 I->setDebugLoc(LastLoc);
2248 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2249 I = 0; // Get the last instruction emitted.
2250 if (CurBB && !CurBB->empty())
2252 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2253 !FunctionBBs[CurBBNo-1]->empty())
2254 I = &FunctionBBs[CurBBNo-1]->back();
2255 if (I == 0 || Record.size() < 4)
2256 return Error(InvalidRecord);
2258 unsigned Line = Record[0], Col = Record[1];
2259 unsigned ScopeID = Record[2], IAID = Record[3];
2261 MDNode *Scope = 0, *IA = 0;
2262 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2263 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2264 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2265 I->setDebugLoc(LastLoc);
2270 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2273 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2274 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2275 OpNum+1 > Record.size())
2276 return Error(InvalidRecord);
2278 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2280 return Error(InvalidRecord);
2281 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2282 InstructionList.push_back(I);
2283 if (OpNum < Record.size()) {
2284 if (Opc == Instruction::Add ||
2285 Opc == Instruction::Sub ||
2286 Opc == Instruction::Mul ||
2287 Opc == Instruction::Shl) {
2288 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2289 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2290 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2291 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2292 } else if (Opc == Instruction::SDiv ||
2293 Opc == Instruction::UDiv ||
2294 Opc == Instruction::LShr ||
2295 Opc == Instruction::AShr) {
2296 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2297 cast<BinaryOperator>(I)->setIsExact(true);
2298 } else if (isa<FPMathOperator>(I)) {
2300 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2301 FMF.setUnsafeAlgebra();
2302 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2304 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2306 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2307 FMF.setNoSignedZeros();
2308 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2309 FMF.setAllowReciprocal();
2311 I->setFastMathFlags(FMF);
2317 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2320 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2321 OpNum+2 != Record.size())
2322 return Error(InvalidRecord);
2324 Type *ResTy = getTypeByID(Record[OpNum]);
2325 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2326 if (Opc == -1 || ResTy == 0)
2327 return Error(InvalidRecord);
2328 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2329 InstructionList.push_back(I);
2332 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2333 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2336 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2337 return Error(InvalidRecord);
2339 SmallVector<Value*, 16> GEPIdx;
2340 while (OpNum != Record.size()) {
2342 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2343 return Error(InvalidRecord);
2344 GEPIdx.push_back(Op);
2347 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2348 InstructionList.push_back(I);
2349 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2350 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2354 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2355 // EXTRACTVAL: [opty, opval, n x indices]
2358 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2359 return Error(InvalidRecord);
2361 SmallVector<unsigned, 4> EXTRACTVALIdx;
2362 for (unsigned RecSize = Record.size();
2363 OpNum != RecSize; ++OpNum) {
2364 uint64_t Index = Record[OpNum];
2365 if ((unsigned)Index != Index)
2366 return Error(InvalidValue);
2367 EXTRACTVALIdx.push_back((unsigned)Index);
2370 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2371 InstructionList.push_back(I);
2375 case bitc::FUNC_CODE_INST_INSERTVAL: {
2376 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2379 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2380 return Error(InvalidRecord);
2382 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2383 return Error(InvalidRecord);
2385 SmallVector<unsigned, 4> INSERTVALIdx;
2386 for (unsigned RecSize = Record.size();
2387 OpNum != RecSize; ++OpNum) {
2388 uint64_t Index = Record[OpNum];
2389 if ((unsigned)Index != Index)
2390 return Error(InvalidValue);
2391 INSERTVALIdx.push_back((unsigned)Index);
2394 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2395 InstructionList.push_back(I);
2399 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2400 // obsolete form of select
2401 // handles select i1 ... in old bitcode
2403 Value *TrueVal, *FalseVal, *Cond;
2404 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2405 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2406 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2407 return Error(InvalidRecord);
2409 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2410 InstructionList.push_back(I);
2414 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2415 // new form of select
2416 // handles select i1 or select [N x i1]
2418 Value *TrueVal, *FalseVal, *Cond;
2419 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2420 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2421 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2422 return Error(InvalidRecord);
2424 // select condition can be either i1 or [N x i1]
2425 if (VectorType* vector_type =
2426 dyn_cast<VectorType>(Cond->getType())) {
2428 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2429 return Error(InvalidTypeForValue);
2432 if (Cond->getType() != Type::getInt1Ty(Context))
2433 return Error(InvalidTypeForValue);
2436 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2437 InstructionList.push_back(I);
2441 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2444 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2445 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2446 return Error(InvalidRecord);
2447 I = ExtractElementInst::Create(Vec, Idx);
2448 InstructionList.push_back(I);
2452 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2454 Value *Vec, *Elt, *Idx;
2455 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2456 popValue(Record, OpNum, NextValueNo,
2457 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2458 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2459 return Error(InvalidRecord);
2460 I = InsertElementInst::Create(Vec, Elt, Idx);
2461 InstructionList.push_back(I);
2465 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2467 Value *Vec1, *Vec2, *Mask;
2468 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2469 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2470 return Error(InvalidRecord);
2472 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2473 return Error(InvalidRecord);
2474 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2475 InstructionList.push_back(I);
2479 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2480 // Old form of ICmp/FCmp returning bool
2481 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2482 // both legal on vectors but had different behaviour.
2483 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2484 // FCmp/ICmp returning bool or vector of bool
2488 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2489 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2490 OpNum+1 != Record.size())
2491 return Error(InvalidRecord);
2493 if (LHS->getType()->isFPOrFPVectorTy())
2494 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2496 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2497 InstructionList.push_back(I);
2501 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2503 unsigned Size = Record.size();
2505 I = ReturnInst::Create(Context);
2506 InstructionList.push_back(I);
2512 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2513 return Error(InvalidRecord);
2514 if (OpNum != Record.size())
2515 return Error(InvalidRecord);
2517 I = ReturnInst::Create(Context, Op);
2518 InstructionList.push_back(I);
2521 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2522 if (Record.size() != 1 && Record.size() != 3)
2523 return Error(InvalidRecord);
2524 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2526 return Error(InvalidRecord);
2528 if (Record.size() == 1) {
2529 I = BranchInst::Create(TrueDest);
2530 InstructionList.push_back(I);
2533 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2534 Value *Cond = getValue(Record, 2, NextValueNo,
2535 Type::getInt1Ty(Context));
2536 if (FalseDest == 0 || Cond == 0)
2537 return Error(InvalidRecord);
2538 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2539 InstructionList.push_back(I);
2543 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2545 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2546 // "New" SwitchInst format with case ranges. The changes to write this
2547 // format were reverted but we still recognize bitcode that uses it.
2548 // Hopefully someday we will have support for case ranges and can use
2549 // this format again.
2551 Type *OpTy = getTypeByID(Record[1]);
2552 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2554 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2555 BasicBlock *Default = getBasicBlock(Record[3]);
2556 if (OpTy == 0 || Cond == 0 || Default == 0)
2557 return Error(InvalidRecord);
2559 unsigned NumCases = Record[4];
2561 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2562 InstructionList.push_back(SI);
2564 unsigned CurIdx = 5;
2565 for (unsigned i = 0; i != NumCases; ++i) {
2566 SmallVector<ConstantInt*, 1> CaseVals;
2567 unsigned NumItems = Record[CurIdx++];
2568 for (unsigned ci = 0; ci != NumItems; ++ci) {
2569 bool isSingleNumber = Record[CurIdx++];
2572 unsigned ActiveWords = 1;
2573 if (ValueBitWidth > 64)
2574 ActiveWords = Record[CurIdx++];
2575 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2577 CurIdx += ActiveWords;
2579 if (!isSingleNumber) {
2581 if (ValueBitWidth > 64)
2582 ActiveWords = Record[CurIdx++];
2584 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2586 CurIdx += ActiveWords;
2588 // FIXME: It is not clear whether values in the range should be
2589 // compared as signed or unsigned values. The partially
2590 // implemented changes that used this format in the past used
2591 // unsigned comparisons.
2592 for ( ; Low.ule(High); ++Low)
2593 CaseVals.push_back(ConstantInt::get(Context, Low));
2595 CaseVals.push_back(ConstantInt::get(Context, Low));
2597 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2598 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2599 cve = CaseVals.end(); cvi != cve; ++cvi)
2600 SI->addCase(*cvi, DestBB);
2606 // Old SwitchInst format without case ranges.
2608 if (Record.size() < 3 || (Record.size() & 1) == 0)
2609 return Error(InvalidRecord);
2610 Type *OpTy = getTypeByID(Record[0]);
2611 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2612 BasicBlock *Default = getBasicBlock(Record[2]);
2613 if (OpTy == 0 || Cond == 0 || Default == 0)
2614 return Error(InvalidRecord);
2615 unsigned NumCases = (Record.size()-3)/2;
2616 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2617 InstructionList.push_back(SI);
2618 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2619 ConstantInt *CaseVal =
2620 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2621 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2622 if (CaseVal == 0 || DestBB == 0) {
2624 return Error(InvalidRecord);
2626 SI->addCase(CaseVal, DestBB);
2631 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2632 if (Record.size() < 2)
2633 return Error(InvalidRecord);
2634 Type *OpTy = getTypeByID(Record[0]);
2635 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2636 if (OpTy == 0 || Address == 0)
2637 return Error(InvalidRecord);
2638 unsigned NumDests = Record.size()-2;
2639 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2640 InstructionList.push_back(IBI);
2641 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2642 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2643 IBI->addDestination(DestBB);
2646 return Error(InvalidRecord);
2653 case bitc::FUNC_CODE_INST_INVOKE: {
2654 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2655 if (Record.size() < 4)
2656 return Error(InvalidRecord);
2657 AttributeSet PAL = getAttributes(Record[0]);
2658 unsigned CCInfo = Record[1];
2659 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2660 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2664 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2665 return Error(InvalidRecord);
2667 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2668 FunctionType *FTy = !CalleeTy ? 0 :
2669 dyn_cast<FunctionType>(CalleeTy->getElementType());
2671 // Check that the right number of fixed parameters are here.
2672 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2673 Record.size() < OpNum+FTy->getNumParams())
2674 return Error(InvalidRecord);
2676 SmallVector<Value*, 16> Ops;
2677 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2678 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2679 FTy->getParamType(i)));
2680 if (Ops.back() == 0)
2681 return Error(InvalidRecord);
2684 if (!FTy->isVarArg()) {
2685 if (Record.size() != OpNum)
2686 return Error(InvalidRecord);
2688 // Read type/value pairs for varargs params.
2689 while (OpNum != Record.size()) {
2691 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2692 return Error(InvalidRecord);
2697 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2698 InstructionList.push_back(I);
2699 cast<InvokeInst>(I)->setCallingConv(
2700 static_cast<CallingConv::ID>(CCInfo));
2701 cast<InvokeInst>(I)->setAttributes(PAL);
2704 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2707 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2708 return Error(InvalidRecord);
2709 I = ResumeInst::Create(Val);
2710 InstructionList.push_back(I);
2713 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2714 I = new UnreachableInst(Context);
2715 InstructionList.push_back(I);
2717 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2718 if (Record.size() < 1 || ((Record.size()-1)&1))
2719 return Error(InvalidRecord);
2720 Type *Ty = getTypeByID(Record[0]);
2722 return Error(InvalidRecord);
2724 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2725 InstructionList.push_back(PN);
2727 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2729 // With the new function encoding, it is possible that operands have
2730 // negative IDs (for forward references). Use a signed VBR
2731 // representation to keep the encoding small.
2733 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2735 V = getValue(Record, 1+i, NextValueNo, Ty);
2736 BasicBlock *BB = getBasicBlock(Record[2+i]);
2738 return Error(InvalidRecord);
2739 PN->addIncoming(V, BB);
2745 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2746 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2748 if (Record.size() < 4)
2749 return Error(InvalidRecord);
2750 Type *Ty = getTypeByID(Record[Idx++]);
2752 return Error(InvalidRecord);
2754 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2755 return Error(InvalidRecord);
2757 bool IsCleanup = !!Record[Idx++];
2758 unsigned NumClauses = Record[Idx++];
2759 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2760 LP->setCleanup(IsCleanup);
2761 for (unsigned J = 0; J != NumClauses; ++J) {
2762 LandingPadInst::ClauseType CT =
2763 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2766 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2768 return Error(InvalidRecord);
2771 assert((CT != LandingPadInst::Catch ||
2772 !isa<ArrayType>(Val->getType())) &&
2773 "Catch clause has a invalid type!");
2774 assert((CT != LandingPadInst::Filter ||
2775 isa<ArrayType>(Val->getType())) &&
2776 "Filter clause has invalid type!");
2781 InstructionList.push_back(I);
2785 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2786 if (Record.size() != 4)
2787 return Error(InvalidRecord);
2789 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2790 Type *OpTy = getTypeByID(Record[1]);
2791 Value *Size = getFnValueByID(Record[2], OpTy);
2792 unsigned Align = Record[3];
2794 return Error(InvalidRecord);
2795 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2796 InstructionList.push_back(I);
2799 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2802 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2803 OpNum+2 != Record.size())
2804 return Error(InvalidRecord);
2806 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2807 InstructionList.push_back(I);
2810 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2811 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2814 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2815 OpNum+4 != Record.size())
2816 return Error(InvalidRecord);
2819 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2820 if (Ordering == NotAtomic || Ordering == Release ||
2821 Ordering == AcquireRelease)
2822 return Error(InvalidRecord);
2823 if (Ordering != NotAtomic && Record[OpNum] == 0)
2824 return Error(InvalidRecord);
2825 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2827 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2828 Ordering, SynchScope);
2829 InstructionList.push_back(I);
2832 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2835 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2836 popValue(Record, OpNum, NextValueNo,
2837 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2838 OpNum+2 != Record.size())
2839 return Error(InvalidRecord);
2841 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2842 InstructionList.push_back(I);
2845 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2846 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2849 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2850 popValue(Record, OpNum, NextValueNo,
2851 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2852 OpNum+4 != Record.size())
2853 return Error(InvalidRecord);
2855 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2856 if (Ordering == NotAtomic || Ordering == Acquire ||
2857 Ordering == AcquireRelease)
2858 return Error(InvalidRecord);
2859 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2860 if (Ordering != NotAtomic && Record[OpNum] == 0)
2861 return Error(InvalidRecord);
2863 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2864 Ordering, SynchScope);
2865 InstructionList.push_back(I);
2868 case bitc::FUNC_CODE_INST_CMPXCHG: {
2869 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2871 Value *Ptr, *Cmp, *New;
2872 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2873 popValue(Record, OpNum, NextValueNo,
2874 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2875 popValue(Record, OpNum, NextValueNo,
2876 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2877 OpNum+3 != Record.size())
2878 return Error(InvalidRecord);
2879 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2880 if (Ordering == NotAtomic || Ordering == Unordered)
2881 return Error(InvalidRecord);
2882 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2883 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2884 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2885 InstructionList.push_back(I);
2888 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2889 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2892 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2893 popValue(Record, OpNum, NextValueNo,
2894 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2895 OpNum+4 != Record.size())
2896 return Error(InvalidRecord);
2897 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2898 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2899 Operation > AtomicRMWInst::LAST_BINOP)
2900 return Error(InvalidRecord);
2901 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2902 if (Ordering == NotAtomic || Ordering == Unordered)
2903 return Error(InvalidRecord);
2904 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2905 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2906 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2907 InstructionList.push_back(I);
2910 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2911 if (2 != Record.size())
2912 return Error(InvalidRecord);
2913 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2914 if (Ordering == NotAtomic || Ordering == Unordered ||
2915 Ordering == Monotonic)
2916 return Error(InvalidRecord);
2917 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2918 I = new FenceInst(Context, Ordering, SynchScope);
2919 InstructionList.push_back(I);
2922 case bitc::FUNC_CODE_INST_CALL: {
2923 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2924 if (Record.size() < 3)
2925 return Error(InvalidRecord);
2927 AttributeSet PAL = getAttributes(Record[0]);
2928 unsigned CCInfo = Record[1];
2932 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2933 return Error(InvalidRecord);
2935 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2936 FunctionType *FTy = 0;
2937 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2938 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2939 return Error(InvalidRecord);
2941 SmallVector<Value*, 16> Args;
2942 // Read the fixed params.
2943 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2944 if (FTy->getParamType(i)->isLabelTy())
2945 Args.push_back(getBasicBlock(Record[OpNum]));
2947 Args.push_back(getValue(Record, OpNum, NextValueNo,
2948 FTy->getParamType(i)));
2949 if (Args.back() == 0)
2950 return Error(InvalidRecord);
2953 // Read type/value pairs for varargs params.
2954 if (!FTy->isVarArg()) {
2955 if (OpNum != Record.size())
2956 return Error(InvalidRecord);
2958 while (OpNum != Record.size()) {
2960 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2961 return Error(InvalidRecord);
2966 I = CallInst::Create(Callee, Args);
2967 InstructionList.push_back(I);
2968 cast<CallInst>(I)->setCallingConv(
2969 static_cast<CallingConv::ID>(CCInfo>>1));
2970 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2971 cast<CallInst>(I)->setAttributes(PAL);
2974 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2975 if (Record.size() < 3)
2976 return Error(InvalidRecord);
2977 Type *OpTy = getTypeByID(Record[0]);
2978 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2979 Type *ResTy = getTypeByID(Record[2]);
2980 if (!OpTy || !Op || !ResTy)
2981 return Error(InvalidRecord);
2982 I = new VAArgInst(Op, ResTy);
2983 InstructionList.push_back(I);
2988 // Add instruction to end of current BB. If there is no current BB, reject
2992 return Error(InvalidInstructionWithNoBB);
2994 CurBB->getInstList().push_back(I);
2996 // If this was a terminator instruction, move to the next block.
2997 if (isa<TerminatorInst>(I)) {
2999 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
3002 // Non-void values get registered in the value table for future use.
3003 if (I && !I->getType()->isVoidTy())
3004 ValueList.AssignValue(I, NextValueNo++);
3009 // Check the function list for unresolved values.
3010 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3011 if (A->getParent() == 0) {
3012 // We found at least one unresolved value. Nuke them all to avoid leaks.
3013 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3014 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
3015 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3019 return Error(NeverResolvedValueFoundInFunction);
3023 // FIXME: Check for unresolved forward-declared metadata references
3024 // and clean up leaks.
3026 // See if anything took the address of blocks in this function. If so,
3027 // resolve them now.
3028 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3029 BlockAddrFwdRefs.find(F);
3030 if (BAFRI != BlockAddrFwdRefs.end()) {
3031 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3032 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3033 unsigned BlockIdx = RefList[i].first;
3034 if (BlockIdx >= FunctionBBs.size())
3035 return Error(InvalidID);
3037 GlobalVariable *FwdRef = RefList[i].second;
3038 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3039 FwdRef->eraseFromParent();
3042 BlockAddrFwdRefs.erase(BAFRI);
3045 // Trim the value list down to the size it was before we parsed this function.
3046 ValueList.shrinkTo(ModuleValueListSize);
3047 MDValueList.shrinkTo(ModuleMDValueListSize);
3048 std::vector<BasicBlock*>().swap(FunctionBBs);
3049 return error_code::success();
3052 /// Find the function body in the bitcode stream
3053 error_code BitcodeReader::FindFunctionInStream(Function *F,
3054 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3055 while (DeferredFunctionInfoIterator->second == 0) {
3056 if (Stream.AtEndOfStream())
3057 return Error(CouldNotFindFunctionInStream);
3058 // ParseModule will parse the next body in the stream and set its
3059 // position in the DeferredFunctionInfo map.
3060 if (error_code EC = ParseModule(true))
3063 return error_code::success();
3066 //===----------------------------------------------------------------------===//
3067 // GVMaterializer implementation
3068 //===----------------------------------------------------------------------===//
3071 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3072 if (const Function *F = dyn_cast<Function>(GV)) {
3073 return F->isDeclaration() &&
3074 DeferredFunctionInfo.count(const_cast<Function*>(F));
3079 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3080 Function *F = dyn_cast<Function>(GV);
3081 // If it's not a function or is already material, ignore the request.
3082 if (!F || !F->isMaterializable())
3083 return error_code::success();
3085 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3086 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3087 // If its position is recorded as 0, its body is somewhere in the stream
3088 // but we haven't seen it yet.
3089 if (DFII->second == 0 && LazyStreamer)
3090 if (error_code EC = FindFunctionInStream(F, DFII))
3093 // Move the bit stream to the saved position of the deferred function body.
3094 Stream.JumpToBit(DFII->second);
3096 if (error_code EC = ParseFunctionBody(F))
3099 // Upgrade any old intrinsic calls in the function.
3100 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3101 E = UpgradedIntrinsics.end(); I != E; ++I) {
3102 if (I->first != I->second) {
3103 for (Value::use_iterator UI = I->first->use_begin(),
3104 UE = I->first->use_end(); UI != UE; ) {
3105 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3106 UpgradeIntrinsicCall(CI, I->second);
3111 return error_code::success();
3114 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3115 const Function *F = dyn_cast<Function>(GV);
3116 if (!F || F->isDeclaration())
3118 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3121 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3122 Function *F = dyn_cast<Function>(GV);
3123 // If this function isn't dematerializable, this is a noop.
3124 if (!F || !isDematerializable(F))
3127 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3129 // Just forget the function body, we can remat it later.
3134 error_code BitcodeReader::MaterializeModule(Module *M) {
3135 assert(M == TheModule &&
3136 "Can only Materialize the Module this BitcodeReader is attached to.");
3137 // Iterate over the module, deserializing any functions that are still on
3139 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3141 if (F->isMaterializable()) {
3142 if (error_code EC = Materialize(F))
3146 // At this point, if there are any function bodies, the current bit is
3147 // pointing to the END_BLOCK record after them. Now make sure the rest
3148 // of the bits in the module have been read.
3152 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3153 // delete the old functions to clean up. We can't do this unless the entire
3154 // module is materialized because there could always be another function body
3155 // with calls to the old function.
3156 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3157 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3158 if (I->first != I->second) {
3159 for (Value::use_iterator UI = I->first->use_begin(),
3160 UE = I->first->use_end(); UI != UE; ) {
3161 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3162 UpgradeIntrinsicCall(CI, I->second);
3164 if (!I->first->use_empty())
3165 I->first->replaceAllUsesWith(I->second);
3166 I->first->eraseFromParent();
3169 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3171 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3172 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3174 return error_code::success();
3177 error_code BitcodeReader::InitStream() {
3179 return InitLazyStream();
3180 return InitStreamFromBuffer();
3183 error_code BitcodeReader::InitStreamFromBuffer() {
3184 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3185 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3187 if (Buffer->getBufferSize() & 3) {
3188 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3189 return Error(InvalidBitcodeSignature);
3191 return Error(BitcodeStreamInvalidSize);
3194 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3195 // The magic number is 0x0B17C0DE stored in little endian.
3196 if (isBitcodeWrapper(BufPtr, BufEnd))
3197 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3198 return Error(InvalidBitcodeWrapperHeader);
3200 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3201 Stream.init(*StreamFile);
3203 return error_code::success();
3206 error_code BitcodeReader::InitLazyStream() {
3207 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3209 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3210 StreamFile.reset(new BitstreamReader(Bytes));
3211 Stream.init(*StreamFile);
3213 unsigned char buf[16];
3214 if (Bytes->readBytes(0, 16, buf) == -1)
3215 return Error(BitcodeStreamInvalidSize);
3217 if (!isBitcode(buf, buf + 16))
3218 return Error(InvalidBitcodeSignature);
3220 if (isBitcodeWrapper(buf, buf + 4)) {
3221 const unsigned char *bitcodeStart = buf;
3222 const unsigned char *bitcodeEnd = buf + 16;
3223 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3224 Bytes->dropLeadingBytes(bitcodeStart - buf);
3225 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3227 return error_code::success();
3231 class BitcodeErrorCategoryType : public _do_message {
3232 const char *name() const LLVM_OVERRIDE {
3233 return "llvm.bitcode";
3235 std::string message(int IE) const LLVM_OVERRIDE {
3236 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3238 case BitcodeReader::BitcodeStreamInvalidSize:
3239 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3240 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3241 return "Conflicting METADATA_KIND records";
3242 case BitcodeReader::CouldNotFindFunctionInStream:
3243 return "Could not find function in stream";
3244 case BitcodeReader::ExpectedConstant:
3245 return "Expected a constant";
3246 case BitcodeReader::InsufficientFunctionProtos:
3247 return "Insufficient function protos";
3248 case BitcodeReader::InvalidBitcodeSignature:
3249 return "Invalid bitcode signature";
3250 case BitcodeReader::InvalidBitcodeWrapperHeader:
3251 return "Invalid bitcode wrapper header";
3252 case BitcodeReader::InvalidConstantReference:
3253 return "Invalid ronstant reference";
3254 case BitcodeReader::InvalidID:
3255 return "Invalid ID";
3256 case BitcodeReader::InvalidInstructionWithNoBB:
3257 return "Invalid instruction with no BB";
3258 case BitcodeReader::InvalidRecord:
3259 return "Invalid record";
3260 case BitcodeReader::InvalidTypeForValue:
3261 return "Invalid type for value";
3262 case BitcodeReader::InvalidTYPETable:
3263 return "Invalid TYPE table";
3264 case BitcodeReader::InvalidType:
3265 return "Invalid type";
3266 case BitcodeReader::MalformedBlock:
3267 return "Malformed block";
3268 case BitcodeReader::MalformedGlobalInitializerSet:
3269 return "Malformed global initializer set";
3270 case BitcodeReader::InvalidMultipleBlocks:
3271 return "Invalid multiple blocks";
3272 case BitcodeReader::NeverResolvedValueFoundInFunction:
3273 return "Never resolved value found in function";
3274 case BitcodeReader::InvalidValue:
3275 return "Invalid value";
3277 llvm_unreachable("Unknown error type!");
3282 const error_category &BitcodeReader::BitcodeErrorCategory() {
3283 static BitcodeErrorCategoryType O;
3287 //===----------------------------------------------------------------------===//
3288 // External interface
3289 //===----------------------------------------------------------------------===//
3291 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3293 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3294 LLVMContext& Context,
3295 std::string *ErrMsg) {
3296 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3297 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3298 M->setMaterializer(R);
3299 if (error_code EC = R->ParseBitcodeInto(M)) {
3301 *ErrMsg = EC.message();
3303 delete M; // Also deletes R.
3306 // Have the BitcodeReader dtor delete 'Buffer'.
3307 R->setBufferOwned(true);
3309 R->materializeForwardReferencedFunctions();
3315 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3316 DataStreamer *streamer,
3317 LLVMContext &Context,
3318 std::string *ErrMsg) {
3319 Module *M = new Module(name, Context);
3320 BitcodeReader *R = new BitcodeReader(streamer, Context);
3321 M->setMaterializer(R);
3322 if (error_code EC = R->ParseBitcodeInto(M)) {
3324 *ErrMsg = EC.message();
3325 delete M; // Also deletes R.
3328 R->setBufferOwned(false); // no buffer to delete
3332 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3333 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3334 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3335 std::string *ErrMsg){
3336 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3339 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3340 // there was an error.
3341 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3343 // Read in the entire module, and destroy the BitcodeReader.
3344 if (M->MaterializeAllPermanently(ErrMsg)) {
3349 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3350 // written. We must defer until the Module has been fully materialized.
3355 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3356 LLVMContext& Context,
3357 std::string *ErrMsg) {
3358 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3359 // Don't let the BitcodeReader dtor delete 'Buffer'.
3360 R->setBufferOwned(false);
3362 std::string Triple("");
3363 if (error_code EC = R->ParseTriple(Triple))
3365 *ErrMsg = EC.message();