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/Module.h"
21 #include "llvm/IR/OperandTraits.h"
22 #include "llvm/IR/Operator.h"
23 #include "llvm/Support/DataStream.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
30 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33 void BitcodeReader::materializeForwardReferencedFunctions() {
34 while (!BlockAddrFwdRefs.empty()) {
35 Function *F = BlockAddrFwdRefs.begin()->first;
40 void BitcodeReader::FreeState() {
44 std::vector<Type*>().swap(TypeList);
48 std::vector<AttributeSet>().swap(MAttributes);
49 std::vector<BasicBlock*>().swap(FunctionBBs);
50 std::vector<Function*>().swap(FunctionsWithBodies);
51 DeferredFunctionInfo.clear();
54 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
57 //===----------------------------------------------------------------------===//
58 // Helper functions to implement forward reference resolution, etc.
59 //===----------------------------------------------------------------------===//
61 /// ConvertToString - Convert a string from a record into an std::string, return
63 template<typename StrTy>
64 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
66 if (Idx > Record.size())
69 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70 Result += (char)Record[i];
74 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
76 default: // Map unknown/new linkages to external
77 case 0: return GlobalValue::ExternalLinkage;
78 case 1: return GlobalValue::WeakAnyLinkage;
79 case 2: return GlobalValue::AppendingLinkage;
80 case 3: return GlobalValue::InternalLinkage;
81 case 4: return GlobalValue::LinkOnceAnyLinkage;
82 case 5: return GlobalValue::DLLImportLinkage;
83 case 6: return GlobalValue::DLLExportLinkage;
84 case 7: return GlobalValue::ExternalWeakLinkage;
85 case 8: return GlobalValue::CommonLinkage;
86 case 9: return GlobalValue::PrivateLinkage;
87 case 10: return GlobalValue::WeakODRLinkage;
88 case 11: return GlobalValue::LinkOnceODRLinkage;
89 case 12: return GlobalValue::AvailableExternallyLinkage;
90 case 13: return GlobalValue::LinkerPrivateLinkage;
91 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
92 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
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 bool BitcodeReader::ParseAttributeBlock() {
454 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
455 return Error("Malformed block record");
457 if (!MAttributes.empty())
458 return Error("Multiple PARAMATTR blocks found!");
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("Error at end of PARAMATTR block");
472 case BitstreamEntry::EndBlock:
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("Invalid ENTRY record");
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 bool BitcodeReader::ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
513 case bitc::ATTR_KIND_ALIGNMENT:
514 *Kind = Attribute::Alignment;
516 case bitc::ATTR_KIND_ALWAYS_INLINE:
517 *Kind = Attribute::AlwaysInline;
519 case bitc::ATTR_KIND_BUILTIN:
520 *Kind = Attribute::Builtin;
522 case bitc::ATTR_KIND_BY_VAL:
523 *Kind = Attribute::ByVal;
525 case bitc::ATTR_KIND_COLD:
526 *Kind = Attribute::Cold;
528 case bitc::ATTR_KIND_INLINE_HINT:
529 *Kind = Attribute::InlineHint;
531 case bitc::ATTR_KIND_IN_REG:
532 *Kind = Attribute::InReg;
534 case bitc::ATTR_KIND_MIN_SIZE:
535 *Kind = Attribute::MinSize;
537 case bitc::ATTR_KIND_NAKED:
538 *Kind = Attribute::Naked;
540 case bitc::ATTR_KIND_NEST:
541 *Kind = Attribute::Nest;
543 case bitc::ATTR_KIND_NO_ALIAS:
544 *Kind = Attribute::NoAlias;
546 case bitc::ATTR_KIND_NO_BUILTIN:
547 *Kind = Attribute::NoBuiltin;
549 case bitc::ATTR_KIND_NO_CAPTURE:
550 *Kind = Attribute::NoCapture;
552 case bitc::ATTR_KIND_NO_DUPLICATE:
553 *Kind = Attribute::NoDuplicate;
555 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
556 *Kind = Attribute::NoImplicitFloat;
558 case bitc::ATTR_KIND_NO_INLINE:
559 *Kind = Attribute::NoInline;
561 case bitc::ATTR_KIND_NON_LAZY_BIND:
562 *Kind = Attribute::NonLazyBind;
564 case bitc::ATTR_KIND_NO_RED_ZONE:
565 *Kind = Attribute::NoRedZone;
567 case bitc::ATTR_KIND_NO_RETURN:
568 *Kind = Attribute::NoReturn;
570 case bitc::ATTR_KIND_NO_UNWIND:
571 *Kind = Attribute::NoUnwind;
573 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
574 *Kind = Attribute::OptimizeForSize;
576 case bitc::ATTR_KIND_OPTIMIZE_NONE:
577 *Kind = Attribute::OptimizeNone;
579 case bitc::ATTR_KIND_READ_NONE:
580 *Kind = Attribute::ReadNone;
582 case bitc::ATTR_KIND_READ_ONLY:
583 *Kind = Attribute::ReadOnly;
585 case bitc::ATTR_KIND_RETURNED:
586 *Kind = Attribute::Returned;
588 case bitc::ATTR_KIND_RETURNS_TWICE:
589 *Kind = Attribute::ReturnsTwice;
591 case bitc::ATTR_KIND_S_EXT:
592 *Kind = Attribute::SExt;
594 case bitc::ATTR_KIND_STACK_ALIGNMENT:
595 *Kind = Attribute::StackAlignment;
597 case bitc::ATTR_KIND_STACK_PROTECT:
598 *Kind = Attribute::StackProtect;
600 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
601 *Kind = Attribute::StackProtectReq;
603 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
604 *Kind = Attribute::StackProtectStrong;
606 case bitc::ATTR_KIND_STRUCT_RET:
607 *Kind = Attribute::StructRet;
609 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
610 *Kind = Attribute::SanitizeAddress;
612 case bitc::ATTR_KIND_SANITIZE_THREAD:
613 *Kind = Attribute::SanitizeThread;
615 case bitc::ATTR_KIND_SANITIZE_MEMORY:
616 *Kind = Attribute::SanitizeMemory;
618 case bitc::ATTR_KIND_UW_TABLE:
619 *Kind = Attribute::UWTable;
621 case bitc::ATTR_KIND_Z_EXT:
622 *Kind = Attribute::ZExt;
626 raw_string_ostream fmt(Buf);
627 fmt << "Unknown attribute kind (" << Code << ")";
629 return Error(Buf.c_str());
633 bool BitcodeReader::ParseAttributeGroupBlock() {
634 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
635 return Error("Malformed block record");
637 if (!MAttributeGroups.empty())
638 return Error("Multiple PARAMATTR_GROUP blocks found!");
640 SmallVector<uint64_t, 64> Record;
642 // Read all the records.
644 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
646 switch (Entry.Kind) {
647 case BitstreamEntry::SubBlock: // Handled for us already.
648 case BitstreamEntry::Error:
649 return Error("Error at end of PARAMATTR_GROUP block");
650 case BitstreamEntry::EndBlock:
652 case BitstreamEntry::Record:
653 // The interesting case.
659 switch (Stream.readRecord(Entry.ID, Record)) {
660 default: // Default behavior: ignore.
662 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
663 if (Record.size() < 3)
664 return Error("Invalid ENTRY record");
666 uint64_t GrpID = Record[0];
667 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
670 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
671 if (Record[i] == 0) { // Enum attribute
672 Attribute::AttrKind Kind;
673 if (ParseAttrKind(Record[++i], &Kind))
676 B.addAttribute(Kind);
677 } else if (Record[i] == 1) { // Align attribute
678 Attribute::AttrKind Kind;
679 if (ParseAttrKind(Record[++i], &Kind))
681 if (Kind == Attribute::Alignment)
682 B.addAlignmentAttr(Record[++i]);
684 B.addStackAlignmentAttr(Record[++i]);
685 } else { // String attribute
686 assert((Record[i] == 3 || Record[i] == 4) &&
687 "Invalid attribute group entry");
688 bool HasValue = (Record[i++] == 4);
689 SmallString<64> KindStr;
690 SmallString<64> ValStr;
692 while (Record[i] != 0 && i != e)
693 KindStr += Record[i++];
694 assert(Record[i] == 0 && "Kind string not null terminated");
697 // Has a value associated with it.
698 ++i; // Skip the '0' that terminates the "kind" string.
699 while (Record[i] != 0 && i != e)
700 ValStr += Record[i++];
701 assert(Record[i] == 0 && "Value string not null terminated");
704 B.addAttribute(KindStr.str(), ValStr.str());
708 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
715 bool BitcodeReader::ParseTypeTable() {
716 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
717 return Error("Malformed block record");
719 return ParseTypeTableBody();
722 bool BitcodeReader::ParseTypeTableBody() {
723 if (!TypeList.empty())
724 return Error("Multiple TYPE_BLOCKs found!");
726 SmallVector<uint64_t, 64> Record;
727 unsigned NumRecords = 0;
729 SmallString<64> TypeName;
731 // Read all the records for this type table.
733 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
735 switch (Entry.Kind) {
736 case BitstreamEntry::SubBlock: // Handled for us already.
737 case BitstreamEntry::Error:
738 Error("Error in the type table block");
740 case BitstreamEntry::EndBlock:
741 if (NumRecords != TypeList.size())
742 return Error("Invalid type forward reference in TYPE_BLOCK");
744 case BitstreamEntry::Record:
745 // The interesting case.
752 switch (Stream.readRecord(Entry.ID, Record)) {
753 default: return Error("unknown type in type table");
754 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
755 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
756 // type list. This allows us to reserve space.
757 if (Record.size() < 1)
758 return Error("Invalid TYPE_CODE_NUMENTRY record");
759 TypeList.resize(Record[0]);
761 case bitc::TYPE_CODE_VOID: // VOID
762 ResultTy = Type::getVoidTy(Context);
764 case bitc::TYPE_CODE_HALF: // HALF
765 ResultTy = Type::getHalfTy(Context);
767 case bitc::TYPE_CODE_FLOAT: // FLOAT
768 ResultTy = Type::getFloatTy(Context);
770 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
771 ResultTy = Type::getDoubleTy(Context);
773 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
774 ResultTy = Type::getX86_FP80Ty(Context);
776 case bitc::TYPE_CODE_FP128: // FP128
777 ResultTy = Type::getFP128Ty(Context);
779 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
780 ResultTy = Type::getPPC_FP128Ty(Context);
782 case bitc::TYPE_CODE_LABEL: // LABEL
783 ResultTy = Type::getLabelTy(Context);
785 case bitc::TYPE_CODE_METADATA: // METADATA
786 ResultTy = Type::getMetadataTy(Context);
788 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
789 ResultTy = Type::getX86_MMXTy(Context);
791 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
792 if (Record.size() < 1)
793 return Error("Invalid Integer type record");
795 ResultTy = IntegerType::get(Context, Record[0]);
797 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
798 // [pointee type, address space]
799 if (Record.size() < 1)
800 return Error("Invalid POINTER type record");
801 unsigned AddressSpace = 0;
802 if (Record.size() == 2)
803 AddressSpace = Record[1];
804 ResultTy = getTypeByID(Record[0]);
805 if (ResultTy == 0) return Error("invalid element type in pointer type");
806 ResultTy = PointerType::get(ResultTy, AddressSpace);
809 case bitc::TYPE_CODE_FUNCTION_OLD: {
810 // FIXME: attrid is dead, remove it in LLVM 4.0
811 // FUNCTION: [vararg, attrid, retty, paramty x N]
812 if (Record.size() < 3)
813 return Error("Invalid FUNCTION type record");
814 SmallVector<Type*, 8> ArgTys;
815 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
816 if (Type *T = getTypeByID(Record[i]))
822 ResultTy = getTypeByID(Record[2]);
823 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
824 return Error("invalid type in function type");
826 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
829 case bitc::TYPE_CODE_FUNCTION: {
830 // FUNCTION: [vararg, retty, paramty x N]
831 if (Record.size() < 2)
832 return Error("Invalid FUNCTION type record");
833 SmallVector<Type*, 8> ArgTys;
834 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
835 if (Type *T = getTypeByID(Record[i]))
841 ResultTy = getTypeByID(Record[1]);
842 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
843 return Error("invalid type in function type");
845 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
848 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
849 if (Record.size() < 1)
850 return Error("Invalid STRUCT type record");
851 SmallVector<Type*, 8> EltTys;
852 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
853 if (Type *T = getTypeByID(Record[i]))
858 if (EltTys.size() != Record.size()-1)
859 return Error("invalid type in struct type");
860 ResultTy = StructType::get(Context, EltTys, Record[0]);
863 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
864 if (ConvertToString(Record, 0, TypeName))
865 return Error("Invalid STRUCT_NAME record");
868 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
869 if (Record.size() < 1)
870 return Error("Invalid STRUCT type record");
872 if (NumRecords >= TypeList.size())
873 return Error("invalid TYPE table");
875 // Check to see if this was forward referenced, if so fill in the temp.
876 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
878 Res->setName(TypeName);
879 TypeList[NumRecords] = 0;
880 } else // Otherwise, create a new struct.
881 Res = StructType::create(Context, TypeName);
884 SmallVector<Type*, 8> EltTys;
885 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
886 if (Type *T = getTypeByID(Record[i]))
891 if (EltTys.size() != Record.size()-1)
892 return Error("invalid STRUCT type record");
893 Res->setBody(EltTys, Record[0]);
897 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
898 if (Record.size() != 1)
899 return Error("Invalid OPAQUE type record");
901 if (NumRecords >= TypeList.size())
902 return Error("invalid TYPE table");
904 // Check to see if this was forward referenced, if so fill in the temp.
905 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
907 Res->setName(TypeName);
908 TypeList[NumRecords] = 0;
909 } else // Otherwise, create a new struct with no body.
910 Res = StructType::create(Context, TypeName);
915 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
916 if (Record.size() < 2)
917 return Error("Invalid ARRAY type record");
918 if ((ResultTy = getTypeByID(Record[1])))
919 ResultTy = ArrayType::get(ResultTy, Record[0]);
921 return Error("Invalid ARRAY type element");
923 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
924 if (Record.size() < 2)
925 return Error("Invalid VECTOR type record");
926 if ((ResultTy = getTypeByID(Record[1])))
927 ResultTy = VectorType::get(ResultTy, Record[0]);
929 return Error("Invalid ARRAY type element");
933 if (NumRecords >= TypeList.size())
934 return Error("invalid TYPE table");
935 assert(ResultTy && "Didn't read a type?");
936 assert(TypeList[NumRecords] == 0 && "Already read type?");
937 TypeList[NumRecords++] = ResultTy;
941 bool BitcodeReader::ParseValueSymbolTable() {
942 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
943 return Error("Malformed block record");
945 SmallVector<uint64_t, 64> Record;
947 // Read all the records for this value table.
948 SmallString<128> ValueName;
950 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
952 switch (Entry.Kind) {
953 case BitstreamEntry::SubBlock: // Handled for us already.
954 case BitstreamEntry::Error:
955 return Error("malformed value symbol table block");
956 case BitstreamEntry::EndBlock:
958 case BitstreamEntry::Record:
959 // The interesting case.
965 switch (Stream.readRecord(Entry.ID, Record)) {
966 default: // Default behavior: unknown type.
968 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
969 if (ConvertToString(Record, 1, ValueName))
970 return Error("Invalid VST_ENTRY record");
971 unsigned ValueID = Record[0];
972 if (ValueID >= ValueList.size())
973 return Error("Invalid Value ID in VST_ENTRY record");
974 Value *V = ValueList[ValueID];
976 V->setName(StringRef(ValueName.data(), ValueName.size()));
980 case bitc::VST_CODE_BBENTRY: {
981 if (ConvertToString(Record, 1, ValueName))
982 return Error("Invalid VST_BBENTRY record");
983 BasicBlock *BB = getBasicBlock(Record[0]);
985 return Error("Invalid BB ID in VST_BBENTRY record");
987 BB->setName(StringRef(ValueName.data(), ValueName.size()));
995 bool BitcodeReader::ParseMetadata() {
996 unsigned NextMDValueNo = MDValueList.size();
998 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
999 return Error("Malformed block record");
1001 SmallVector<uint64_t, 64> Record;
1003 // Read all the records.
1005 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1007 switch (Entry.Kind) {
1008 case BitstreamEntry::SubBlock: // Handled for us already.
1009 case BitstreamEntry::Error:
1010 Error("malformed metadata block");
1012 case BitstreamEntry::EndBlock:
1014 case BitstreamEntry::Record:
1015 // The interesting case.
1019 bool IsFunctionLocal = false;
1022 unsigned Code = Stream.readRecord(Entry.ID, Record);
1024 default: // Default behavior: ignore.
1026 case bitc::METADATA_NAME: {
1027 // Read name of the named metadata.
1028 SmallString<8> Name(Record.begin(), Record.end());
1030 Code = Stream.ReadCode();
1032 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1033 unsigned NextBitCode = Stream.readRecord(Code, Record);
1034 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1036 // Read named metadata elements.
1037 unsigned Size = Record.size();
1038 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1039 for (unsigned i = 0; i != Size; ++i) {
1040 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1042 return Error("Malformed metadata record");
1043 NMD->addOperand(MD);
1047 case bitc::METADATA_FN_NODE:
1048 IsFunctionLocal = true;
1050 case bitc::METADATA_NODE: {
1051 if (Record.size() % 2 == 1)
1052 return Error("Invalid METADATA_NODE record");
1054 unsigned Size = Record.size();
1055 SmallVector<Value*, 8> Elts;
1056 for (unsigned i = 0; i != Size; i += 2) {
1057 Type *Ty = getTypeByID(Record[i]);
1058 if (!Ty) return Error("Invalid METADATA_NODE record");
1059 if (Ty->isMetadataTy())
1060 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1061 else if (!Ty->isVoidTy())
1062 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1064 Elts.push_back(NULL);
1066 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1067 IsFunctionLocal = false;
1068 MDValueList.AssignValue(V, NextMDValueNo++);
1071 case bitc::METADATA_STRING: {
1072 SmallString<8> String(Record.begin(), Record.end());
1073 Value *V = MDString::get(Context, String);
1074 MDValueList.AssignValue(V, NextMDValueNo++);
1077 case bitc::METADATA_KIND: {
1078 if (Record.size() < 2)
1079 return Error("Invalid METADATA_KIND record");
1081 unsigned Kind = Record[0];
1082 SmallString<8> Name(Record.begin()+1, Record.end());
1084 unsigned NewKind = TheModule->getMDKindID(Name.str());
1085 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1086 return Error("Conflicting METADATA_KIND records");
1093 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1094 /// the LSB for dense VBR encoding.
1095 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1100 // There is no such thing as -0 with integers. "-0" really means MININT.
1104 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1105 /// values and aliases that we can.
1106 bool BitcodeReader::ResolveGlobalAndAliasInits() {
1107 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1108 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1110 GlobalInitWorklist.swap(GlobalInits);
1111 AliasInitWorklist.swap(AliasInits);
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("Global variable initializer is not a constant!");
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("Alias initializer is not a constant!");
1137 AliasInitWorklist.pop_back();
1142 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1143 SmallVector<uint64_t, 8> Words(Vals.size());
1144 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1145 BitcodeReader::decodeSignRotatedValue);
1147 return APInt(TypeBits, Words);
1150 bool BitcodeReader::ParseConstants() {
1151 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1152 return Error("Malformed block record");
1154 SmallVector<uint64_t, 64> Record;
1156 // Read all the records for this value table.
1157 Type *CurTy = Type::getInt32Ty(Context);
1158 unsigned NextCstNo = ValueList.size();
1160 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1162 switch (Entry.Kind) {
1163 case BitstreamEntry::SubBlock: // Handled for us already.
1164 case BitstreamEntry::Error:
1165 return Error("malformed block record in AST file");
1166 case BitstreamEntry::EndBlock:
1167 if (NextCstNo != ValueList.size())
1168 return Error("Invalid constant reference!");
1170 // Once all the constants have been read, go through and resolve forward
1172 ValueList.ResolveConstantForwardRefs();
1174 case BitstreamEntry::Record:
1175 // The interesting case.
1182 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1184 default: // Default behavior: unknown constant
1185 case bitc::CST_CODE_UNDEF: // UNDEF
1186 V = UndefValue::get(CurTy);
1188 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1190 return Error("Malformed CST_SETTYPE record");
1191 if (Record[0] >= TypeList.size())
1192 return Error("Invalid Type ID in CST_SETTYPE record");
1193 CurTy = TypeList[Record[0]];
1194 continue; // Skip the ValueList manipulation.
1195 case bitc::CST_CODE_NULL: // NULL
1196 V = Constant::getNullValue(CurTy);
1198 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1199 if (!CurTy->isIntegerTy() || Record.empty())
1200 return Error("Invalid CST_INTEGER record");
1201 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1203 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1204 if (!CurTy->isIntegerTy() || Record.empty())
1205 return Error("Invalid WIDE_INTEGER record");
1207 APInt VInt = ReadWideAPInt(Record,
1208 cast<IntegerType>(CurTy)->getBitWidth());
1209 V = ConstantInt::get(Context, VInt);
1213 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1215 return Error("Invalid FLOAT record");
1216 if (CurTy->isHalfTy())
1217 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1218 APInt(16, (uint16_t)Record[0])));
1219 else if (CurTy->isFloatTy())
1220 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1221 APInt(32, (uint32_t)Record[0])));
1222 else if (CurTy->isDoubleTy())
1223 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1224 APInt(64, Record[0])));
1225 else if (CurTy->isX86_FP80Ty()) {
1226 // Bits are not stored the same way as a normal i80 APInt, compensate.
1227 uint64_t Rearrange[2];
1228 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1229 Rearrange[1] = Record[0] >> 48;
1230 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1231 APInt(80, Rearrange)));
1232 } else if (CurTy->isFP128Ty())
1233 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1234 APInt(128, Record)));
1235 else if (CurTy->isPPC_FP128Ty())
1236 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1237 APInt(128, Record)));
1239 V = UndefValue::get(CurTy);
1243 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1245 return Error("Invalid CST_AGGREGATE record");
1247 unsigned Size = Record.size();
1248 SmallVector<Constant*, 16> Elts;
1250 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1251 for (unsigned i = 0; i != Size; ++i)
1252 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1253 STy->getElementType(i)));
1254 V = ConstantStruct::get(STy, Elts);
1255 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1256 Type *EltTy = ATy->getElementType();
1257 for (unsigned i = 0; i != Size; ++i)
1258 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1259 V = ConstantArray::get(ATy, Elts);
1260 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1261 Type *EltTy = VTy->getElementType();
1262 for (unsigned i = 0; i != Size; ++i)
1263 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1264 V = ConstantVector::get(Elts);
1266 V = UndefValue::get(CurTy);
1270 case bitc::CST_CODE_STRING: // STRING: [values]
1271 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1273 return Error("Invalid CST_STRING record");
1275 SmallString<16> Elts(Record.begin(), Record.end());
1276 V = ConstantDataArray::getString(Context, Elts,
1277 BitCode == bitc::CST_CODE_CSTRING);
1280 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1282 return Error("Invalid CST_DATA record");
1284 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1285 unsigned Size = Record.size();
1287 if (EltTy->isIntegerTy(8)) {
1288 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1289 if (isa<VectorType>(CurTy))
1290 V = ConstantDataVector::get(Context, Elts);
1292 V = ConstantDataArray::get(Context, Elts);
1293 } else if (EltTy->isIntegerTy(16)) {
1294 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1295 if (isa<VectorType>(CurTy))
1296 V = ConstantDataVector::get(Context, Elts);
1298 V = ConstantDataArray::get(Context, Elts);
1299 } else if (EltTy->isIntegerTy(32)) {
1300 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1301 if (isa<VectorType>(CurTy))
1302 V = ConstantDataVector::get(Context, Elts);
1304 V = ConstantDataArray::get(Context, Elts);
1305 } else if (EltTy->isIntegerTy(64)) {
1306 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1307 if (isa<VectorType>(CurTy))
1308 V = ConstantDataVector::get(Context, Elts);
1310 V = ConstantDataArray::get(Context, Elts);
1311 } else if (EltTy->isFloatTy()) {
1312 SmallVector<float, 16> Elts(Size);
1313 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1314 if (isa<VectorType>(CurTy))
1315 V = ConstantDataVector::get(Context, Elts);
1317 V = ConstantDataArray::get(Context, Elts);
1318 } else if (EltTy->isDoubleTy()) {
1319 SmallVector<double, 16> Elts(Size);
1320 std::transform(Record.begin(), Record.end(), Elts.begin(),
1322 if (isa<VectorType>(CurTy))
1323 V = ConstantDataVector::get(Context, Elts);
1325 V = ConstantDataArray::get(Context, Elts);
1327 return Error("Unknown element type in CE_DATA");
1332 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1333 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1334 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1336 V = UndefValue::get(CurTy); // Unknown binop.
1338 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1339 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1341 if (Record.size() >= 4) {
1342 if (Opc == Instruction::Add ||
1343 Opc == Instruction::Sub ||
1344 Opc == Instruction::Mul ||
1345 Opc == Instruction::Shl) {
1346 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1347 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1348 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1349 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1350 } else if (Opc == Instruction::SDiv ||
1351 Opc == Instruction::UDiv ||
1352 Opc == Instruction::LShr ||
1353 Opc == Instruction::AShr) {
1354 if (Record[3] & (1 << bitc::PEO_EXACT))
1355 Flags |= SDivOperator::IsExact;
1358 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1362 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1363 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1364 int Opc = GetDecodedCastOpcode(Record[0]);
1366 V = UndefValue::get(CurTy); // Unknown cast.
1368 Type *OpTy = getTypeByID(Record[1]);
1369 if (!OpTy) return Error("Invalid CE_CAST record");
1370 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1371 V = ConstantExpr::getCast(Opc, Op, CurTy);
1375 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1376 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1377 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1378 SmallVector<Constant*, 16> Elts;
1379 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1380 Type *ElTy = getTypeByID(Record[i]);
1381 if (!ElTy) return Error("Invalid CE_GEP record");
1382 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1384 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1385 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1387 bitc::CST_CODE_CE_INBOUNDS_GEP);
1390 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1391 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1392 V = ConstantExpr::getSelect(
1393 ValueList.getConstantFwdRef(Record[0],
1394 Type::getInt1Ty(Context)),
1395 ValueList.getConstantFwdRef(Record[1],CurTy),
1396 ValueList.getConstantFwdRef(Record[2],CurTy));
1398 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1399 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1401 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1402 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1403 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1404 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1405 Type::getInt32Ty(Context));
1406 V = ConstantExpr::getExtractElement(Op0, Op1);
1409 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1410 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1411 if (Record.size() < 3 || OpTy == 0)
1412 return Error("Invalid CE_INSERTELT record");
1413 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1414 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1415 OpTy->getElementType());
1416 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1417 Type::getInt32Ty(Context));
1418 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1421 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1422 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1423 if (Record.size() < 3 || OpTy == 0)
1424 return Error("Invalid CE_SHUFFLEVEC record");
1425 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1426 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1427 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1428 OpTy->getNumElements());
1429 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1430 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1433 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1434 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1436 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1437 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1438 return Error("Invalid CE_SHUFVEC_EX record");
1439 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1440 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1441 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1442 RTy->getNumElements());
1443 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1444 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1447 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1448 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1449 Type *OpTy = getTypeByID(Record[0]);
1450 if (OpTy == 0) return Error("Invalid CE_CMP record");
1451 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1452 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1454 if (OpTy->isFPOrFPVectorTy())
1455 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1457 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1460 // This maintains backward compatibility, pre-asm dialect keywords.
1461 // FIXME: Remove with the 4.0 release.
1462 case bitc::CST_CODE_INLINEASM_OLD: {
1463 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1464 std::string AsmStr, ConstrStr;
1465 bool HasSideEffects = Record[0] & 1;
1466 bool IsAlignStack = Record[0] >> 1;
1467 unsigned AsmStrSize = Record[1];
1468 if (2+AsmStrSize >= Record.size())
1469 return Error("Invalid INLINEASM record");
1470 unsigned ConstStrSize = Record[2+AsmStrSize];
1471 if (3+AsmStrSize+ConstStrSize > Record.size())
1472 return Error("Invalid INLINEASM record");
1474 for (unsigned i = 0; i != AsmStrSize; ++i)
1475 AsmStr += (char)Record[2+i];
1476 for (unsigned i = 0; i != ConstStrSize; ++i)
1477 ConstrStr += (char)Record[3+AsmStrSize+i];
1478 PointerType *PTy = cast<PointerType>(CurTy);
1479 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1480 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1483 // This version adds support for the asm dialect keywords (e.g.,
1485 case bitc::CST_CODE_INLINEASM: {
1486 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1487 std::string AsmStr, ConstrStr;
1488 bool HasSideEffects = Record[0] & 1;
1489 bool IsAlignStack = (Record[0] >> 1) & 1;
1490 unsigned AsmDialect = Record[0] >> 2;
1491 unsigned AsmStrSize = Record[1];
1492 if (2+AsmStrSize >= Record.size())
1493 return Error("Invalid INLINEASM record");
1494 unsigned ConstStrSize = Record[2+AsmStrSize];
1495 if (3+AsmStrSize+ConstStrSize > Record.size())
1496 return Error("Invalid INLINEASM record");
1498 for (unsigned i = 0; i != AsmStrSize; ++i)
1499 AsmStr += (char)Record[2+i];
1500 for (unsigned i = 0; i != ConstStrSize; ++i)
1501 ConstrStr += (char)Record[3+AsmStrSize+i];
1502 PointerType *PTy = cast<PointerType>(CurTy);
1503 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1504 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1505 InlineAsm::AsmDialect(AsmDialect));
1508 case bitc::CST_CODE_BLOCKADDRESS:{
1509 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1510 Type *FnTy = getTypeByID(Record[0]);
1511 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1513 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1514 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1516 // If the function is already parsed we can insert the block address right
1519 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1520 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1522 return Error("Invalid blockaddress block #");
1525 V = BlockAddress::get(Fn, BBI);
1527 // Otherwise insert a placeholder and remember it so it can be inserted
1528 // when the function is parsed.
1529 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1530 Type::getInt8Ty(Context),
1531 false, GlobalValue::InternalLinkage,
1533 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1540 ValueList.AssignValue(V, NextCstNo);
1545 bool BitcodeReader::ParseUseLists() {
1546 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1547 return Error("Malformed block record");
1549 SmallVector<uint64_t, 64> Record;
1551 // Read all the records.
1553 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1555 switch (Entry.Kind) {
1556 case BitstreamEntry::SubBlock: // Handled for us already.
1557 case BitstreamEntry::Error:
1558 return Error("malformed use list block");
1559 case BitstreamEntry::EndBlock:
1561 case BitstreamEntry::Record:
1562 // The interesting case.
1566 // Read a use list record.
1568 switch (Stream.readRecord(Entry.ID, Record)) {
1569 default: // Default behavior: unknown type.
1571 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1572 unsigned RecordLength = Record.size();
1573 if (RecordLength < 1)
1574 return Error ("Invalid UseList reader!");
1575 UseListRecords.push_back(Record);
1582 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1583 /// remember where it is and then skip it. This lets us lazily deserialize the
1585 bool BitcodeReader::RememberAndSkipFunctionBody() {
1586 // Get the function we are talking about.
1587 if (FunctionsWithBodies.empty())
1588 return Error("Insufficient function protos");
1590 Function *Fn = FunctionsWithBodies.back();
1591 FunctionsWithBodies.pop_back();
1593 // Save the current stream state.
1594 uint64_t CurBit = Stream.GetCurrentBitNo();
1595 DeferredFunctionInfo[Fn] = CurBit;
1597 // Skip over the function block for now.
1598 if (Stream.SkipBlock())
1599 return Error("Malformed block record");
1603 bool BitcodeReader::GlobalCleanup() {
1604 // Patch the initializers for globals and aliases up.
1605 ResolveGlobalAndAliasInits();
1606 if (!GlobalInits.empty() || !AliasInits.empty())
1607 return Error("Malformed global initializer set");
1609 // Look for intrinsic functions which need to be upgraded at some point
1610 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1613 if (UpgradeIntrinsicFunction(FI, NewFn))
1614 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1617 // Look for global variables which need to be renamed.
1618 for (Module::global_iterator
1619 GI = TheModule->global_begin(), GE = TheModule->global_end();
1621 UpgradeGlobalVariable(GI);
1622 // Force deallocation of memory for these vectors to favor the client that
1623 // want lazy deserialization.
1624 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1625 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1629 bool BitcodeReader::ParseModule(bool Resume) {
1631 Stream.JumpToBit(NextUnreadBit);
1632 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1633 return Error("Malformed block record");
1635 SmallVector<uint64_t, 64> Record;
1636 std::vector<std::string> SectionTable;
1637 std::vector<std::string> GCTable;
1639 // Read all the records for this module.
1641 BitstreamEntry Entry = Stream.advance();
1643 switch (Entry.Kind) {
1644 case BitstreamEntry::Error:
1645 Error("malformed module block");
1647 case BitstreamEntry::EndBlock:
1648 return GlobalCleanup();
1650 case BitstreamEntry::SubBlock:
1652 default: // Skip unknown content.
1653 if (Stream.SkipBlock())
1654 return Error("Malformed block record");
1656 case bitc::BLOCKINFO_BLOCK_ID:
1657 if (Stream.ReadBlockInfoBlock())
1658 return Error("Malformed BlockInfoBlock");
1660 case bitc::PARAMATTR_BLOCK_ID:
1661 if (ParseAttributeBlock())
1664 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1665 if (ParseAttributeGroupBlock())
1668 case bitc::TYPE_BLOCK_ID_NEW:
1669 if (ParseTypeTable())
1672 case bitc::VALUE_SYMTAB_BLOCK_ID:
1673 if (ParseValueSymbolTable())
1675 SeenValueSymbolTable = true;
1677 case bitc::CONSTANTS_BLOCK_ID:
1678 if (ParseConstants() || ResolveGlobalAndAliasInits())
1681 case bitc::METADATA_BLOCK_ID:
1682 if (ParseMetadata())
1685 case bitc::FUNCTION_BLOCK_ID:
1686 // If this is the first function body we've seen, reverse the
1687 // FunctionsWithBodies list.
1688 if (!SeenFirstFunctionBody) {
1689 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1690 if (GlobalCleanup())
1692 SeenFirstFunctionBody = true;
1695 if (RememberAndSkipFunctionBody())
1697 // For streaming bitcode, suspend parsing when we reach the function
1698 // bodies. Subsequent materialization calls will resume it when
1699 // necessary. For streaming, the function bodies must be at the end of
1700 // the bitcode. If the bitcode file is old, the symbol table will be
1701 // at the end instead and will not have been seen yet. In this case,
1702 // just finish the parse now.
1703 if (LazyStreamer && SeenValueSymbolTable) {
1704 NextUnreadBit = Stream.GetCurrentBitNo();
1708 case bitc::USELIST_BLOCK_ID:
1709 if (ParseUseLists())
1715 case BitstreamEntry::Record:
1716 // The interesting case.
1722 switch (Stream.readRecord(Entry.ID, Record)) {
1723 default: break; // Default behavior, ignore unknown content.
1724 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1725 if (Record.size() < 1)
1726 return Error("Malformed MODULE_CODE_VERSION");
1727 // Only version #0 and #1 are supported so far.
1728 unsigned module_version = Record[0];
1729 switch (module_version) {
1730 default: return Error("Unknown bitstream version!");
1732 UseRelativeIDs = false;
1735 UseRelativeIDs = true;
1740 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1742 if (ConvertToString(Record, 0, S))
1743 return Error("Invalid MODULE_CODE_TRIPLE record");
1744 TheModule->setTargetTriple(S);
1747 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1749 if (ConvertToString(Record, 0, S))
1750 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1751 TheModule->setDataLayout(S);
1754 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1756 if (ConvertToString(Record, 0, S))
1757 return Error("Invalid MODULE_CODE_ASM record");
1758 TheModule->setModuleInlineAsm(S);
1761 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1762 // FIXME: Remove in 4.0.
1764 if (ConvertToString(Record, 0, S))
1765 return Error("Invalid MODULE_CODE_DEPLIB record");
1769 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1771 if (ConvertToString(Record, 0, S))
1772 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1773 SectionTable.push_back(S);
1776 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1778 if (ConvertToString(Record, 0, S))
1779 return Error("Invalid MODULE_CODE_GCNAME record");
1780 GCTable.push_back(S);
1783 // GLOBALVAR: [pointer type, isconst, initid,
1784 // linkage, alignment, section, visibility, threadlocal,
1786 case bitc::MODULE_CODE_GLOBALVAR: {
1787 if (Record.size() < 6)
1788 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1789 Type *Ty = getTypeByID(Record[0]);
1790 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1791 if (!Ty->isPointerTy())
1792 return Error("Global not a pointer type!");
1793 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1794 Ty = cast<PointerType>(Ty)->getElementType();
1796 bool isConstant = Record[1];
1797 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1798 unsigned Alignment = (1 << Record[4]) >> 1;
1799 std::string Section;
1801 if (Record[5]-1 >= SectionTable.size())
1802 return Error("Invalid section ID");
1803 Section = SectionTable[Record[5]-1];
1805 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1806 if (Record.size() > 6)
1807 Visibility = GetDecodedVisibility(Record[6]);
1809 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1810 if (Record.size() > 7)
1811 TLM = GetDecodedThreadLocalMode(Record[7]);
1813 bool UnnamedAddr = false;
1814 if (Record.size() > 8)
1815 UnnamedAddr = Record[8];
1817 bool ExternallyInitialized = false;
1818 if (Record.size() > 9)
1819 ExternallyInitialized = Record[9];
1821 GlobalVariable *NewGV =
1822 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1823 TLM, AddressSpace, ExternallyInitialized);
1824 NewGV->setAlignment(Alignment);
1825 if (!Section.empty())
1826 NewGV->setSection(Section);
1827 NewGV->setVisibility(Visibility);
1828 NewGV->setUnnamedAddr(UnnamedAddr);
1830 ValueList.push_back(NewGV);
1832 // Remember which value to use for the global initializer.
1833 if (unsigned InitID = Record[2])
1834 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1837 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1838 // alignment, section, visibility, gc, unnamed_addr]
1839 case bitc::MODULE_CODE_FUNCTION: {
1840 if (Record.size() < 8)
1841 return Error("Invalid MODULE_CODE_FUNCTION record");
1842 Type *Ty = getTypeByID(Record[0]);
1843 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1844 if (!Ty->isPointerTy())
1845 return Error("Function not a pointer type!");
1847 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1849 return Error("Function not a pointer to function type!");
1851 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1854 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1855 bool isProto = Record[2];
1856 Func->setLinkage(GetDecodedLinkage(Record[3]));
1857 Func->setAttributes(getAttributes(Record[4]));
1859 Func->setAlignment((1 << Record[5]) >> 1);
1861 if (Record[6]-1 >= SectionTable.size())
1862 return Error("Invalid section ID");
1863 Func->setSection(SectionTable[Record[6]-1]);
1865 Func->setVisibility(GetDecodedVisibility(Record[7]));
1866 if (Record.size() > 8 && Record[8]) {
1867 if (Record[8]-1 > GCTable.size())
1868 return Error("Invalid GC ID");
1869 Func->setGC(GCTable[Record[8]-1].c_str());
1871 bool UnnamedAddr = false;
1872 if (Record.size() > 9)
1873 UnnamedAddr = Record[9];
1874 Func->setUnnamedAddr(UnnamedAddr);
1875 ValueList.push_back(Func);
1877 // If this is a function with a body, remember the prototype we are
1878 // creating now, so that we can match up the body with them later.
1880 FunctionsWithBodies.push_back(Func);
1881 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1885 // ALIAS: [alias type, aliasee val#, linkage]
1886 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1887 case bitc::MODULE_CODE_ALIAS: {
1888 if (Record.size() < 3)
1889 return Error("Invalid MODULE_ALIAS record");
1890 Type *Ty = getTypeByID(Record[0]);
1891 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1892 if (!Ty->isPointerTy())
1893 return Error("Function not a pointer type!");
1895 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1897 // Old bitcode files didn't have visibility field.
1898 if (Record.size() > 3)
1899 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1900 ValueList.push_back(NewGA);
1901 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1904 /// MODULE_CODE_PURGEVALS: [numvals]
1905 case bitc::MODULE_CODE_PURGEVALS:
1906 // Trim down the value list to the specified size.
1907 if (Record.size() < 1 || Record[0] > ValueList.size())
1908 return Error("Invalid MODULE_PURGEVALS record");
1909 ValueList.shrinkTo(Record[0]);
1916 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1919 if (InitStream()) return true;
1921 // Sniff for the signature.
1922 if (Stream.Read(8) != 'B' ||
1923 Stream.Read(8) != 'C' ||
1924 Stream.Read(4) != 0x0 ||
1925 Stream.Read(4) != 0xC ||
1926 Stream.Read(4) != 0xE ||
1927 Stream.Read(4) != 0xD)
1928 return Error("Invalid bitcode signature");
1930 // We expect a number of well-defined blocks, though we don't necessarily
1931 // need to understand them all.
1933 if (Stream.AtEndOfStream())
1936 BitstreamEntry Entry =
1937 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1939 switch (Entry.Kind) {
1940 case BitstreamEntry::Error:
1941 Error("malformed module file");
1943 case BitstreamEntry::EndBlock:
1946 case BitstreamEntry::SubBlock:
1948 case bitc::BLOCKINFO_BLOCK_ID:
1949 if (Stream.ReadBlockInfoBlock())
1950 return Error("Malformed BlockInfoBlock");
1952 case bitc::MODULE_BLOCK_ID:
1953 // Reject multiple MODULE_BLOCK's in a single bitstream.
1955 return Error("Multiple MODULE_BLOCKs in same stream");
1957 if (ParseModule(false))
1959 if (LazyStreamer) return false;
1962 if (Stream.SkipBlock())
1963 return Error("Malformed block record");
1967 case BitstreamEntry::Record:
1968 // There should be no records in the top-level of blocks.
1970 // The ranlib in Xcode 4 will align archive members by appending newlines
1971 // to the end of them. If this file size is a multiple of 4 but not 8, we
1972 // have to read and ignore these final 4 bytes :-(
1973 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1974 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1975 Stream.AtEndOfStream())
1978 return Error("Invalid record at top-level");
1983 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1984 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1985 return Error("Malformed block record");
1987 SmallVector<uint64_t, 64> Record;
1989 // Read all the records for this module.
1991 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1993 switch (Entry.Kind) {
1994 case BitstreamEntry::SubBlock: // Handled for us already.
1995 case BitstreamEntry::Error:
1996 return Error("malformed module block");
1997 case BitstreamEntry::EndBlock:
1999 case BitstreamEntry::Record:
2000 // The interesting case.
2005 switch (Stream.readRecord(Entry.ID, Record)) {
2006 default: break; // Default behavior, ignore unknown content.
2007 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2009 if (ConvertToString(Record, 0, S))
2010 return Error("Invalid MODULE_CODE_TRIPLE record");
2019 bool BitcodeReader::ParseTriple(std::string &Triple) {
2020 if (InitStream()) return true;
2022 // Sniff for the signature.
2023 if (Stream.Read(8) != 'B' ||
2024 Stream.Read(8) != 'C' ||
2025 Stream.Read(4) != 0x0 ||
2026 Stream.Read(4) != 0xC ||
2027 Stream.Read(4) != 0xE ||
2028 Stream.Read(4) != 0xD)
2029 return Error("Invalid bitcode signature");
2031 // We expect a number of well-defined blocks, though we don't necessarily
2032 // need to understand them all.
2034 BitstreamEntry Entry = Stream.advance();
2036 switch (Entry.Kind) {
2037 case BitstreamEntry::Error:
2038 Error("malformed module file");
2040 case BitstreamEntry::EndBlock:
2043 case BitstreamEntry::SubBlock:
2044 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2045 return ParseModuleTriple(Triple);
2047 // Ignore other sub-blocks.
2048 if (Stream.SkipBlock()) {
2049 Error("malformed block record in AST file");
2054 case BitstreamEntry::Record:
2055 Stream.skipRecord(Entry.ID);
2061 /// ParseMetadataAttachment - Parse metadata attachments.
2062 bool BitcodeReader::ParseMetadataAttachment() {
2063 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2064 return Error("Malformed block record");
2066 SmallVector<uint64_t, 64> Record;
2068 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2070 switch (Entry.Kind) {
2071 case BitstreamEntry::SubBlock: // Handled for us already.
2072 case BitstreamEntry::Error:
2073 return Error("malformed metadata block");
2074 case BitstreamEntry::EndBlock:
2076 case BitstreamEntry::Record:
2077 // The interesting case.
2081 // Read a metadata attachment record.
2083 switch (Stream.readRecord(Entry.ID, Record)) {
2084 default: // Default behavior: ignore.
2086 case bitc::METADATA_ATTACHMENT: {
2087 unsigned RecordLength = Record.size();
2088 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2089 return Error ("Invalid METADATA_ATTACHMENT reader!");
2090 Instruction *Inst = InstructionList[Record[0]];
2091 for (unsigned i = 1; i != RecordLength; i = i+2) {
2092 unsigned Kind = Record[i];
2093 DenseMap<unsigned, unsigned>::iterator I =
2094 MDKindMap.find(Kind);
2095 if (I == MDKindMap.end())
2096 return Error("Invalid metadata kind ID");
2097 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2098 Inst->setMetadata(I->second, cast<MDNode>(Node));
2106 /// ParseFunctionBody - Lazily parse the specified function body block.
2107 bool BitcodeReader::ParseFunctionBody(Function *F) {
2108 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2109 return Error("Malformed block record");
2111 InstructionList.clear();
2112 unsigned ModuleValueListSize = ValueList.size();
2113 unsigned ModuleMDValueListSize = MDValueList.size();
2115 // Add all the function arguments to the value table.
2116 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2117 ValueList.push_back(I);
2119 unsigned NextValueNo = ValueList.size();
2120 BasicBlock *CurBB = 0;
2121 unsigned CurBBNo = 0;
2125 // Read all the records.
2126 SmallVector<uint64_t, 64> Record;
2128 BitstreamEntry Entry = Stream.advance();
2130 switch (Entry.Kind) {
2131 case BitstreamEntry::Error:
2132 return Error("Bitcode error in function block");
2133 case BitstreamEntry::EndBlock:
2134 goto OutOfRecordLoop;
2136 case BitstreamEntry::SubBlock:
2138 default: // Skip unknown content.
2139 if (Stream.SkipBlock())
2140 return Error("Malformed block record");
2142 case bitc::CONSTANTS_BLOCK_ID:
2143 if (ParseConstants()) return true;
2144 NextValueNo = ValueList.size();
2146 case bitc::VALUE_SYMTAB_BLOCK_ID:
2147 if (ParseValueSymbolTable()) return true;
2149 case bitc::METADATA_ATTACHMENT_ID:
2150 if (ParseMetadataAttachment()) return true;
2152 case bitc::METADATA_BLOCK_ID:
2153 if (ParseMetadata()) return true;
2158 case BitstreamEntry::Record:
2159 // The interesting case.
2166 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2168 default: // Default behavior: reject
2169 return Error("Unknown instruction");
2170 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2171 if (Record.size() < 1 || Record[0] == 0)
2172 return Error("Invalid DECLAREBLOCKS record");
2173 // Create all the basic blocks for the function.
2174 FunctionBBs.resize(Record[0]);
2175 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2176 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2177 CurBB = FunctionBBs[0];
2180 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2181 // This record indicates that the last instruction is at the same
2182 // location as the previous instruction with a location.
2185 // Get the last instruction emitted.
2186 if (CurBB && !CurBB->empty())
2188 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2189 !FunctionBBs[CurBBNo-1]->empty())
2190 I = &FunctionBBs[CurBBNo-1]->back();
2192 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2193 I->setDebugLoc(LastLoc);
2197 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2198 I = 0; // Get the last instruction emitted.
2199 if (CurBB && !CurBB->empty())
2201 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2202 !FunctionBBs[CurBBNo-1]->empty())
2203 I = &FunctionBBs[CurBBNo-1]->back();
2204 if (I == 0 || Record.size() < 4)
2205 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2207 unsigned Line = Record[0], Col = Record[1];
2208 unsigned ScopeID = Record[2], IAID = Record[3];
2210 MDNode *Scope = 0, *IA = 0;
2211 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2212 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2213 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2214 I->setDebugLoc(LastLoc);
2219 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2222 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2223 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2224 OpNum+1 > Record.size())
2225 return Error("Invalid BINOP record");
2227 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2228 if (Opc == -1) return Error("Invalid BINOP record");
2229 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2230 InstructionList.push_back(I);
2231 if (OpNum < Record.size()) {
2232 if (Opc == Instruction::Add ||
2233 Opc == Instruction::Sub ||
2234 Opc == Instruction::Mul ||
2235 Opc == Instruction::Shl) {
2236 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2237 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2238 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2239 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2240 } else if (Opc == Instruction::SDiv ||
2241 Opc == Instruction::UDiv ||
2242 Opc == Instruction::LShr ||
2243 Opc == Instruction::AShr) {
2244 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2245 cast<BinaryOperator>(I)->setIsExact(true);
2246 } else if (isa<FPMathOperator>(I)) {
2248 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2249 FMF.setUnsafeAlgebra();
2250 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2252 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2254 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2255 FMF.setNoSignedZeros();
2256 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2257 FMF.setAllowReciprocal();
2259 I->setFastMathFlags(FMF);
2265 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2268 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2269 OpNum+2 != Record.size())
2270 return Error("Invalid CAST record");
2272 Type *ResTy = getTypeByID(Record[OpNum]);
2273 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2274 if (Opc == -1 || ResTy == 0)
2275 return Error("Invalid CAST record");
2276 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2277 InstructionList.push_back(I);
2280 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2281 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2284 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2285 return Error("Invalid GEP record");
2287 SmallVector<Value*, 16> GEPIdx;
2288 while (OpNum != Record.size()) {
2290 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2291 return Error("Invalid GEP record");
2292 GEPIdx.push_back(Op);
2295 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2296 InstructionList.push_back(I);
2297 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2298 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2302 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2303 // EXTRACTVAL: [opty, opval, n x indices]
2306 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2307 return Error("Invalid EXTRACTVAL record");
2309 SmallVector<unsigned, 4> EXTRACTVALIdx;
2310 for (unsigned RecSize = Record.size();
2311 OpNum != RecSize; ++OpNum) {
2312 uint64_t Index = Record[OpNum];
2313 if ((unsigned)Index != Index)
2314 return Error("Invalid EXTRACTVAL index");
2315 EXTRACTVALIdx.push_back((unsigned)Index);
2318 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2319 InstructionList.push_back(I);
2323 case bitc::FUNC_CODE_INST_INSERTVAL: {
2324 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2327 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2328 return Error("Invalid INSERTVAL record");
2330 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2331 return Error("Invalid INSERTVAL record");
2333 SmallVector<unsigned, 4> INSERTVALIdx;
2334 for (unsigned RecSize = Record.size();
2335 OpNum != RecSize; ++OpNum) {
2336 uint64_t Index = Record[OpNum];
2337 if ((unsigned)Index != Index)
2338 return Error("Invalid INSERTVAL index");
2339 INSERTVALIdx.push_back((unsigned)Index);
2342 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2343 InstructionList.push_back(I);
2347 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2348 // obsolete form of select
2349 // handles select i1 ... in old bitcode
2351 Value *TrueVal, *FalseVal, *Cond;
2352 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2353 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2354 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2355 return Error("Invalid SELECT record");
2357 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2358 InstructionList.push_back(I);
2362 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2363 // new form of select
2364 // handles select i1 or select [N x i1]
2366 Value *TrueVal, *FalseVal, *Cond;
2367 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2368 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2369 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2370 return Error("Invalid SELECT record");
2372 // select condition can be either i1 or [N x i1]
2373 if (VectorType* vector_type =
2374 dyn_cast<VectorType>(Cond->getType())) {
2376 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2377 return Error("Invalid SELECT condition type");
2380 if (Cond->getType() != Type::getInt1Ty(Context))
2381 return Error("Invalid SELECT condition type");
2384 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2385 InstructionList.push_back(I);
2389 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2392 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2393 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2394 return Error("Invalid EXTRACTELT record");
2395 I = ExtractElementInst::Create(Vec, Idx);
2396 InstructionList.push_back(I);
2400 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2402 Value *Vec, *Elt, *Idx;
2403 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2404 popValue(Record, OpNum, NextValueNo,
2405 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2406 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2407 return Error("Invalid INSERTELT record");
2408 I = InsertElementInst::Create(Vec, Elt, Idx);
2409 InstructionList.push_back(I);
2413 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2415 Value *Vec1, *Vec2, *Mask;
2416 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2417 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2418 return Error("Invalid SHUFFLEVEC record");
2420 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2421 return Error("Invalid SHUFFLEVEC record");
2422 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2423 InstructionList.push_back(I);
2427 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2428 // Old form of ICmp/FCmp returning bool
2429 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2430 // both legal on vectors but had different behaviour.
2431 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2432 // FCmp/ICmp returning bool or vector of bool
2436 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2437 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2438 OpNum+1 != Record.size())
2439 return Error("Invalid CMP record");
2441 if (LHS->getType()->isFPOrFPVectorTy())
2442 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2444 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2445 InstructionList.push_back(I);
2449 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2451 unsigned Size = Record.size();
2453 I = ReturnInst::Create(Context);
2454 InstructionList.push_back(I);
2460 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2461 return Error("Invalid RET record");
2462 if (OpNum != Record.size())
2463 return Error("Invalid RET record");
2465 I = ReturnInst::Create(Context, Op);
2466 InstructionList.push_back(I);
2469 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2470 if (Record.size() != 1 && Record.size() != 3)
2471 return Error("Invalid BR record");
2472 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2474 return Error("Invalid BR record");
2476 if (Record.size() == 1) {
2477 I = BranchInst::Create(TrueDest);
2478 InstructionList.push_back(I);
2481 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2482 Value *Cond = getValue(Record, 2, NextValueNo,
2483 Type::getInt1Ty(Context));
2484 if (FalseDest == 0 || Cond == 0)
2485 return Error("Invalid BR record");
2486 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2487 InstructionList.push_back(I);
2491 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2493 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2494 // New SwitchInst format with case ranges.
2496 Type *OpTy = getTypeByID(Record[1]);
2497 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2499 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2500 BasicBlock *Default = getBasicBlock(Record[3]);
2501 if (OpTy == 0 || Cond == 0 || Default == 0)
2502 return Error("Invalid SWITCH record");
2504 unsigned NumCases = Record[4];
2506 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2507 InstructionList.push_back(SI);
2509 unsigned CurIdx = 5;
2510 for (unsigned i = 0; i != NumCases; ++i) {
2511 IntegersSubsetToBB CaseBuilder;
2512 unsigned NumItems = Record[CurIdx++];
2513 for (unsigned ci = 0; ci != NumItems; ++ci) {
2514 bool isSingleNumber = Record[CurIdx++];
2517 unsigned ActiveWords = 1;
2518 if (ValueBitWidth > 64)
2519 ActiveWords = Record[CurIdx++];
2520 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2522 CurIdx += ActiveWords;
2524 if (!isSingleNumber) {
2526 if (ValueBitWidth > 64)
2527 ActiveWords = Record[CurIdx++];
2529 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2532 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2533 IntItem::fromType(OpTy, High));
2534 CurIdx += ActiveWords;
2536 CaseBuilder.add(IntItem::fromType(OpTy, Low));
2538 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2539 IntegersSubset Case = CaseBuilder.getCase();
2540 SI->addCase(Case, DestBB);
2542 uint16_t Hash = SI->hash();
2543 if (Hash != (Record[0] & 0xFFFF))
2544 return Error("Invalid SWITCH record");
2549 // Old SwitchInst format without case ranges.
2551 if (Record.size() < 3 || (Record.size() & 1) == 0)
2552 return Error("Invalid SWITCH record");
2553 Type *OpTy = getTypeByID(Record[0]);
2554 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2555 BasicBlock *Default = getBasicBlock(Record[2]);
2556 if (OpTy == 0 || Cond == 0 || Default == 0)
2557 return Error("Invalid SWITCH record");
2558 unsigned NumCases = (Record.size()-3)/2;
2559 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2560 InstructionList.push_back(SI);
2561 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2562 ConstantInt *CaseVal =
2563 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2564 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2565 if (CaseVal == 0 || DestBB == 0) {
2567 return Error("Invalid SWITCH record!");
2569 SI->addCase(CaseVal, DestBB);
2574 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2575 if (Record.size() < 2)
2576 return Error("Invalid INDIRECTBR record");
2577 Type *OpTy = getTypeByID(Record[0]);
2578 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2579 if (OpTy == 0 || Address == 0)
2580 return Error("Invalid INDIRECTBR record");
2581 unsigned NumDests = Record.size()-2;
2582 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2583 InstructionList.push_back(IBI);
2584 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2585 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2586 IBI->addDestination(DestBB);
2589 return Error("Invalid INDIRECTBR record!");
2596 case bitc::FUNC_CODE_INST_INVOKE: {
2597 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2598 if (Record.size() < 4) return Error("Invalid INVOKE record");
2599 AttributeSet PAL = getAttributes(Record[0]);
2600 unsigned CCInfo = Record[1];
2601 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2602 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2606 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2607 return Error("Invalid INVOKE record");
2609 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2610 FunctionType *FTy = !CalleeTy ? 0 :
2611 dyn_cast<FunctionType>(CalleeTy->getElementType());
2613 // Check that the right number of fixed parameters are here.
2614 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2615 Record.size() < OpNum+FTy->getNumParams())
2616 return Error("Invalid INVOKE record");
2618 SmallVector<Value*, 16> Ops;
2619 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2620 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2621 FTy->getParamType(i)));
2622 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2625 if (!FTy->isVarArg()) {
2626 if (Record.size() != OpNum)
2627 return Error("Invalid INVOKE record");
2629 // Read type/value pairs for varargs params.
2630 while (OpNum != Record.size()) {
2632 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2633 return Error("Invalid INVOKE record");
2638 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2639 InstructionList.push_back(I);
2640 cast<InvokeInst>(I)->setCallingConv(
2641 static_cast<CallingConv::ID>(CCInfo));
2642 cast<InvokeInst>(I)->setAttributes(PAL);
2645 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2648 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2649 return Error("Invalid RESUME record");
2650 I = ResumeInst::Create(Val);
2651 InstructionList.push_back(I);
2654 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2655 I = new UnreachableInst(Context);
2656 InstructionList.push_back(I);
2658 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2659 if (Record.size() < 1 || ((Record.size()-1)&1))
2660 return Error("Invalid PHI record");
2661 Type *Ty = getTypeByID(Record[0]);
2662 if (!Ty) return Error("Invalid PHI record");
2664 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2665 InstructionList.push_back(PN);
2667 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2669 // With the new function encoding, it is possible that operands have
2670 // negative IDs (for forward references). Use a signed VBR
2671 // representation to keep the encoding small.
2673 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2675 V = getValue(Record, 1+i, NextValueNo, Ty);
2676 BasicBlock *BB = getBasicBlock(Record[2+i]);
2677 if (!V || !BB) return Error("Invalid PHI record");
2678 PN->addIncoming(V, BB);
2684 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2685 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2687 if (Record.size() < 4)
2688 return Error("Invalid LANDINGPAD record");
2689 Type *Ty = getTypeByID(Record[Idx++]);
2690 if (!Ty) return Error("Invalid LANDINGPAD record");
2692 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2693 return Error("Invalid LANDINGPAD record");
2695 bool IsCleanup = !!Record[Idx++];
2696 unsigned NumClauses = Record[Idx++];
2697 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2698 LP->setCleanup(IsCleanup);
2699 for (unsigned J = 0; J != NumClauses; ++J) {
2700 LandingPadInst::ClauseType CT =
2701 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2704 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2706 return Error("Invalid LANDINGPAD record");
2709 assert((CT != LandingPadInst::Catch ||
2710 !isa<ArrayType>(Val->getType())) &&
2711 "Catch clause has a invalid type!");
2712 assert((CT != LandingPadInst::Filter ||
2713 isa<ArrayType>(Val->getType())) &&
2714 "Filter clause has invalid type!");
2719 InstructionList.push_back(I);
2723 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2724 if (Record.size() != 4)
2725 return Error("Invalid ALLOCA record");
2727 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2728 Type *OpTy = getTypeByID(Record[1]);
2729 Value *Size = getFnValueByID(Record[2], OpTy);
2730 unsigned Align = Record[3];
2731 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2732 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2733 InstructionList.push_back(I);
2736 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2739 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2740 OpNum+2 != Record.size())
2741 return Error("Invalid LOAD record");
2743 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2744 InstructionList.push_back(I);
2747 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2748 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2751 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2752 OpNum+4 != Record.size())
2753 return Error("Invalid LOADATOMIC record");
2756 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2757 if (Ordering == NotAtomic || Ordering == Release ||
2758 Ordering == AcquireRelease)
2759 return Error("Invalid LOADATOMIC record");
2760 if (Ordering != NotAtomic && Record[OpNum] == 0)
2761 return Error("Invalid LOADATOMIC record");
2762 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2764 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2765 Ordering, SynchScope);
2766 InstructionList.push_back(I);
2769 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2772 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2773 popValue(Record, OpNum, NextValueNo,
2774 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2775 OpNum+2 != Record.size())
2776 return Error("Invalid STORE record");
2778 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2779 InstructionList.push_back(I);
2782 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2783 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2786 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2787 popValue(Record, OpNum, NextValueNo,
2788 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2789 OpNum+4 != Record.size())
2790 return Error("Invalid STOREATOMIC record");
2792 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2793 if (Ordering == NotAtomic || Ordering == Acquire ||
2794 Ordering == AcquireRelease)
2795 return Error("Invalid STOREATOMIC record");
2796 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2797 if (Ordering != NotAtomic && Record[OpNum] == 0)
2798 return Error("Invalid STOREATOMIC record");
2800 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2801 Ordering, SynchScope);
2802 InstructionList.push_back(I);
2805 case bitc::FUNC_CODE_INST_CMPXCHG: {
2806 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2808 Value *Ptr, *Cmp, *New;
2809 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2810 popValue(Record, OpNum, NextValueNo,
2811 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2812 popValue(Record, OpNum, NextValueNo,
2813 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2814 OpNum+3 != Record.size())
2815 return Error("Invalid CMPXCHG record");
2816 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2817 if (Ordering == NotAtomic || Ordering == Unordered)
2818 return Error("Invalid CMPXCHG record");
2819 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2820 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2821 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2822 InstructionList.push_back(I);
2825 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2826 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2829 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2830 popValue(Record, OpNum, NextValueNo,
2831 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2832 OpNum+4 != Record.size())
2833 return Error("Invalid ATOMICRMW record");
2834 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2835 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2836 Operation > AtomicRMWInst::LAST_BINOP)
2837 return Error("Invalid ATOMICRMW record");
2838 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2839 if (Ordering == NotAtomic || Ordering == Unordered)
2840 return Error("Invalid ATOMICRMW record");
2841 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2842 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2843 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2844 InstructionList.push_back(I);
2847 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2848 if (2 != Record.size())
2849 return Error("Invalid FENCE record");
2850 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2851 if (Ordering == NotAtomic || Ordering == Unordered ||
2852 Ordering == Monotonic)
2853 return Error("Invalid FENCE record");
2854 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2855 I = new FenceInst(Context, Ordering, SynchScope);
2856 InstructionList.push_back(I);
2859 case bitc::FUNC_CODE_INST_CALL: {
2860 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2861 if (Record.size() < 3)
2862 return Error("Invalid CALL record");
2864 AttributeSet PAL = getAttributes(Record[0]);
2865 unsigned CCInfo = Record[1];
2869 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2870 return Error("Invalid CALL record");
2872 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2873 FunctionType *FTy = 0;
2874 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2875 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2876 return Error("Invalid CALL record");
2878 SmallVector<Value*, 16> Args;
2879 // Read the fixed params.
2880 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2881 if (FTy->getParamType(i)->isLabelTy())
2882 Args.push_back(getBasicBlock(Record[OpNum]));
2884 Args.push_back(getValue(Record, OpNum, NextValueNo,
2885 FTy->getParamType(i)));
2886 if (Args.back() == 0) return Error("Invalid CALL record");
2889 // Read type/value pairs for varargs params.
2890 if (!FTy->isVarArg()) {
2891 if (OpNum != Record.size())
2892 return Error("Invalid CALL record");
2894 while (OpNum != Record.size()) {
2896 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2897 return Error("Invalid CALL record");
2902 I = CallInst::Create(Callee, Args);
2903 InstructionList.push_back(I);
2904 cast<CallInst>(I)->setCallingConv(
2905 static_cast<CallingConv::ID>(CCInfo>>1));
2906 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2907 cast<CallInst>(I)->setAttributes(PAL);
2910 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2911 if (Record.size() < 3)
2912 return Error("Invalid VAARG record");
2913 Type *OpTy = getTypeByID(Record[0]);
2914 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2915 Type *ResTy = getTypeByID(Record[2]);
2916 if (!OpTy || !Op || !ResTy)
2917 return Error("Invalid VAARG record");
2918 I = new VAArgInst(Op, ResTy);
2919 InstructionList.push_back(I);
2924 // Add instruction to end of current BB. If there is no current BB, reject
2928 return Error("Invalid instruction with no BB");
2930 CurBB->getInstList().push_back(I);
2932 // If this was a terminator instruction, move to the next block.
2933 if (isa<TerminatorInst>(I)) {
2935 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2938 // Non-void values get registered in the value table for future use.
2939 if (I && !I->getType()->isVoidTy())
2940 ValueList.AssignValue(I, NextValueNo++);
2945 // Check the function list for unresolved values.
2946 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2947 if (A->getParent() == 0) {
2948 // We found at least one unresolved value. Nuke them all to avoid leaks.
2949 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2950 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2951 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2955 return Error("Never resolved value found in function!");
2959 // FIXME: Check for unresolved forward-declared metadata references
2960 // and clean up leaks.
2962 // See if anything took the address of blocks in this function. If so,
2963 // resolve them now.
2964 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2965 BlockAddrFwdRefs.find(F);
2966 if (BAFRI != BlockAddrFwdRefs.end()) {
2967 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2968 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2969 unsigned BlockIdx = RefList[i].first;
2970 if (BlockIdx >= FunctionBBs.size())
2971 return Error("Invalid blockaddress block #");
2973 GlobalVariable *FwdRef = RefList[i].second;
2974 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2975 FwdRef->eraseFromParent();
2978 BlockAddrFwdRefs.erase(BAFRI);
2981 // Trim the value list down to the size it was before we parsed this function.
2982 ValueList.shrinkTo(ModuleValueListSize);
2983 MDValueList.shrinkTo(ModuleMDValueListSize);
2984 std::vector<BasicBlock*>().swap(FunctionBBs);
2988 /// FindFunctionInStream - Find the function body in the bitcode stream
2989 bool BitcodeReader::FindFunctionInStream(Function *F,
2990 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2991 while (DeferredFunctionInfoIterator->second == 0) {
2992 if (Stream.AtEndOfStream())
2993 return Error("Could not find Function in stream");
2994 // ParseModule will parse the next body in the stream and set its
2995 // position in the DeferredFunctionInfo map.
2996 if (ParseModule(true)) return true;
3001 //===----------------------------------------------------------------------===//
3002 // GVMaterializer implementation
3003 //===----------------------------------------------------------------------===//
3006 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3007 if (const Function *F = dyn_cast<Function>(GV)) {
3008 return F->isDeclaration() &&
3009 DeferredFunctionInfo.count(const_cast<Function*>(F));
3014 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3015 Function *F = dyn_cast<Function>(GV);
3016 // If it's not a function or is already material, ignore the request.
3017 if (!F || !F->isMaterializable()) return false;
3019 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3020 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3021 // If its position is recorded as 0, its body is somewhere in the stream
3022 // but we haven't seen it yet.
3023 if (DFII->second == 0)
3024 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
3026 // Move the bit stream to the saved position of the deferred function body.
3027 Stream.JumpToBit(DFII->second);
3029 if (ParseFunctionBody(F)) {
3030 if (ErrInfo) *ErrInfo = ErrorString;
3034 // Upgrade any old intrinsic calls in the function.
3035 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3036 E = UpgradedIntrinsics.end(); I != E; ++I) {
3037 if (I->first != I->second) {
3038 for (Value::use_iterator UI = I->first->use_begin(),
3039 UE = I->first->use_end(); UI != UE; ) {
3040 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3041 UpgradeIntrinsicCall(CI, I->second);
3049 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3050 const Function *F = dyn_cast<Function>(GV);
3051 if (!F || F->isDeclaration())
3053 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3056 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3057 Function *F = dyn_cast<Function>(GV);
3058 // If this function isn't dematerializable, this is a noop.
3059 if (!F || !isDematerializable(F))
3062 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3064 // Just forget the function body, we can remat it later.
3069 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3070 assert(M == TheModule &&
3071 "Can only Materialize the Module this BitcodeReader is attached to.");
3072 // Iterate over the module, deserializing any functions that are still on
3074 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3076 if (F->isMaterializable() &&
3077 Materialize(F, ErrInfo))
3080 // At this point, if there are any function bodies, the current bit is
3081 // pointing to the END_BLOCK record after them. Now make sure the rest
3082 // of the bits in the module have been read.
3086 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3087 // delete the old functions to clean up. We can't do this unless the entire
3088 // module is materialized because there could always be another function body
3089 // with calls to the old function.
3090 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3091 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3092 if (I->first != I->second) {
3093 for (Value::use_iterator UI = I->first->use_begin(),
3094 UE = I->first->use_end(); UI != UE; ) {
3095 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3096 UpgradeIntrinsicCall(CI, I->second);
3098 if (!I->first->use_empty())
3099 I->first->replaceAllUsesWith(I->second);
3100 I->first->eraseFromParent();
3103 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3108 bool BitcodeReader::InitStream() {
3109 if (LazyStreamer) return InitLazyStream();
3110 return InitStreamFromBuffer();
3113 bool BitcodeReader::InitStreamFromBuffer() {
3114 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3115 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3117 if (Buffer->getBufferSize() & 3) {
3118 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3119 return Error("Invalid bitcode signature");
3121 return Error("Bitcode stream should be a multiple of 4 bytes in length");
3124 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3125 // The magic number is 0x0B17C0DE stored in little endian.
3126 if (isBitcodeWrapper(BufPtr, BufEnd))
3127 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3128 return Error("Invalid bitcode wrapper header");
3130 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3131 Stream.init(*StreamFile);
3136 bool BitcodeReader::InitLazyStream() {
3137 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3139 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3140 StreamFile.reset(new BitstreamReader(Bytes));
3141 Stream.init(*StreamFile);
3143 unsigned char buf[16];
3144 if (Bytes->readBytes(0, 16, buf) == -1)
3145 return Error("Bitcode stream must be at least 16 bytes in length");
3147 if (!isBitcode(buf, buf + 16))
3148 return Error("Invalid bitcode signature");
3150 if (isBitcodeWrapper(buf, buf + 4)) {
3151 const unsigned char *bitcodeStart = buf;
3152 const unsigned char *bitcodeEnd = buf + 16;
3153 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3154 Bytes->dropLeadingBytes(bitcodeStart - buf);
3155 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3160 //===----------------------------------------------------------------------===//
3161 // External interface
3162 //===----------------------------------------------------------------------===//
3164 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3166 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3167 LLVMContext& Context,
3168 std::string *ErrMsg) {
3169 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3170 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3171 M->setMaterializer(R);
3172 if (R->ParseBitcodeInto(M)) {
3174 *ErrMsg = R->getErrorString();
3176 delete M; // Also deletes R.
3179 // Have the BitcodeReader dtor delete 'Buffer'.
3180 R->setBufferOwned(true);
3182 R->materializeForwardReferencedFunctions();
3188 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3189 DataStreamer *streamer,
3190 LLVMContext &Context,
3191 std::string *ErrMsg) {
3192 Module *M = new Module(name, Context);
3193 BitcodeReader *R = new BitcodeReader(streamer, Context);
3194 M->setMaterializer(R);
3195 if (R->ParseBitcodeInto(M)) {
3197 *ErrMsg = R->getErrorString();
3198 delete M; // Also deletes R.
3201 R->setBufferOwned(false); // no buffer to delete
3205 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3206 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3207 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3208 std::string *ErrMsg){
3209 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3212 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3213 // there was an error.
3214 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3216 // Read in the entire module, and destroy the BitcodeReader.
3217 if (M->MaterializeAllPermanently(ErrMsg)) {
3222 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3223 // written. We must defer until the Module has been fully materialized.
3228 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3229 LLVMContext& Context,
3230 std::string *ErrMsg) {
3231 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3232 // Don't let the BitcodeReader dtor delete 'Buffer'.
3233 R->setBufferOwned(false);
3235 std::string Triple("");
3236 if (R->ParseTriple(Triple))
3238 *ErrMsg = R->getErrorString();