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/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
41 void BitcodeReader::FreeState() {
43 std::vector<Type*>().swap(TypeList);
46 std::vector<Comdat *>().swap(ComdatList);
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::ExternalLinkage; // Obsolete DLLImportLinkage
83 case 6: return GlobalValue::ExternalLinkage; // Obsolete 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;
91 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
93 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
97 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
99 default: // Map unknown visibilities to default.
100 case 0: return GlobalValue::DefaultVisibility;
101 case 1: return GlobalValue::HiddenVisibility;
102 case 2: return GlobalValue::ProtectedVisibility;
106 static GlobalValue::DLLStorageClassTypes
107 GetDecodedDLLStorageClass(unsigned Val) {
109 default: // Map unknown values to default.
110 case 0: return GlobalValue::DefaultStorageClass;
111 case 1: return GlobalValue::DLLImportStorageClass;
112 case 2: return GlobalValue::DLLExportStorageClass;
116 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
118 case 0: return GlobalVariable::NotThreadLocal;
119 default: // Map unknown non-zero value to general dynamic.
120 case 1: return GlobalVariable::GeneralDynamicTLSModel;
121 case 2: return GlobalVariable::LocalDynamicTLSModel;
122 case 3: return GlobalVariable::InitialExecTLSModel;
123 case 4: return GlobalVariable::LocalExecTLSModel;
127 static int GetDecodedCastOpcode(unsigned Val) {
130 case bitc::CAST_TRUNC : return Instruction::Trunc;
131 case bitc::CAST_ZEXT : return Instruction::ZExt;
132 case bitc::CAST_SEXT : return Instruction::SExt;
133 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
134 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
135 case bitc::CAST_UITOFP : return Instruction::UIToFP;
136 case bitc::CAST_SITOFP : return Instruction::SIToFP;
137 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
138 case bitc::CAST_FPEXT : return Instruction::FPExt;
139 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
140 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
141 case bitc::CAST_BITCAST : return Instruction::BitCast;
142 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
145 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
148 case bitc::BINOP_ADD:
149 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
150 case bitc::BINOP_SUB:
151 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
152 case bitc::BINOP_MUL:
153 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
154 case bitc::BINOP_UDIV: return Instruction::UDiv;
155 case bitc::BINOP_SDIV:
156 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
157 case bitc::BINOP_UREM: return Instruction::URem;
158 case bitc::BINOP_SREM:
159 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
160 case bitc::BINOP_SHL: return Instruction::Shl;
161 case bitc::BINOP_LSHR: return Instruction::LShr;
162 case bitc::BINOP_ASHR: return Instruction::AShr;
163 case bitc::BINOP_AND: return Instruction::And;
164 case bitc::BINOP_OR: return Instruction::Or;
165 case bitc::BINOP_XOR: return Instruction::Xor;
169 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
171 default: return AtomicRMWInst::BAD_BINOP;
172 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
173 case bitc::RMW_ADD: return AtomicRMWInst::Add;
174 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
175 case bitc::RMW_AND: return AtomicRMWInst::And;
176 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
177 case bitc::RMW_OR: return AtomicRMWInst::Or;
178 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
179 case bitc::RMW_MAX: return AtomicRMWInst::Max;
180 case bitc::RMW_MIN: return AtomicRMWInst::Min;
181 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
182 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
186 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
188 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
189 case bitc::ORDERING_UNORDERED: return Unordered;
190 case bitc::ORDERING_MONOTONIC: return Monotonic;
191 case bitc::ORDERING_ACQUIRE: return Acquire;
192 case bitc::ORDERING_RELEASE: return Release;
193 case bitc::ORDERING_ACQREL: return AcquireRelease;
194 default: // Map unknown orderings to sequentially-consistent.
195 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
199 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
201 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
202 default: // Map unknown scopes to cross-thread.
203 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
207 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
209 default: // Map unknown selection kinds to any.
210 case bitc::COMDAT_SELECTION_KIND_ANY:
212 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
213 return Comdat::ExactMatch;
214 case bitc::COMDAT_SELECTION_KIND_LARGEST:
215 return Comdat::Largest;
216 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
217 return Comdat::NoDuplicates;
218 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
219 return Comdat::SameSize;
223 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
225 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
226 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
232 /// @brief A class for maintaining the slot number definition
233 /// as a placeholder for the actual definition for forward constants defs.
234 class ConstantPlaceHolder : public ConstantExpr {
235 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
237 // allocate space for exactly one operand
238 void *operator new(size_t s) {
239 return User::operator new(s, 1);
241 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
242 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
243 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
246 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
247 static bool classof(const Value *V) {
248 return isa<ConstantExpr>(V) &&
249 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
253 /// Provide fast operand accessors
254 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
258 // FIXME: can we inherit this from ConstantExpr?
260 struct OperandTraits<ConstantPlaceHolder> :
261 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
266 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
275 WeakVH &OldV = ValuePtrs[Idx];
281 // Handle constants and non-constants (e.g. instrs) differently for
283 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
284 ResolveConstants.push_back(std::make_pair(PHC, Idx));
287 // If there was a forward reference to this value, replace it.
288 Value *PrevVal = OldV;
289 OldV->replaceAllUsesWith(V);
295 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
300 if (Value *V = ValuePtrs[Idx]) {
301 assert(Ty == V->getType() && "Type mismatch in constant table!");
302 return cast<Constant>(V);
305 // Create and return a placeholder, which will later be RAUW'd.
306 Constant *C = new ConstantPlaceHolder(Ty, Context);
311 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
315 if (Value *V = ValuePtrs[Idx]) {
316 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
320 // No type specified, must be invalid reference.
321 if (!Ty) return nullptr;
323 // Create and return a placeholder, which will later be RAUW'd.
324 Value *V = new Argument(Ty);
329 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
330 /// resolves any forward references. The idea behind this is that we sometimes
331 /// get constants (such as large arrays) which reference *many* forward ref
332 /// constants. Replacing each of these causes a lot of thrashing when
333 /// building/reuniquing the constant. Instead of doing this, we look at all the
334 /// uses and rewrite all the place holders at once for any constant that uses
336 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
337 // Sort the values by-pointer so that they are efficient to look up with a
339 std::sort(ResolveConstants.begin(), ResolveConstants.end());
341 SmallVector<Constant*, 64> NewOps;
343 while (!ResolveConstants.empty()) {
344 Value *RealVal = operator[](ResolveConstants.back().second);
345 Constant *Placeholder = ResolveConstants.back().first;
346 ResolveConstants.pop_back();
348 // Loop over all users of the placeholder, updating them to reference the
349 // new value. If they reference more than one placeholder, update them all
351 while (!Placeholder->use_empty()) {
352 auto UI = Placeholder->user_begin();
355 // If the using object isn't uniqued, just update the operands. This
356 // handles instructions and initializers for global variables.
357 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
358 UI.getUse().set(RealVal);
362 // Otherwise, we have a constant that uses the placeholder. Replace that
363 // constant with a new constant that has *all* placeholder uses updated.
364 Constant *UserC = cast<Constant>(U);
365 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
368 if (!isa<ConstantPlaceHolder>(*I)) {
369 // Not a placeholder reference.
371 } else if (*I == Placeholder) {
372 // Common case is that it just references this one placeholder.
375 // Otherwise, look up the placeholder in ResolveConstants.
376 ResolveConstantsTy::iterator It =
377 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
378 std::pair<Constant*, unsigned>(cast<Constant>(*I),
380 assert(It != ResolveConstants.end() && It->first == *I);
381 NewOp = operator[](It->second);
384 NewOps.push_back(cast<Constant>(NewOp));
387 // Make the new constant.
389 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
390 NewC = ConstantArray::get(UserCA->getType(), NewOps);
391 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
392 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
393 } else if (isa<ConstantVector>(UserC)) {
394 NewC = ConstantVector::get(NewOps);
396 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
397 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
400 UserC->replaceAllUsesWith(NewC);
401 UserC->destroyConstant();
405 // Update all ValueHandles, they should be the only users at this point.
406 Placeholder->replaceAllUsesWith(RealVal);
411 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
420 WeakVH &OldV = MDValuePtrs[Idx];
426 // If there was a forward reference to this value, replace it.
427 MDNode *PrevVal = cast<MDNode>(OldV);
428 OldV->replaceAllUsesWith(V);
429 MDNode::deleteTemporary(PrevVal);
430 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
432 MDValuePtrs[Idx] = V;
435 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
439 if (Value *V = MDValuePtrs[Idx]) {
440 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
444 // Create and return a placeholder, which will later be RAUW'd.
445 Value *V = MDNode::getTemporary(Context, None);
446 MDValuePtrs[Idx] = V;
450 Type *BitcodeReader::getTypeByID(unsigned ID) {
451 // The type table size is always specified correctly.
452 if (ID >= TypeList.size())
455 if (Type *Ty = TypeList[ID])
458 // If we have a forward reference, the only possible case is when it is to a
459 // named struct. Just create a placeholder for now.
460 return TypeList[ID] = StructType::create(Context);
464 //===----------------------------------------------------------------------===//
465 // Functions for parsing blocks from the bitcode file
466 //===----------------------------------------------------------------------===//
469 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
470 /// been decoded from the given integer. This function must stay in sync with
471 /// 'encodeLLVMAttributesForBitcode'.
472 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
473 uint64_t EncodedAttrs) {
474 // FIXME: Remove in 4.0.
476 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
477 // the bits above 31 down by 11 bits.
478 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
479 assert((!Alignment || isPowerOf2_32(Alignment)) &&
480 "Alignment must be a power of two.");
483 B.addAlignmentAttr(Alignment);
484 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
485 (EncodedAttrs & 0xffff));
488 std::error_code BitcodeReader::ParseAttributeBlock() {
489 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
490 return Error(InvalidRecord);
492 if (!MAttributes.empty())
493 return Error(InvalidMultipleBlocks);
495 SmallVector<uint64_t, 64> Record;
497 SmallVector<AttributeSet, 8> Attrs;
499 // Read all the records.
501 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
503 switch (Entry.Kind) {
504 case BitstreamEntry::SubBlock: // Handled for us already.
505 case BitstreamEntry::Error:
506 return Error(MalformedBlock);
507 case BitstreamEntry::EndBlock:
508 return std::error_code();
509 case BitstreamEntry::Record:
510 // The interesting case.
516 switch (Stream.readRecord(Entry.ID, Record)) {
517 default: // Default behavior: ignore.
519 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
520 // FIXME: Remove in 4.0.
521 if (Record.size() & 1)
522 return Error(InvalidRecord);
524 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
526 decodeLLVMAttributesForBitcode(B, Record[i+1]);
527 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
530 MAttributes.push_back(AttributeSet::get(Context, Attrs));
534 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
535 for (unsigned i = 0, e = Record.size(); i != e; ++i)
536 Attrs.push_back(MAttributeGroups[Record[i]]);
538 MAttributes.push_back(AttributeSet::get(Context, Attrs));
546 // Returns Attribute::None on unrecognized codes.
547 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
550 return Attribute::None;
551 case bitc::ATTR_KIND_ALIGNMENT:
552 return Attribute::Alignment;
553 case bitc::ATTR_KIND_ALWAYS_INLINE:
554 return Attribute::AlwaysInline;
555 case bitc::ATTR_KIND_BUILTIN:
556 return Attribute::Builtin;
557 case bitc::ATTR_KIND_BY_VAL:
558 return Attribute::ByVal;
559 case bitc::ATTR_KIND_IN_ALLOCA:
560 return Attribute::InAlloca;
561 case bitc::ATTR_KIND_COLD:
562 return Attribute::Cold;
563 case bitc::ATTR_KIND_INLINE_HINT:
564 return Attribute::InlineHint;
565 case bitc::ATTR_KIND_IN_REG:
566 return Attribute::InReg;
567 case bitc::ATTR_KIND_JUMP_TABLE:
568 return Attribute::JumpTable;
569 case bitc::ATTR_KIND_MIN_SIZE:
570 return Attribute::MinSize;
571 case bitc::ATTR_KIND_NAKED:
572 return Attribute::Naked;
573 case bitc::ATTR_KIND_NEST:
574 return Attribute::Nest;
575 case bitc::ATTR_KIND_NO_ALIAS:
576 return Attribute::NoAlias;
577 case bitc::ATTR_KIND_NO_BUILTIN:
578 return Attribute::NoBuiltin;
579 case bitc::ATTR_KIND_NO_CAPTURE:
580 return Attribute::NoCapture;
581 case bitc::ATTR_KIND_NO_DUPLICATE:
582 return Attribute::NoDuplicate;
583 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
584 return Attribute::NoImplicitFloat;
585 case bitc::ATTR_KIND_NO_INLINE:
586 return Attribute::NoInline;
587 case bitc::ATTR_KIND_NON_LAZY_BIND:
588 return Attribute::NonLazyBind;
589 case bitc::ATTR_KIND_NON_NULL:
590 return Attribute::NonNull;
591 case bitc::ATTR_KIND_DEREFERENCEABLE:
592 return Attribute::Dereferenceable;
593 case bitc::ATTR_KIND_NO_RED_ZONE:
594 return Attribute::NoRedZone;
595 case bitc::ATTR_KIND_NO_RETURN:
596 return Attribute::NoReturn;
597 case bitc::ATTR_KIND_NO_UNWIND:
598 return Attribute::NoUnwind;
599 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
600 return Attribute::OptimizeForSize;
601 case bitc::ATTR_KIND_OPTIMIZE_NONE:
602 return Attribute::OptimizeNone;
603 case bitc::ATTR_KIND_READ_NONE:
604 return Attribute::ReadNone;
605 case bitc::ATTR_KIND_READ_ONLY:
606 return Attribute::ReadOnly;
607 case bitc::ATTR_KIND_RETURNED:
608 return Attribute::Returned;
609 case bitc::ATTR_KIND_RETURNS_TWICE:
610 return Attribute::ReturnsTwice;
611 case bitc::ATTR_KIND_S_EXT:
612 return Attribute::SExt;
613 case bitc::ATTR_KIND_STACK_ALIGNMENT:
614 return Attribute::StackAlignment;
615 case bitc::ATTR_KIND_STACK_PROTECT:
616 return Attribute::StackProtect;
617 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
618 return Attribute::StackProtectReq;
619 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
620 return Attribute::StackProtectStrong;
621 case bitc::ATTR_KIND_STRUCT_RET:
622 return Attribute::StructRet;
623 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
624 return Attribute::SanitizeAddress;
625 case bitc::ATTR_KIND_SANITIZE_THREAD:
626 return Attribute::SanitizeThread;
627 case bitc::ATTR_KIND_SANITIZE_MEMORY:
628 return Attribute::SanitizeMemory;
629 case bitc::ATTR_KIND_UW_TABLE:
630 return Attribute::UWTable;
631 case bitc::ATTR_KIND_Z_EXT:
632 return Attribute::ZExt;
636 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
637 Attribute::AttrKind *Kind) {
638 *Kind = GetAttrFromCode(Code);
639 if (*Kind == Attribute::None)
640 return Error(InvalidValue);
641 return std::error_code();
644 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
645 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
646 return Error(InvalidRecord);
648 if (!MAttributeGroups.empty())
649 return Error(InvalidMultipleBlocks);
651 SmallVector<uint64_t, 64> Record;
653 // Read all the records.
655 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
657 switch (Entry.Kind) {
658 case BitstreamEntry::SubBlock: // Handled for us already.
659 case BitstreamEntry::Error:
660 return Error(MalformedBlock);
661 case BitstreamEntry::EndBlock:
662 return std::error_code();
663 case BitstreamEntry::Record:
664 // The interesting case.
670 switch (Stream.readRecord(Entry.ID, Record)) {
671 default: // Default behavior: ignore.
673 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
674 if (Record.size() < 3)
675 return Error(InvalidRecord);
677 uint64_t GrpID = Record[0];
678 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
681 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
682 if (Record[i] == 0) { // Enum attribute
683 Attribute::AttrKind Kind;
684 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
687 B.addAttribute(Kind);
688 } else if (Record[i] == 1) { // Integer attribute
689 Attribute::AttrKind Kind;
690 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
692 if (Kind == Attribute::Alignment)
693 B.addAlignmentAttr(Record[++i]);
694 else if (Kind == Attribute::StackAlignment)
695 B.addStackAlignmentAttr(Record[++i]);
696 else if (Kind == Attribute::Dereferenceable)
697 B.addDereferenceableAttr(Record[++i]);
698 } else { // String attribute
699 assert((Record[i] == 3 || Record[i] == 4) &&
700 "Invalid attribute group entry");
701 bool HasValue = (Record[i++] == 4);
702 SmallString<64> KindStr;
703 SmallString<64> ValStr;
705 while (Record[i] != 0 && i != e)
706 KindStr += Record[i++];
707 assert(Record[i] == 0 && "Kind string not null terminated");
710 // Has a value associated with it.
711 ++i; // Skip the '0' that terminates the "kind" string.
712 while (Record[i] != 0 && i != e)
713 ValStr += Record[i++];
714 assert(Record[i] == 0 && "Value string not null terminated");
717 B.addAttribute(KindStr.str(), ValStr.str());
721 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
728 std::error_code BitcodeReader::ParseTypeTable() {
729 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
730 return Error(InvalidRecord);
732 return ParseTypeTableBody();
735 std::error_code BitcodeReader::ParseTypeTableBody() {
736 if (!TypeList.empty())
737 return Error(InvalidMultipleBlocks);
739 SmallVector<uint64_t, 64> Record;
740 unsigned NumRecords = 0;
742 SmallString<64> TypeName;
744 // Read all the records for this type table.
746 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
748 switch (Entry.Kind) {
749 case BitstreamEntry::SubBlock: // Handled for us already.
750 case BitstreamEntry::Error:
751 return Error(MalformedBlock);
752 case BitstreamEntry::EndBlock:
753 if (NumRecords != TypeList.size())
754 return Error(MalformedBlock);
755 return std::error_code();
756 case BitstreamEntry::Record:
757 // The interesting case.
763 Type *ResultTy = nullptr;
764 switch (Stream.readRecord(Entry.ID, Record)) {
766 return Error(InvalidValue);
767 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
768 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
769 // type list. This allows us to reserve space.
770 if (Record.size() < 1)
771 return Error(InvalidRecord);
772 TypeList.resize(Record[0]);
774 case bitc::TYPE_CODE_VOID: // VOID
775 ResultTy = Type::getVoidTy(Context);
777 case bitc::TYPE_CODE_HALF: // HALF
778 ResultTy = Type::getHalfTy(Context);
780 case bitc::TYPE_CODE_FLOAT: // FLOAT
781 ResultTy = Type::getFloatTy(Context);
783 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
784 ResultTy = Type::getDoubleTy(Context);
786 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
787 ResultTy = Type::getX86_FP80Ty(Context);
789 case bitc::TYPE_CODE_FP128: // FP128
790 ResultTy = Type::getFP128Ty(Context);
792 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
793 ResultTy = Type::getPPC_FP128Ty(Context);
795 case bitc::TYPE_CODE_LABEL: // LABEL
796 ResultTy = Type::getLabelTy(Context);
798 case bitc::TYPE_CODE_METADATA: // METADATA
799 ResultTy = Type::getMetadataTy(Context);
801 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
802 ResultTy = Type::getX86_MMXTy(Context);
804 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
805 if (Record.size() < 1)
806 return Error(InvalidRecord);
808 ResultTy = IntegerType::get(Context, Record[0]);
810 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
811 // [pointee type, address space]
812 if (Record.size() < 1)
813 return Error(InvalidRecord);
814 unsigned AddressSpace = 0;
815 if (Record.size() == 2)
816 AddressSpace = Record[1];
817 ResultTy = getTypeByID(Record[0]);
819 return Error(InvalidType);
820 ResultTy = PointerType::get(ResultTy, AddressSpace);
823 case bitc::TYPE_CODE_FUNCTION_OLD: {
824 // FIXME: attrid is dead, remove it in LLVM 4.0
825 // FUNCTION: [vararg, attrid, retty, paramty x N]
826 if (Record.size() < 3)
827 return Error(InvalidRecord);
828 SmallVector<Type*, 8> ArgTys;
829 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
830 if (Type *T = getTypeByID(Record[i]))
836 ResultTy = getTypeByID(Record[2]);
837 if (!ResultTy || ArgTys.size() < Record.size()-3)
838 return Error(InvalidType);
840 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
843 case bitc::TYPE_CODE_FUNCTION: {
844 // FUNCTION: [vararg, retty, paramty x N]
845 if (Record.size() < 2)
846 return Error(InvalidRecord);
847 SmallVector<Type*, 8> ArgTys;
848 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
849 if (Type *T = getTypeByID(Record[i]))
855 ResultTy = getTypeByID(Record[1]);
856 if (!ResultTy || ArgTys.size() < Record.size()-2)
857 return Error(InvalidType);
859 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
862 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
863 if (Record.size() < 1)
864 return Error(InvalidRecord);
865 SmallVector<Type*, 8> EltTys;
866 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
867 if (Type *T = getTypeByID(Record[i]))
872 if (EltTys.size() != Record.size()-1)
873 return Error(InvalidType);
874 ResultTy = StructType::get(Context, EltTys, Record[0]);
877 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
878 if (ConvertToString(Record, 0, TypeName))
879 return Error(InvalidRecord);
882 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
883 if (Record.size() < 1)
884 return Error(InvalidRecord);
886 if (NumRecords >= TypeList.size())
887 return Error(InvalidTYPETable);
889 // Check to see if this was forward referenced, if so fill in the temp.
890 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
892 Res->setName(TypeName);
893 TypeList[NumRecords] = nullptr;
894 } else // Otherwise, create a new struct.
895 Res = StructType::create(Context, TypeName);
898 SmallVector<Type*, 8> EltTys;
899 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
900 if (Type *T = getTypeByID(Record[i]))
905 if (EltTys.size() != Record.size()-1)
906 return Error(InvalidRecord);
907 Res->setBody(EltTys, Record[0]);
911 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
912 if (Record.size() != 1)
913 return Error(InvalidRecord);
915 if (NumRecords >= TypeList.size())
916 return Error(InvalidTYPETable);
918 // Check to see if this was forward referenced, if so fill in the temp.
919 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
921 Res->setName(TypeName);
922 TypeList[NumRecords] = nullptr;
923 } else // Otherwise, create a new struct with no body.
924 Res = StructType::create(Context, TypeName);
929 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
930 if (Record.size() < 2)
931 return Error(InvalidRecord);
932 if ((ResultTy = getTypeByID(Record[1])))
933 ResultTy = ArrayType::get(ResultTy, Record[0]);
935 return Error(InvalidType);
937 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
938 if (Record.size() < 2)
939 return Error(InvalidRecord);
940 if ((ResultTy = getTypeByID(Record[1])))
941 ResultTy = VectorType::get(ResultTy, Record[0]);
943 return Error(InvalidType);
947 if (NumRecords >= TypeList.size())
948 return Error(InvalidTYPETable);
949 assert(ResultTy && "Didn't read a type?");
950 assert(!TypeList[NumRecords] && "Already read type?");
951 TypeList[NumRecords++] = ResultTy;
955 std::error_code BitcodeReader::ParseValueSymbolTable() {
956 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
957 return Error(InvalidRecord);
959 SmallVector<uint64_t, 64> Record;
961 // Read all the records for this value table.
962 SmallString<128> ValueName;
964 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
966 switch (Entry.Kind) {
967 case BitstreamEntry::SubBlock: // Handled for us already.
968 case BitstreamEntry::Error:
969 return Error(MalformedBlock);
970 case BitstreamEntry::EndBlock:
971 return std::error_code();
972 case BitstreamEntry::Record:
973 // The interesting case.
979 switch (Stream.readRecord(Entry.ID, Record)) {
980 default: // Default behavior: unknown type.
982 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
983 if (ConvertToString(Record, 1, ValueName))
984 return Error(InvalidRecord);
985 unsigned ValueID = Record[0];
986 if (ValueID >= ValueList.size() || !ValueList[ValueID])
987 return Error(InvalidRecord);
988 Value *V = ValueList[ValueID];
990 V->setName(StringRef(ValueName.data(), ValueName.size()));
994 case bitc::VST_CODE_BBENTRY: {
995 if (ConvertToString(Record, 1, ValueName))
996 return Error(InvalidRecord);
997 BasicBlock *BB = getBasicBlock(Record[0]);
999 return Error(InvalidRecord);
1001 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1009 std::error_code BitcodeReader::ParseMetadata() {
1010 unsigned NextMDValueNo = MDValueList.size();
1012 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1013 return Error(InvalidRecord);
1015 SmallVector<uint64_t, 64> Record;
1017 // Read all the records.
1019 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1021 switch (Entry.Kind) {
1022 case BitstreamEntry::SubBlock: // Handled for us already.
1023 case BitstreamEntry::Error:
1024 return Error(MalformedBlock);
1025 case BitstreamEntry::EndBlock:
1026 return std::error_code();
1027 case BitstreamEntry::Record:
1028 // The interesting case.
1032 bool IsFunctionLocal = false;
1035 unsigned Code = Stream.readRecord(Entry.ID, Record);
1037 default: // Default behavior: ignore.
1039 case bitc::METADATA_NAME: {
1040 // Read name of the named metadata.
1041 SmallString<8> Name(Record.begin(), Record.end());
1043 Code = Stream.ReadCode();
1045 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1046 unsigned NextBitCode = Stream.readRecord(Code, Record);
1047 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1049 // Read named metadata elements.
1050 unsigned Size = Record.size();
1051 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1052 for (unsigned i = 0; i != Size; ++i) {
1053 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1055 return Error(InvalidRecord);
1056 NMD->addOperand(MD);
1060 case bitc::METADATA_FN_NODE:
1061 IsFunctionLocal = true;
1063 case bitc::METADATA_NODE: {
1064 if (Record.size() % 2 == 1)
1065 return Error(InvalidRecord);
1067 unsigned Size = Record.size();
1068 SmallVector<Value*, 8> Elts;
1069 for (unsigned i = 0; i != Size; i += 2) {
1070 Type *Ty = getTypeByID(Record[i]);
1072 return Error(InvalidRecord);
1073 if (Ty->isMetadataTy())
1074 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1075 else if (!Ty->isVoidTy())
1076 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1078 Elts.push_back(nullptr);
1080 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1081 IsFunctionLocal = false;
1082 MDValueList.AssignValue(V, NextMDValueNo++);
1085 case bitc::METADATA_STRING: {
1086 std::string String(Record.begin(), Record.end());
1087 llvm::UpgradeMDStringConstant(String);
1088 Value *V = MDString::get(Context, String);
1089 MDValueList.AssignValue(V, NextMDValueNo++);
1092 case bitc::METADATA_KIND: {
1093 if (Record.size() < 2)
1094 return Error(InvalidRecord);
1096 unsigned Kind = Record[0];
1097 SmallString<8> Name(Record.begin()+1, Record.end());
1099 unsigned NewKind = TheModule->getMDKindID(Name.str());
1100 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1101 return Error(ConflictingMETADATA_KINDRecords);
1108 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1109 /// the LSB for dense VBR encoding.
1110 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1115 // There is no such thing as -0 with integers. "-0" really means MININT.
1119 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1120 /// values and aliases that we can.
1121 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1122 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1123 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1124 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1126 GlobalInitWorklist.swap(GlobalInits);
1127 AliasInitWorklist.swap(AliasInits);
1128 FunctionPrefixWorklist.swap(FunctionPrefixes);
1130 while (!GlobalInitWorklist.empty()) {
1131 unsigned ValID = GlobalInitWorklist.back().second;
1132 if (ValID >= ValueList.size()) {
1133 // Not ready to resolve this yet, it requires something later in the file.
1134 GlobalInits.push_back(GlobalInitWorklist.back());
1136 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1137 GlobalInitWorklist.back().first->setInitializer(C);
1139 return Error(ExpectedConstant);
1141 GlobalInitWorklist.pop_back();
1144 while (!AliasInitWorklist.empty()) {
1145 unsigned ValID = AliasInitWorklist.back().second;
1146 if (ValID >= ValueList.size()) {
1147 AliasInits.push_back(AliasInitWorklist.back());
1149 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1150 AliasInitWorklist.back().first->setAliasee(C);
1152 return Error(ExpectedConstant);
1154 AliasInitWorklist.pop_back();
1157 while (!FunctionPrefixWorklist.empty()) {
1158 unsigned ValID = FunctionPrefixWorklist.back().second;
1159 if (ValID >= ValueList.size()) {
1160 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1162 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1163 FunctionPrefixWorklist.back().first->setPrefixData(C);
1165 return Error(ExpectedConstant);
1167 FunctionPrefixWorklist.pop_back();
1170 return std::error_code();
1173 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1174 SmallVector<uint64_t, 8> Words(Vals.size());
1175 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1176 BitcodeReader::decodeSignRotatedValue);
1178 return APInt(TypeBits, Words);
1181 std::error_code BitcodeReader::ParseConstants() {
1182 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1183 return Error(InvalidRecord);
1185 SmallVector<uint64_t, 64> Record;
1187 // Read all the records for this value table.
1188 Type *CurTy = Type::getInt32Ty(Context);
1189 unsigned NextCstNo = ValueList.size();
1191 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1193 switch (Entry.Kind) {
1194 case BitstreamEntry::SubBlock: // Handled for us already.
1195 case BitstreamEntry::Error:
1196 return Error(MalformedBlock);
1197 case BitstreamEntry::EndBlock:
1198 if (NextCstNo != ValueList.size())
1199 return Error(InvalidConstantReference);
1201 // Once all the constants have been read, go through and resolve forward
1203 ValueList.ResolveConstantForwardRefs();
1204 return std::error_code();
1205 case BitstreamEntry::Record:
1206 // The interesting case.
1213 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1215 default: // Default behavior: unknown constant
1216 case bitc::CST_CODE_UNDEF: // UNDEF
1217 V = UndefValue::get(CurTy);
1219 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1221 return Error(InvalidRecord);
1222 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1223 return Error(InvalidRecord);
1224 CurTy = TypeList[Record[0]];
1225 continue; // Skip the ValueList manipulation.
1226 case bitc::CST_CODE_NULL: // NULL
1227 V = Constant::getNullValue(CurTy);
1229 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1230 if (!CurTy->isIntegerTy() || Record.empty())
1231 return Error(InvalidRecord);
1232 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1234 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1235 if (!CurTy->isIntegerTy() || Record.empty())
1236 return Error(InvalidRecord);
1238 APInt VInt = ReadWideAPInt(Record,
1239 cast<IntegerType>(CurTy)->getBitWidth());
1240 V = ConstantInt::get(Context, VInt);
1244 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1246 return Error(InvalidRecord);
1247 if (CurTy->isHalfTy())
1248 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1249 APInt(16, (uint16_t)Record[0])));
1250 else if (CurTy->isFloatTy())
1251 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1252 APInt(32, (uint32_t)Record[0])));
1253 else if (CurTy->isDoubleTy())
1254 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1255 APInt(64, Record[0])));
1256 else if (CurTy->isX86_FP80Ty()) {
1257 // Bits are not stored the same way as a normal i80 APInt, compensate.
1258 uint64_t Rearrange[2];
1259 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1260 Rearrange[1] = Record[0] >> 48;
1261 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1262 APInt(80, Rearrange)));
1263 } else if (CurTy->isFP128Ty())
1264 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1265 APInt(128, Record)));
1266 else if (CurTy->isPPC_FP128Ty())
1267 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1268 APInt(128, Record)));
1270 V = UndefValue::get(CurTy);
1274 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1276 return Error(InvalidRecord);
1278 unsigned Size = Record.size();
1279 SmallVector<Constant*, 16> Elts;
1281 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1282 for (unsigned i = 0; i != Size; ++i)
1283 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1284 STy->getElementType(i)));
1285 V = ConstantStruct::get(STy, Elts);
1286 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1287 Type *EltTy = ATy->getElementType();
1288 for (unsigned i = 0; i != Size; ++i)
1289 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1290 V = ConstantArray::get(ATy, Elts);
1291 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1292 Type *EltTy = VTy->getElementType();
1293 for (unsigned i = 0; i != Size; ++i)
1294 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1295 V = ConstantVector::get(Elts);
1297 V = UndefValue::get(CurTy);
1301 case bitc::CST_CODE_STRING: // STRING: [values]
1302 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1304 return Error(InvalidRecord);
1306 SmallString<16> Elts(Record.begin(), Record.end());
1307 V = ConstantDataArray::getString(Context, Elts,
1308 BitCode == bitc::CST_CODE_CSTRING);
1311 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1313 return Error(InvalidRecord);
1315 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1316 unsigned Size = Record.size();
1318 if (EltTy->isIntegerTy(8)) {
1319 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1320 if (isa<VectorType>(CurTy))
1321 V = ConstantDataVector::get(Context, Elts);
1323 V = ConstantDataArray::get(Context, Elts);
1324 } else if (EltTy->isIntegerTy(16)) {
1325 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1326 if (isa<VectorType>(CurTy))
1327 V = ConstantDataVector::get(Context, Elts);
1329 V = ConstantDataArray::get(Context, Elts);
1330 } else if (EltTy->isIntegerTy(32)) {
1331 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1332 if (isa<VectorType>(CurTy))
1333 V = ConstantDataVector::get(Context, Elts);
1335 V = ConstantDataArray::get(Context, Elts);
1336 } else if (EltTy->isIntegerTy(64)) {
1337 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1338 if (isa<VectorType>(CurTy))
1339 V = ConstantDataVector::get(Context, Elts);
1341 V = ConstantDataArray::get(Context, Elts);
1342 } else if (EltTy->isFloatTy()) {
1343 SmallVector<float, 16> Elts(Size);
1344 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1345 if (isa<VectorType>(CurTy))
1346 V = ConstantDataVector::get(Context, Elts);
1348 V = ConstantDataArray::get(Context, Elts);
1349 } else if (EltTy->isDoubleTy()) {
1350 SmallVector<double, 16> Elts(Size);
1351 std::transform(Record.begin(), Record.end(), Elts.begin(),
1353 if (isa<VectorType>(CurTy))
1354 V = ConstantDataVector::get(Context, Elts);
1356 V = ConstantDataArray::get(Context, Elts);
1358 return Error(InvalidTypeForValue);
1363 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1364 if (Record.size() < 3)
1365 return Error(InvalidRecord);
1366 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1368 V = UndefValue::get(CurTy); // Unknown binop.
1370 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1371 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1373 if (Record.size() >= 4) {
1374 if (Opc == Instruction::Add ||
1375 Opc == Instruction::Sub ||
1376 Opc == Instruction::Mul ||
1377 Opc == Instruction::Shl) {
1378 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1379 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1380 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1381 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1382 } else if (Opc == Instruction::SDiv ||
1383 Opc == Instruction::UDiv ||
1384 Opc == Instruction::LShr ||
1385 Opc == Instruction::AShr) {
1386 if (Record[3] & (1 << bitc::PEO_EXACT))
1387 Flags |= SDivOperator::IsExact;
1390 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1394 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1395 if (Record.size() < 3)
1396 return Error(InvalidRecord);
1397 int Opc = GetDecodedCastOpcode(Record[0]);
1399 V = UndefValue::get(CurTy); // Unknown cast.
1401 Type *OpTy = getTypeByID(Record[1]);
1403 return Error(InvalidRecord);
1404 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1405 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1406 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1410 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1411 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1412 if (Record.size() & 1)
1413 return Error(InvalidRecord);
1414 SmallVector<Constant*, 16> Elts;
1415 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1416 Type *ElTy = getTypeByID(Record[i]);
1418 return Error(InvalidRecord);
1419 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1421 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1422 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1424 bitc::CST_CODE_CE_INBOUNDS_GEP);
1427 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1428 if (Record.size() < 3)
1429 return Error(InvalidRecord);
1431 Type *SelectorTy = Type::getInt1Ty(Context);
1433 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1434 // vector. Otherwise, it must be a single bit.
1435 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1436 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1437 VTy->getNumElements());
1439 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1441 ValueList.getConstantFwdRef(Record[1],CurTy),
1442 ValueList.getConstantFwdRef(Record[2],CurTy));
1445 case bitc::CST_CODE_CE_EXTRACTELT
1446 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1447 if (Record.size() < 3)
1448 return Error(InvalidRecord);
1450 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1452 return Error(InvalidRecord);
1453 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1454 Constant *Op1 = nullptr;
1455 if (Record.size() == 4) {
1456 Type *IdxTy = getTypeByID(Record[2]);
1458 return Error(InvalidRecord);
1459 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1460 } else // TODO: Remove with llvm 4.0
1461 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1463 return Error(InvalidRecord);
1464 V = ConstantExpr::getExtractElement(Op0, Op1);
1467 case bitc::CST_CODE_CE_INSERTELT
1468 : { // CE_INSERTELT: [opval, opval, opty, opval]
1469 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1470 if (Record.size() < 3 || !OpTy)
1471 return Error(InvalidRecord);
1472 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1473 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1474 OpTy->getElementType());
1475 Constant *Op2 = nullptr;
1476 if (Record.size() == 4) {
1477 Type *IdxTy = getTypeByID(Record[2]);
1479 return Error(InvalidRecord);
1480 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1481 } else // TODO: Remove with llvm 4.0
1482 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1484 return Error(InvalidRecord);
1485 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1488 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1489 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1490 if (Record.size() < 3 || !OpTy)
1491 return Error(InvalidRecord);
1492 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1493 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1494 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1495 OpTy->getNumElements());
1496 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1497 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1500 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1501 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1503 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1504 if (Record.size() < 4 || !RTy || !OpTy)
1505 return Error(InvalidRecord);
1506 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1507 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1508 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1509 RTy->getNumElements());
1510 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1511 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1514 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1515 if (Record.size() < 4)
1516 return Error(InvalidRecord);
1517 Type *OpTy = getTypeByID(Record[0]);
1519 return Error(InvalidRecord);
1520 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1521 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1523 if (OpTy->isFPOrFPVectorTy())
1524 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1526 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1529 // This maintains backward compatibility, pre-asm dialect keywords.
1530 // FIXME: Remove with the 4.0 release.
1531 case bitc::CST_CODE_INLINEASM_OLD: {
1532 if (Record.size() < 2)
1533 return Error(InvalidRecord);
1534 std::string AsmStr, ConstrStr;
1535 bool HasSideEffects = Record[0] & 1;
1536 bool IsAlignStack = Record[0] >> 1;
1537 unsigned AsmStrSize = Record[1];
1538 if (2+AsmStrSize >= Record.size())
1539 return Error(InvalidRecord);
1540 unsigned ConstStrSize = Record[2+AsmStrSize];
1541 if (3+AsmStrSize+ConstStrSize > Record.size())
1542 return Error(InvalidRecord);
1544 for (unsigned i = 0; i != AsmStrSize; ++i)
1545 AsmStr += (char)Record[2+i];
1546 for (unsigned i = 0; i != ConstStrSize; ++i)
1547 ConstrStr += (char)Record[3+AsmStrSize+i];
1548 PointerType *PTy = cast<PointerType>(CurTy);
1549 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1550 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1553 // This version adds support for the asm dialect keywords (e.g.,
1555 case bitc::CST_CODE_INLINEASM: {
1556 if (Record.size() < 2)
1557 return Error(InvalidRecord);
1558 std::string AsmStr, ConstrStr;
1559 bool HasSideEffects = Record[0] & 1;
1560 bool IsAlignStack = (Record[0] >> 1) & 1;
1561 unsigned AsmDialect = Record[0] >> 2;
1562 unsigned AsmStrSize = Record[1];
1563 if (2+AsmStrSize >= Record.size())
1564 return Error(InvalidRecord);
1565 unsigned ConstStrSize = Record[2+AsmStrSize];
1566 if (3+AsmStrSize+ConstStrSize > Record.size())
1567 return Error(InvalidRecord);
1569 for (unsigned i = 0; i != AsmStrSize; ++i)
1570 AsmStr += (char)Record[2+i];
1571 for (unsigned i = 0; i != ConstStrSize; ++i)
1572 ConstrStr += (char)Record[3+AsmStrSize+i];
1573 PointerType *PTy = cast<PointerType>(CurTy);
1574 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1575 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1576 InlineAsm::AsmDialect(AsmDialect));
1579 case bitc::CST_CODE_BLOCKADDRESS:{
1580 if (Record.size() < 3)
1581 return Error(InvalidRecord);
1582 Type *FnTy = getTypeByID(Record[0]);
1584 return Error(InvalidRecord);
1586 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1588 return Error(InvalidRecord);
1590 // If the function is already parsed we can insert the block address right
1593 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1594 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1596 return Error(InvalidID);
1599 V = BlockAddress::get(Fn, BBI);
1601 // Otherwise insert a placeholder and remember it so it can be inserted
1602 // when the function is parsed.
1603 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1604 Type::getInt8Ty(Context),
1605 false, GlobalValue::InternalLinkage,
1607 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1614 ValueList.AssignValue(V, NextCstNo);
1619 std::error_code BitcodeReader::ParseUseLists() {
1620 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1621 return Error(InvalidRecord);
1623 SmallVector<uint64_t, 64> Record;
1625 // Read all the records.
1627 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1629 switch (Entry.Kind) {
1630 case BitstreamEntry::SubBlock: // Handled for us already.
1631 case BitstreamEntry::Error:
1632 return Error(MalformedBlock);
1633 case BitstreamEntry::EndBlock:
1634 return std::error_code();
1635 case BitstreamEntry::Record:
1636 // The interesting case.
1640 // Read a use list record.
1642 switch (Stream.readRecord(Entry.ID, Record)) {
1643 default: // Default behavior: unknown type.
1645 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1646 unsigned RecordLength = Record.size();
1647 if (RecordLength < 1)
1648 return Error(InvalidRecord);
1649 UseListRecords.push_back(Record);
1656 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1657 /// remember where it is and then skip it. This lets us lazily deserialize the
1659 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1660 // Get the function we are talking about.
1661 if (FunctionsWithBodies.empty())
1662 return Error(InsufficientFunctionProtos);
1664 Function *Fn = FunctionsWithBodies.back();
1665 FunctionsWithBodies.pop_back();
1667 // Save the current stream state.
1668 uint64_t CurBit = Stream.GetCurrentBitNo();
1669 DeferredFunctionInfo[Fn] = CurBit;
1671 // Skip over the function block for now.
1672 if (Stream.SkipBlock())
1673 return Error(InvalidRecord);
1674 return std::error_code();
1677 std::error_code BitcodeReader::GlobalCleanup() {
1678 // Patch the initializers for globals and aliases up.
1679 ResolveGlobalAndAliasInits();
1680 if (!GlobalInits.empty() || !AliasInits.empty())
1681 return Error(MalformedGlobalInitializerSet);
1683 // Look for intrinsic functions which need to be upgraded at some point
1684 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1687 if (UpgradeIntrinsicFunction(FI, NewFn))
1688 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1691 // Look for global variables which need to be renamed.
1692 for (Module::global_iterator
1693 GI = TheModule->global_begin(), GE = TheModule->global_end();
1695 GlobalVariable *GV = GI++;
1696 UpgradeGlobalVariable(GV);
1699 // Force deallocation of memory for these vectors to favor the client that
1700 // want lazy deserialization.
1701 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1702 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1703 return std::error_code();
1706 std::error_code BitcodeReader::ParseModule(bool Resume) {
1708 Stream.JumpToBit(NextUnreadBit);
1709 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1710 return Error(InvalidRecord);
1712 SmallVector<uint64_t, 64> Record;
1713 std::vector<std::string> SectionTable;
1714 std::vector<std::string> GCTable;
1716 // Read all the records for this module.
1718 BitstreamEntry Entry = Stream.advance();
1720 switch (Entry.Kind) {
1721 case BitstreamEntry::Error:
1722 return Error(MalformedBlock);
1723 case BitstreamEntry::EndBlock:
1724 return GlobalCleanup();
1726 case BitstreamEntry::SubBlock:
1728 default: // Skip unknown content.
1729 if (Stream.SkipBlock())
1730 return Error(InvalidRecord);
1732 case bitc::BLOCKINFO_BLOCK_ID:
1733 if (Stream.ReadBlockInfoBlock())
1734 return Error(MalformedBlock);
1736 case bitc::PARAMATTR_BLOCK_ID:
1737 if (std::error_code EC = ParseAttributeBlock())
1740 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1741 if (std::error_code EC = ParseAttributeGroupBlock())
1744 case bitc::TYPE_BLOCK_ID_NEW:
1745 if (std::error_code EC = ParseTypeTable())
1748 case bitc::VALUE_SYMTAB_BLOCK_ID:
1749 if (std::error_code EC = ParseValueSymbolTable())
1751 SeenValueSymbolTable = true;
1753 case bitc::CONSTANTS_BLOCK_ID:
1754 if (std::error_code EC = ParseConstants())
1756 if (std::error_code EC = ResolveGlobalAndAliasInits())
1759 case bitc::METADATA_BLOCK_ID:
1760 if (std::error_code EC = ParseMetadata())
1763 case bitc::FUNCTION_BLOCK_ID:
1764 // If this is the first function body we've seen, reverse the
1765 // FunctionsWithBodies list.
1766 if (!SeenFirstFunctionBody) {
1767 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1768 if (std::error_code EC = GlobalCleanup())
1770 SeenFirstFunctionBody = true;
1773 if (std::error_code EC = RememberAndSkipFunctionBody())
1775 // For streaming bitcode, suspend parsing when we reach the function
1776 // bodies. Subsequent materialization calls will resume it when
1777 // necessary. For streaming, the function bodies must be at the end of
1778 // the bitcode. If the bitcode file is old, the symbol table will be
1779 // at the end instead and will not have been seen yet. In this case,
1780 // just finish the parse now.
1781 if (LazyStreamer && SeenValueSymbolTable) {
1782 NextUnreadBit = Stream.GetCurrentBitNo();
1783 return std::error_code();
1786 case bitc::USELIST_BLOCK_ID:
1787 if (std::error_code EC = ParseUseLists())
1793 case BitstreamEntry::Record:
1794 // The interesting case.
1800 switch (Stream.readRecord(Entry.ID, Record)) {
1801 default: break; // Default behavior, ignore unknown content.
1802 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1803 if (Record.size() < 1)
1804 return Error(InvalidRecord);
1805 // Only version #0 and #1 are supported so far.
1806 unsigned module_version = Record[0];
1807 switch (module_version) {
1809 return Error(InvalidValue);
1811 UseRelativeIDs = false;
1814 UseRelativeIDs = true;
1819 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1821 if (ConvertToString(Record, 0, S))
1822 return Error(InvalidRecord);
1823 TheModule->setTargetTriple(S);
1826 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1828 if (ConvertToString(Record, 0, S))
1829 return Error(InvalidRecord);
1830 TheModule->setDataLayout(S);
1833 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1835 if (ConvertToString(Record, 0, S))
1836 return Error(InvalidRecord);
1837 TheModule->setModuleInlineAsm(S);
1840 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1841 // FIXME: Remove in 4.0.
1843 if (ConvertToString(Record, 0, S))
1844 return Error(InvalidRecord);
1848 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1850 if (ConvertToString(Record, 0, S))
1851 return Error(InvalidRecord);
1852 SectionTable.push_back(S);
1855 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1857 if (ConvertToString(Record, 0, S))
1858 return Error(InvalidRecord);
1859 GCTable.push_back(S);
1862 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1863 if (Record.size() < 2)
1864 return Error(InvalidRecord);
1865 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1866 unsigned ComdatNameSize = Record[1];
1867 std::string ComdatName;
1868 ComdatName.reserve(ComdatNameSize);
1869 for (unsigned i = 0; i != ComdatNameSize; ++i)
1870 ComdatName += (char)Record[2 + i];
1871 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1872 C->setSelectionKind(SK);
1873 ComdatList.push_back(C);
1876 // GLOBALVAR: [pointer type, isconst, initid,
1877 // linkage, alignment, section, visibility, threadlocal,
1878 // unnamed_addr, dllstorageclass]
1879 case bitc::MODULE_CODE_GLOBALVAR: {
1880 if (Record.size() < 6)
1881 return Error(InvalidRecord);
1882 Type *Ty = getTypeByID(Record[0]);
1884 return Error(InvalidRecord);
1885 if (!Ty->isPointerTy())
1886 return Error(InvalidTypeForValue);
1887 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1888 Ty = cast<PointerType>(Ty)->getElementType();
1890 bool isConstant = Record[1];
1891 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1892 unsigned Alignment = (1 << Record[4]) >> 1;
1893 std::string Section;
1895 if (Record[5]-1 >= SectionTable.size())
1896 return Error(InvalidID);
1897 Section = SectionTable[Record[5]-1];
1899 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1900 // Local linkage must have default visibility.
1901 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1902 // FIXME: Change to an error if non-default in 4.0.
1903 Visibility = GetDecodedVisibility(Record[6]);
1905 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1906 if (Record.size() > 7)
1907 TLM = GetDecodedThreadLocalMode(Record[7]);
1909 bool UnnamedAddr = false;
1910 if (Record.size() > 8)
1911 UnnamedAddr = Record[8];
1913 bool ExternallyInitialized = false;
1914 if (Record.size() > 9)
1915 ExternallyInitialized = Record[9];
1917 GlobalVariable *NewGV =
1918 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1919 TLM, AddressSpace, ExternallyInitialized);
1920 NewGV->setAlignment(Alignment);
1921 if (!Section.empty())
1922 NewGV->setSection(Section);
1923 NewGV->setVisibility(Visibility);
1924 NewGV->setUnnamedAddr(UnnamedAddr);
1926 if (Record.size() > 10)
1927 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1929 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1931 ValueList.push_back(NewGV);
1933 // Remember which value to use for the global initializer.
1934 if (unsigned InitID = Record[2])
1935 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1937 if (Record.size() > 11)
1938 if (unsigned ComdatID = Record[11]) {
1939 assert(ComdatID <= ComdatList.size());
1940 NewGV->setComdat(ComdatList[ComdatID - 1]);
1944 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1945 // alignment, section, visibility, gc, unnamed_addr,
1947 case bitc::MODULE_CODE_FUNCTION: {
1948 if (Record.size() < 8)
1949 return Error(InvalidRecord);
1950 Type *Ty = getTypeByID(Record[0]);
1952 return Error(InvalidRecord);
1953 if (!Ty->isPointerTy())
1954 return Error(InvalidTypeForValue);
1956 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1958 return Error(InvalidTypeForValue);
1960 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1963 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1964 bool isProto = Record[2];
1965 Func->setLinkage(GetDecodedLinkage(Record[3]));
1966 Func->setAttributes(getAttributes(Record[4]));
1968 Func->setAlignment((1 << Record[5]) >> 1);
1970 if (Record[6]-1 >= SectionTable.size())
1971 return Error(InvalidID);
1972 Func->setSection(SectionTable[Record[6]-1]);
1974 // Local linkage must have default visibility.
1975 if (!Func->hasLocalLinkage())
1976 // FIXME: Change to an error if non-default in 4.0.
1977 Func->setVisibility(GetDecodedVisibility(Record[7]));
1978 if (Record.size() > 8 && Record[8]) {
1979 if (Record[8]-1 > GCTable.size())
1980 return Error(InvalidID);
1981 Func->setGC(GCTable[Record[8]-1].c_str());
1983 bool UnnamedAddr = false;
1984 if (Record.size() > 9)
1985 UnnamedAddr = Record[9];
1986 Func->setUnnamedAddr(UnnamedAddr);
1987 if (Record.size() > 10 && Record[10] != 0)
1988 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1990 if (Record.size() > 11)
1991 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1993 UpgradeDLLImportExportLinkage(Func, Record[3]);
1995 if (Record.size() > 12)
1996 if (unsigned ComdatID = Record[12]) {
1997 assert(ComdatID <= ComdatList.size());
1998 Func->setComdat(ComdatList[ComdatID - 1]);
2001 ValueList.push_back(Func);
2003 // If this is a function with a body, remember the prototype we are
2004 // creating now, so that we can match up the body with them later.
2006 FunctionsWithBodies.push_back(Func);
2007 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
2011 // ALIAS: [alias type, aliasee val#, linkage]
2012 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2013 case bitc::MODULE_CODE_ALIAS: {
2014 if (Record.size() < 3)
2015 return Error(InvalidRecord);
2016 Type *Ty = getTypeByID(Record[0]);
2018 return Error(InvalidRecord);
2019 auto *PTy = dyn_cast<PointerType>(Ty);
2021 return Error(InvalidTypeForValue);
2024 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2025 GetDecodedLinkage(Record[2]), "", TheModule);
2026 // Old bitcode files didn't have visibility field.
2027 // Local linkage must have default visibility.
2028 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2029 // FIXME: Change to an error if non-default in 4.0.
2030 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2031 if (Record.size() > 4)
2032 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2034 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2035 if (Record.size() > 5)
2036 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2037 if (Record.size() > 6)
2038 NewGA->setUnnamedAddr(Record[6]);
2039 ValueList.push_back(NewGA);
2040 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2043 /// MODULE_CODE_PURGEVALS: [numvals]
2044 case bitc::MODULE_CODE_PURGEVALS:
2045 // Trim down the value list to the specified size.
2046 if (Record.size() < 1 || Record[0] > ValueList.size())
2047 return Error(InvalidRecord);
2048 ValueList.shrinkTo(Record[0]);
2055 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2056 TheModule = nullptr;
2058 if (std::error_code EC = InitStream())
2061 // Sniff for the signature.
2062 if (Stream.Read(8) != 'B' ||
2063 Stream.Read(8) != 'C' ||
2064 Stream.Read(4) != 0x0 ||
2065 Stream.Read(4) != 0xC ||
2066 Stream.Read(4) != 0xE ||
2067 Stream.Read(4) != 0xD)
2068 return Error(InvalidBitcodeSignature);
2070 // We expect a number of well-defined blocks, though we don't necessarily
2071 // need to understand them all.
2073 if (Stream.AtEndOfStream())
2074 return std::error_code();
2076 BitstreamEntry Entry =
2077 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2079 switch (Entry.Kind) {
2080 case BitstreamEntry::Error:
2081 return Error(MalformedBlock);
2082 case BitstreamEntry::EndBlock:
2083 return std::error_code();
2085 case BitstreamEntry::SubBlock:
2087 case bitc::BLOCKINFO_BLOCK_ID:
2088 if (Stream.ReadBlockInfoBlock())
2089 return Error(MalformedBlock);
2091 case bitc::MODULE_BLOCK_ID:
2092 // Reject multiple MODULE_BLOCK's in a single bitstream.
2094 return Error(InvalidMultipleBlocks);
2096 if (std::error_code EC = ParseModule(false))
2099 return std::error_code();
2102 if (Stream.SkipBlock())
2103 return Error(InvalidRecord);
2107 case BitstreamEntry::Record:
2108 // There should be no records in the top-level of blocks.
2110 // The ranlib in Xcode 4 will align archive members by appending newlines
2111 // to the end of them. If this file size is a multiple of 4 but not 8, we
2112 // have to read and ignore these final 4 bytes :-(
2113 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2114 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2115 Stream.AtEndOfStream())
2116 return std::error_code();
2118 return Error(InvalidRecord);
2123 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2124 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2125 return Error(InvalidRecord);
2127 SmallVector<uint64_t, 64> Record;
2130 // Read all the records for this module.
2132 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2134 switch (Entry.Kind) {
2135 case BitstreamEntry::SubBlock: // Handled for us already.
2136 case BitstreamEntry::Error:
2137 return Error(MalformedBlock);
2138 case BitstreamEntry::EndBlock:
2140 case BitstreamEntry::Record:
2141 // The interesting case.
2146 switch (Stream.readRecord(Entry.ID, Record)) {
2147 default: break; // Default behavior, ignore unknown content.
2148 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2150 if (ConvertToString(Record, 0, S))
2151 return Error(InvalidRecord);
2158 llvm_unreachable("Exit infinite loop");
2161 ErrorOr<std::string> BitcodeReader::parseTriple() {
2162 if (std::error_code EC = InitStream())
2165 // Sniff for the signature.
2166 if (Stream.Read(8) != 'B' ||
2167 Stream.Read(8) != 'C' ||
2168 Stream.Read(4) != 0x0 ||
2169 Stream.Read(4) != 0xC ||
2170 Stream.Read(4) != 0xE ||
2171 Stream.Read(4) != 0xD)
2172 return Error(InvalidBitcodeSignature);
2174 // We expect a number of well-defined blocks, though we don't necessarily
2175 // need to understand them all.
2177 BitstreamEntry Entry = Stream.advance();
2179 switch (Entry.Kind) {
2180 case BitstreamEntry::Error:
2181 return Error(MalformedBlock);
2182 case BitstreamEntry::EndBlock:
2183 return std::error_code();
2185 case BitstreamEntry::SubBlock:
2186 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2187 return parseModuleTriple();
2189 // Ignore other sub-blocks.
2190 if (Stream.SkipBlock())
2191 return Error(MalformedBlock);
2194 case BitstreamEntry::Record:
2195 Stream.skipRecord(Entry.ID);
2201 /// ParseMetadataAttachment - Parse metadata attachments.
2202 std::error_code BitcodeReader::ParseMetadataAttachment() {
2203 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2204 return Error(InvalidRecord);
2206 SmallVector<uint64_t, 64> Record;
2208 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2210 switch (Entry.Kind) {
2211 case BitstreamEntry::SubBlock: // Handled for us already.
2212 case BitstreamEntry::Error:
2213 return Error(MalformedBlock);
2214 case BitstreamEntry::EndBlock:
2215 return std::error_code();
2216 case BitstreamEntry::Record:
2217 // The interesting case.
2221 // Read a metadata attachment record.
2223 switch (Stream.readRecord(Entry.ID, Record)) {
2224 default: // Default behavior: ignore.
2226 case bitc::METADATA_ATTACHMENT: {
2227 unsigned RecordLength = Record.size();
2228 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2229 return Error(InvalidRecord);
2230 Instruction *Inst = InstructionList[Record[0]];
2231 for (unsigned i = 1; i != RecordLength; i = i+2) {
2232 unsigned Kind = Record[i];
2233 DenseMap<unsigned, unsigned>::iterator I =
2234 MDKindMap.find(Kind);
2235 if (I == MDKindMap.end())
2236 return Error(InvalidID);
2237 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2238 Inst->setMetadata(I->second, cast<MDNode>(Node));
2239 if (I->second == LLVMContext::MD_tbaa)
2240 InstsWithTBAATag.push_back(Inst);
2248 /// ParseFunctionBody - Lazily parse the specified function body block.
2249 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2250 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2251 return Error(InvalidRecord);
2253 InstructionList.clear();
2254 unsigned ModuleValueListSize = ValueList.size();
2255 unsigned ModuleMDValueListSize = MDValueList.size();
2257 // Add all the function arguments to the value table.
2258 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2259 ValueList.push_back(I);
2261 unsigned NextValueNo = ValueList.size();
2262 BasicBlock *CurBB = nullptr;
2263 unsigned CurBBNo = 0;
2267 // Read all the records.
2268 SmallVector<uint64_t, 64> Record;
2270 BitstreamEntry Entry = Stream.advance();
2272 switch (Entry.Kind) {
2273 case BitstreamEntry::Error:
2274 return Error(MalformedBlock);
2275 case BitstreamEntry::EndBlock:
2276 goto OutOfRecordLoop;
2278 case BitstreamEntry::SubBlock:
2280 default: // Skip unknown content.
2281 if (Stream.SkipBlock())
2282 return Error(InvalidRecord);
2284 case bitc::CONSTANTS_BLOCK_ID:
2285 if (std::error_code EC = ParseConstants())
2287 NextValueNo = ValueList.size();
2289 case bitc::VALUE_SYMTAB_BLOCK_ID:
2290 if (std::error_code EC = ParseValueSymbolTable())
2293 case bitc::METADATA_ATTACHMENT_ID:
2294 if (std::error_code EC = ParseMetadataAttachment())
2297 case bitc::METADATA_BLOCK_ID:
2298 if (std::error_code EC = ParseMetadata())
2304 case BitstreamEntry::Record:
2305 // The interesting case.
2311 Instruction *I = nullptr;
2312 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2314 default: // Default behavior: reject
2315 return Error(InvalidValue);
2316 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2317 if (Record.size() < 1 || Record[0] == 0)
2318 return Error(InvalidRecord);
2319 // Create all the basic blocks for the function.
2320 FunctionBBs.resize(Record[0]);
2321 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2322 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2323 CurBB = FunctionBBs[0];
2326 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2327 // This record indicates that the last instruction is at the same
2328 // location as the previous instruction with a location.
2331 // Get the last instruction emitted.
2332 if (CurBB && !CurBB->empty())
2334 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2335 !FunctionBBs[CurBBNo-1]->empty())
2336 I = &FunctionBBs[CurBBNo-1]->back();
2339 return Error(InvalidRecord);
2340 I->setDebugLoc(LastLoc);
2344 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2345 I = nullptr; // Get the last instruction emitted.
2346 if (CurBB && !CurBB->empty())
2348 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2349 !FunctionBBs[CurBBNo-1]->empty())
2350 I = &FunctionBBs[CurBBNo-1]->back();
2351 if (!I || Record.size() < 4)
2352 return Error(InvalidRecord);
2354 unsigned Line = Record[0], Col = Record[1];
2355 unsigned ScopeID = Record[2], IAID = Record[3];
2357 MDNode *Scope = nullptr, *IA = nullptr;
2358 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2359 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2360 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2361 I->setDebugLoc(LastLoc);
2366 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2369 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2370 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2371 OpNum+1 > Record.size())
2372 return Error(InvalidRecord);
2374 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2376 return Error(InvalidRecord);
2377 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2378 InstructionList.push_back(I);
2379 if (OpNum < Record.size()) {
2380 if (Opc == Instruction::Add ||
2381 Opc == Instruction::Sub ||
2382 Opc == Instruction::Mul ||
2383 Opc == Instruction::Shl) {
2384 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2385 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2386 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2387 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2388 } else if (Opc == Instruction::SDiv ||
2389 Opc == Instruction::UDiv ||
2390 Opc == Instruction::LShr ||
2391 Opc == Instruction::AShr) {
2392 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2393 cast<BinaryOperator>(I)->setIsExact(true);
2394 } else if (isa<FPMathOperator>(I)) {
2396 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2397 FMF.setUnsafeAlgebra();
2398 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2400 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2402 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2403 FMF.setNoSignedZeros();
2404 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2405 FMF.setAllowReciprocal();
2407 I->setFastMathFlags(FMF);
2413 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2416 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2417 OpNum+2 != Record.size())
2418 return Error(InvalidRecord);
2420 Type *ResTy = getTypeByID(Record[OpNum]);
2421 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2422 if (Opc == -1 || !ResTy)
2423 return Error(InvalidRecord);
2424 Instruction *Temp = nullptr;
2425 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2427 InstructionList.push_back(Temp);
2428 CurBB->getInstList().push_back(Temp);
2431 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2433 InstructionList.push_back(I);
2436 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2437 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2440 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2441 return Error(InvalidRecord);
2443 SmallVector<Value*, 16> GEPIdx;
2444 while (OpNum != Record.size()) {
2446 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2447 return Error(InvalidRecord);
2448 GEPIdx.push_back(Op);
2451 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2452 InstructionList.push_back(I);
2453 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2454 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2458 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2459 // EXTRACTVAL: [opty, opval, n x indices]
2462 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2463 return Error(InvalidRecord);
2465 SmallVector<unsigned, 4> EXTRACTVALIdx;
2466 for (unsigned RecSize = Record.size();
2467 OpNum != RecSize; ++OpNum) {
2468 uint64_t Index = Record[OpNum];
2469 if ((unsigned)Index != Index)
2470 return Error(InvalidValue);
2471 EXTRACTVALIdx.push_back((unsigned)Index);
2474 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2475 InstructionList.push_back(I);
2479 case bitc::FUNC_CODE_INST_INSERTVAL: {
2480 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2483 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2484 return Error(InvalidRecord);
2486 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2487 return Error(InvalidRecord);
2489 SmallVector<unsigned, 4> INSERTVALIdx;
2490 for (unsigned RecSize = Record.size();
2491 OpNum != RecSize; ++OpNum) {
2492 uint64_t Index = Record[OpNum];
2493 if ((unsigned)Index != Index)
2494 return Error(InvalidValue);
2495 INSERTVALIdx.push_back((unsigned)Index);
2498 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2499 InstructionList.push_back(I);
2503 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2504 // obsolete form of select
2505 // handles select i1 ... in old bitcode
2507 Value *TrueVal, *FalseVal, *Cond;
2508 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2509 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2510 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2511 return Error(InvalidRecord);
2513 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2514 InstructionList.push_back(I);
2518 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2519 // new form of select
2520 // handles select i1 or select [N x i1]
2522 Value *TrueVal, *FalseVal, *Cond;
2523 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2524 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2525 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2526 return Error(InvalidRecord);
2528 // select condition can be either i1 or [N x i1]
2529 if (VectorType* vector_type =
2530 dyn_cast<VectorType>(Cond->getType())) {
2532 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2533 return Error(InvalidTypeForValue);
2536 if (Cond->getType() != Type::getInt1Ty(Context))
2537 return Error(InvalidTypeForValue);
2540 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2541 InstructionList.push_back(I);
2545 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2548 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2549 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2550 return Error(InvalidRecord);
2551 I = ExtractElementInst::Create(Vec, Idx);
2552 InstructionList.push_back(I);
2556 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2558 Value *Vec, *Elt, *Idx;
2559 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2560 popValue(Record, OpNum, NextValueNo,
2561 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2562 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2563 return Error(InvalidRecord);
2564 I = InsertElementInst::Create(Vec, Elt, Idx);
2565 InstructionList.push_back(I);
2569 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2571 Value *Vec1, *Vec2, *Mask;
2572 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2573 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2574 return Error(InvalidRecord);
2576 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2577 return Error(InvalidRecord);
2578 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2579 InstructionList.push_back(I);
2583 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2584 // Old form of ICmp/FCmp returning bool
2585 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2586 // both legal on vectors but had different behaviour.
2587 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2588 // FCmp/ICmp returning bool or vector of bool
2592 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2593 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2594 OpNum+1 != Record.size())
2595 return Error(InvalidRecord);
2597 if (LHS->getType()->isFPOrFPVectorTy())
2598 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2600 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2601 InstructionList.push_back(I);
2605 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2607 unsigned Size = Record.size();
2609 I = ReturnInst::Create(Context);
2610 InstructionList.push_back(I);
2615 Value *Op = nullptr;
2616 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2617 return Error(InvalidRecord);
2618 if (OpNum != Record.size())
2619 return Error(InvalidRecord);
2621 I = ReturnInst::Create(Context, Op);
2622 InstructionList.push_back(I);
2625 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2626 if (Record.size() != 1 && Record.size() != 3)
2627 return Error(InvalidRecord);
2628 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2630 return Error(InvalidRecord);
2632 if (Record.size() == 1) {
2633 I = BranchInst::Create(TrueDest);
2634 InstructionList.push_back(I);
2637 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2638 Value *Cond = getValue(Record, 2, NextValueNo,
2639 Type::getInt1Ty(Context));
2640 if (!FalseDest || !Cond)
2641 return Error(InvalidRecord);
2642 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2643 InstructionList.push_back(I);
2647 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2649 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2650 // "New" SwitchInst format with case ranges. The changes to write this
2651 // format were reverted but we still recognize bitcode that uses it.
2652 // Hopefully someday we will have support for case ranges and can use
2653 // this format again.
2655 Type *OpTy = getTypeByID(Record[1]);
2656 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2658 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2659 BasicBlock *Default = getBasicBlock(Record[3]);
2660 if (!OpTy || !Cond || !Default)
2661 return Error(InvalidRecord);
2663 unsigned NumCases = Record[4];
2665 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2666 InstructionList.push_back(SI);
2668 unsigned CurIdx = 5;
2669 for (unsigned i = 0; i != NumCases; ++i) {
2670 SmallVector<ConstantInt*, 1> CaseVals;
2671 unsigned NumItems = Record[CurIdx++];
2672 for (unsigned ci = 0; ci != NumItems; ++ci) {
2673 bool isSingleNumber = Record[CurIdx++];
2676 unsigned ActiveWords = 1;
2677 if (ValueBitWidth > 64)
2678 ActiveWords = Record[CurIdx++];
2679 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2681 CurIdx += ActiveWords;
2683 if (!isSingleNumber) {
2685 if (ValueBitWidth > 64)
2686 ActiveWords = Record[CurIdx++];
2688 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2690 CurIdx += ActiveWords;
2692 // FIXME: It is not clear whether values in the range should be
2693 // compared as signed or unsigned values. The partially
2694 // implemented changes that used this format in the past used
2695 // unsigned comparisons.
2696 for ( ; Low.ule(High); ++Low)
2697 CaseVals.push_back(ConstantInt::get(Context, Low));
2699 CaseVals.push_back(ConstantInt::get(Context, Low));
2701 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2702 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2703 cve = CaseVals.end(); cvi != cve; ++cvi)
2704 SI->addCase(*cvi, DestBB);
2710 // Old SwitchInst format without case ranges.
2712 if (Record.size() < 3 || (Record.size() & 1) == 0)
2713 return Error(InvalidRecord);
2714 Type *OpTy = getTypeByID(Record[0]);
2715 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2716 BasicBlock *Default = getBasicBlock(Record[2]);
2717 if (!OpTy || !Cond || !Default)
2718 return Error(InvalidRecord);
2719 unsigned NumCases = (Record.size()-3)/2;
2720 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2721 InstructionList.push_back(SI);
2722 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2723 ConstantInt *CaseVal =
2724 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2725 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2726 if (!CaseVal || !DestBB) {
2728 return Error(InvalidRecord);
2730 SI->addCase(CaseVal, DestBB);
2735 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2736 if (Record.size() < 2)
2737 return Error(InvalidRecord);
2738 Type *OpTy = getTypeByID(Record[0]);
2739 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2740 if (!OpTy || !Address)
2741 return Error(InvalidRecord);
2742 unsigned NumDests = Record.size()-2;
2743 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2744 InstructionList.push_back(IBI);
2745 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2746 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2747 IBI->addDestination(DestBB);
2750 return Error(InvalidRecord);
2757 case bitc::FUNC_CODE_INST_INVOKE: {
2758 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2759 if (Record.size() < 4)
2760 return Error(InvalidRecord);
2761 AttributeSet PAL = getAttributes(Record[0]);
2762 unsigned CCInfo = Record[1];
2763 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2764 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2768 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2769 return Error(InvalidRecord);
2771 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2772 FunctionType *FTy = !CalleeTy ? nullptr :
2773 dyn_cast<FunctionType>(CalleeTy->getElementType());
2775 // Check that the right number of fixed parameters are here.
2776 if (!FTy || !NormalBB || !UnwindBB ||
2777 Record.size() < OpNum+FTy->getNumParams())
2778 return Error(InvalidRecord);
2780 SmallVector<Value*, 16> Ops;
2781 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2782 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2783 FTy->getParamType(i)));
2785 return Error(InvalidRecord);
2788 if (!FTy->isVarArg()) {
2789 if (Record.size() != OpNum)
2790 return Error(InvalidRecord);
2792 // Read type/value pairs for varargs params.
2793 while (OpNum != Record.size()) {
2795 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2796 return Error(InvalidRecord);
2801 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2802 InstructionList.push_back(I);
2803 cast<InvokeInst>(I)->setCallingConv(
2804 static_cast<CallingConv::ID>(CCInfo));
2805 cast<InvokeInst>(I)->setAttributes(PAL);
2808 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2810 Value *Val = nullptr;
2811 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2812 return Error(InvalidRecord);
2813 I = ResumeInst::Create(Val);
2814 InstructionList.push_back(I);
2817 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2818 I = new UnreachableInst(Context);
2819 InstructionList.push_back(I);
2821 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2822 if (Record.size() < 1 || ((Record.size()-1)&1))
2823 return Error(InvalidRecord);
2824 Type *Ty = getTypeByID(Record[0]);
2826 return Error(InvalidRecord);
2828 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2829 InstructionList.push_back(PN);
2831 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2833 // With the new function encoding, it is possible that operands have
2834 // negative IDs (for forward references). Use a signed VBR
2835 // representation to keep the encoding small.
2837 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2839 V = getValue(Record, 1+i, NextValueNo, Ty);
2840 BasicBlock *BB = getBasicBlock(Record[2+i]);
2842 return Error(InvalidRecord);
2843 PN->addIncoming(V, BB);
2849 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2850 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2852 if (Record.size() < 4)
2853 return Error(InvalidRecord);
2854 Type *Ty = getTypeByID(Record[Idx++]);
2856 return Error(InvalidRecord);
2857 Value *PersFn = nullptr;
2858 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2859 return Error(InvalidRecord);
2861 bool IsCleanup = !!Record[Idx++];
2862 unsigned NumClauses = Record[Idx++];
2863 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2864 LP->setCleanup(IsCleanup);
2865 for (unsigned J = 0; J != NumClauses; ++J) {
2866 LandingPadInst::ClauseType CT =
2867 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2870 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2872 return Error(InvalidRecord);
2875 assert((CT != LandingPadInst::Catch ||
2876 !isa<ArrayType>(Val->getType())) &&
2877 "Catch clause has a invalid type!");
2878 assert((CT != LandingPadInst::Filter ||
2879 isa<ArrayType>(Val->getType())) &&
2880 "Filter clause has invalid type!");
2881 LP->addClause(cast<Constant>(Val));
2885 InstructionList.push_back(I);
2889 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2890 if (Record.size() != 4)
2891 return Error(InvalidRecord);
2893 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2894 Type *OpTy = getTypeByID(Record[1]);
2895 Value *Size = getFnValueByID(Record[2], OpTy);
2896 unsigned AlignRecord = Record[3];
2897 bool InAlloca = AlignRecord & (1 << 5);
2898 unsigned Align = AlignRecord & ((1 << 5) - 1);
2900 return Error(InvalidRecord);
2901 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2902 AI->setUsedWithInAlloca(InAlloca);
2904 InstructionList.push_back(I);
2907 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2910 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2911 OpNum+2 != Record.size())
2912 return Error(InvalidRecord);
2914 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2915 InstructionList.push_back(I);
2918 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2919 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2922 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2923 OpNum+4 != Record.size())
2924 return Error(InvalidRecord);
2927 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2928 if (Ordering == NotAtomic || Ordering == Release ||
2929 Ordering == AcquireRelease)
2930 return Error(InvalidRecord);
2931 if (Ordering != NotAtomic && Record[OpNum] == 0)
2932 return Error(InvalidRecord);
2933 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2935 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2936 Ordering, SynchScope);
2937 InstructionList.push_back(I);
2940 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2943 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2944 popValue(Record, OpNum, NextValueNo,
2945 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2946 OpNum+2 != Record.size())
2947 return Error(InvalidRecord);
2949 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2950 InstructionList.push_back(I);
2953 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2954 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2957 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2958 popValue(Record, OpNum, NextValueNo,
2959 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2960 OpNum+4 != Record.size())
2961 return Error(InvalidRecord);
2963 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2964 if (Ordering == NotAtomic || Ordering == Acquire ||
2965 Ordering == AcquireRelease)
2966 return Error(InvalidRecord);
2967 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2968 if (Ordering != NotAtomic && Record[OpNum] == 0)
2969 return Error(InvalidRecord);
2971 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2972 Ordering, SynchScope);
2973 InstructionList.push_back(I);
2976 case bitc::FUNC_CODE_INST_CMPXCHG: {
2977 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2978 // failureordering?, isweak?]
2980 Value *Ptr, *Cmp, *New;
2981 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2982 popValue(Record, OpNum, NextValueNo,
2983 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2984 popValue(Record, OpNum, NextValueNo,
2985 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2986 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
2987 return Error(InvalidRecord);
2988 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2989 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2990 return Error(InvalidRecord);
2991 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2993 AtomicOrdering FailureOrdering;
2994 if (Record.size() < 7)
2996 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2998 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3000 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3002 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3004 if (Record.size() < 8) {
3005 // Before weak cmpxchgs existed, the instruction simply returned the
3006 // value loaded from memory, so bitcode files from that era will be
3007 // expecting the first component of a modern cmpxchg.
3008 CurBB->getInstList().push_back(I);
3009 I = ExtractValueInst::Create(I, 0);
3011 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3014 InstructionList.push_back(I);
3017 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3018 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3021 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3022 popValue(Record, OpNum, NextValueNo,
3023 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3024 OpNum+4 != Record.size())
3025 return Error(InvalidRecord);
3026 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3027 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3028 Operation > AtomicRMWInst::LAST_BINOP)
3029 return Error(InvalidRecord);
3030 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3031 if (Ordering == NotAtomic || Ordering == Unordered)
3032 return Error(InvalidRecord);
3033 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3034 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3035 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3036 InstructionList.push_back(I);
3039 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3040 if (2 != Record.size())
3041 return Error(InvalidRecord);
3042 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3043 if (Ordering == NotAtomic || Ordering == Unordered ||
3044 Ordering == Monotonic)
3045 return Error(InvalidRecord);
3046 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3047 I = new FenceInst(Context, Ordering, SynchScope);
3048 InstructionList.push_back(I);
3051 case bitc::FUNC_CODE_INST_CALL: {
3052 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3053 if (Record.size() < 3)
3054 return Error(InvalidRecord);
3056 AttributeSet PAL = getAttributes(Record[0]);
3057 unsigned CCInfo = Record[1];
3061 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3062 return Error(InvalidRecord);
3064 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3065 FunctionType *FTy = nullptr;
3066 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3067 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3068 return Error(InvalidRecord);
3070 SmallVector<Value*, 16> Args;
3071 // Read the fixed params.
3072 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3073 if (FTy->getParamType(i)->isLabelTy())
3074 Args.push_back(getBasicBlock(Record[OpNum]));
3076 Args.push_back(getValue(Record, OpNum, NextValueNo,
3077 FTy->getParamType(i)));
3079 return Error(InvalidRecord);
3082 // Read type/value pairs for varargs params.
3083 if (!FTy->isVarArg()) {
3084 if (OpNum != Record.size())
3085 return Error(InvalidRecord);
3087 while (OpNum != Record.size()) {
3089 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3090 return Error(InvalidRecord);
3095 I = CallInst::Create(Callee, Args);
3096 InstructionList.push_back(I);
3097 cast<CallInst>(I)->setCallingConv(
3098 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3099 CallInst::TailCallKind TCK = CallInst::TCK_None;
3101 TCK = CallInst::TCK_Tail;
3102 if (CCInfo & (1 << 14))
3103 TCK = CallInst::TCK_MustTail;
3104 cast<CallInst>(I)->setTailCallKind(TCK);
3105 cast<CallInst>(I)->setAttributes(PAL);
3108 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3109 if (Record.size() < 3)
3110 return Error(InvalidRecord);
3111 Type *OpTy = getTypeByID(Record[0]);
3112 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3113 Type *ResTy = getTypeByID(Record[2]);
3114 if (!OpTy || !Op || !ResTy)
3115 return Error(InvalidRecord);
3116 I = new VAArgInst(Op, ResTy);
3117 InstructionList.push_back(I);
3122 // Add instruction to end of current BB. If there is no current BB, reject
3126 return Error(InvalidInstructionWithNoBB);
3128 CurBB->getInstList().push_back(I);
3130 // If this was a terminator instruction, move to the next block.
3131 if (isa<TerminatorInst>(I)) {
3133 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3136 // Non-void values get registered in the value table for future use.
3137 if (I && !I->getType()->isVoidTy())
3138 ValueList.AssignValue(I, NextValueNo++);
3143 // Check the function list for unresolved values.
3144 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3145 if (!A->getParent()) {
3146 // We found at least one unresolved value. Nuke them all to avoid leaks.
3147 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3148 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3149 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3153 return Error(NeverResolvedValueFoundInFunction);
3157 // FIXME: Check for unresolved forward-declared metadata references
3158 // and clean up leaks.
3160 // See if anything took the address of blocks in this function. If so,
3161 // resolve them now.
3162 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3163 BlockAddrFwdRefs.find(F);
3164 if (BAFRI != BlockAddrFwdRefs.end()) {
3165 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3166 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3167 unsigned BlockIdx = RefList[i].first;
3168 if (BlockIdx >= FunctionBBs.size())
3169 return Error(InvalidID);
3171 GlobalVariable *FwdRef = RefList[i].second;
3172 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3173 FwdRef->eraseFromParent();
3176 BlockAddrFwdRefs.erase(BAFRI);
3179 // Trim the value list down to the size it was before we parsed this function.
3180 ValueList.shrinkTo(ModuleValueListSize);
3181 MDValueList.shrinkTo(ModuleMDValueListSize);
3182 std::vector<BasicBlock*>().swap(FunctionBBs);
3183 return std::error_code();
3186 /// Find the function body in the bitcode stream
3187 std::error_code BitcodeReader::FindFunctionInStream(
3189 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3190 while (DeferredFunctionInfoIterator->second == 0) {
3191 if (Stream.AtEndOfStream())
3192 return Error(CouldNotFindFunctionInStream);
3193 // ParseModule will parse the next body in the stream and set its
3194 // position in the DeferredFunctionInfo map.
3195 if (std::error_code EC = ParseModule(true))
3198 return std::error_code();
3201 //===----------------------------------------------------------------------===//
3202 // GVMaterializer implementation
3203 //===----------------------------------------------------------------------===//
3205 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3207 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3208 if (const Function *F = dyn_cast<Function>(GV)) {
3209 return F->isDeclaration() &&
3210 DeferredFunctionInfo.count(const_cast<Function*>(F));
3215 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3216 Function *F = dyn_cast<Function>(GV);
3217 // If it's not a function or is already material, ignore the request.
3218 if (!F || !F->isMaterializable())
3219 return std::error_code();
3221 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3222 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3223 // If its position is recorded as 0, its body is somewhere in the stream
3224 // but we haven't seen it yet.
3225 if (DFII->second == 0 && LazyStreamer)
3226 if (std::error_code EC = FindFunctionInStream(F, DFII))
3229 // Move the bit stream to the saved position of the deferred function body.
3230 Stream.JumpToBit(DFII->second);
3232 if (std::error_code EC = ParseFunctionBody(F))
3235 // Upgrade any old intrinsic calls in the function.
3236 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3237 E = UpgradedIntrinsics.end(); I != E; ++I) {
3238 if (I->first != I->second) {
3239 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3241 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3242 UpgradeIntrinsicCall(CI, I->second);
3247 return std::error_code();
3250 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3251 const Function *F = dyn_cast<Function>(GV);
3252 if (!F || F->isDeclaration())
3254 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3257 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3258 Function *F = dyn_cast<Function>(GV);
3259 // If this function isn't dematerializable, this is a noop.
3260 if (!F || !isDematerializable(F))
3263 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3265 // Just forget the function body, we can remat it later.
3269 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3270 assert(M == TheModule &&
3271 "Can only Materialize the Module this BitcodeReader is attached to.");
3272 // Iterate over the module, deserializing any functions that are still on
3274 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3276 if (F->isMaterializable()) {
3277 if (std::error_code EC = Materialize(F))
3281 // At this point, if there are any function bodies, the current bit is
3282 // pointing to the END_BLOCK record after them. Now make sure the rest
3283 // of the bits in the module have been read.
3287 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3288 // delete the old functions to clean up. We can't do this unless the entire
3289 // module is materialized because there could always be another function body
3290 // with calls to the old function.
3291 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3292 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3293 if (I->first != I->second) {
3294 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3296 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3297 UpgradeIntrinsicCall(CI, I->second);
3299 if (!I->first->use_empty())
3300 I->first->replaceAllUsesWith(I->second);
3301 I->first->eraseFromParent();
3304 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3306 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3307 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3309 UpgradeDebugInfo(*M);
3310 return std::error_code();
3313 std::error_code BitcodeReader::InitStream() {
3315 return InitLazyStream();
3316 return InitStreamFromBuffer();
3319 std::error_code BitcodeReader::InitStreamFromBuffer() {
3320 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3321 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3323 if (Buffer->getBufferSize() & 3) {
3324 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3325 return Error(InvalidBitcodeSignature);
3327 return Error(BitcodeStreamInvalidSize);
3330 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3331 // The magic number is 0x0B17C0DE stored in little endian.
3332 if (isBitcodeWrapper(BufPtr, BufEnd))
3333 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3334 return Error(InvalidBitcodeWrapperHeader);
3336 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3337 Stream.init(*StreamFile);
3339 return std::error_code();
3342 std::error_code BitcodeReader::InitLazyStream() {
3343 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3345 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3346 StreamFile.reset(new BitstreamReader(Bytes));
3347 Stream.init(*StreamFile);
3349 unsigned char buf[16];
3350 if (Bytes->readBytes(0, 16, buf) == -1)
3351 return Error(BitcodeStreamInvalidSize);
3353 if (!isBitcode(buf, buf + 16))
3354 return Error(InvalidBitcodeSignature);
3356 if (isBitcodeWrapper(buf, buf + 4)) {
3357 const unsigned char *bitcodeStart = buf;
3358 const unsigned char *bitcodeEnd = buf + 16;
3359 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3360 Bytes->dropLeadingBytes(bitcodeStart - buf);
3361 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3363 return std::error_code();
3367 class BitcodeErrorCategoryType : public std::error_category {
3368 const char *name() const LLVM_NOEXCEPT override {
3369 return "llvm.bitcode";
3371 std::string message(int IE) const override {
3372 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3374 case BitcodeReader::BitcodeStreamInvalidSize:
3375 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3376 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3377 return "Conflicting METADATA_KIND records";
3378 case BitcodeReader::CouldNotFindFunctionInStream:
3379 return "Could not find function in stream";
3380 case BitcodeReader::ExpectedConstant:
3381 return "Expected a constant";
3382 case BitcodeReader::InsufficientFunctionProtos:
3383 return "Insufficient function protos";
3384 case BitcodeReader::InvalidBitcodeSignature:
3385 return "Invalid bitcode signature";
3386 case BitcodeReader::InvalidBitcodeWrapperHeader:
3387 return "Invalid bitcode wrapper header";
3388 case BitcodeReader::InvalidConstantReference:
3389 return "Invalid ronstant reference";
3390 case BitcodeReader::InvalidID:
3391 return "Invalid ID";
3392 case BitcodeReader::InvalidInstructionWithNoBB:
3393 return "Invalid instruction with no BB";
3394 case BitcodeReader::InvalidRecord:
3395 return "Invalid record";
3396 case BitcodeReader::InvalidTypeForValue:
3397 return "Invalid type for value";
3398 case BitcodeReader::InvalidTYPETable:
3399 return "Invalid TYPE table";
3400 case BitcodeReader::InvalidType:
3401 return "Invalid type";
3402 case BitcodeReader::MalformedBlock:
3403 return "Malformed block";
3404 case BitcodeReader::MalformedGlobalInitializerSet:
3405 return "Malformed global initializer set";
3406 case BitcodeReader::InvalidMultipleBlocks:
3407 return "Invalid multiple blocks";
3408 case BitcodeReader::NeverResolvedValueFoundInFunction:
3409 return "Never resolved value found in function";
3410 case BitcodeReader::InvalidValue:
3411 return "Invalid value";
3413 llvm_unreachable("Unknown error type!");
3418 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3419 static BitcodeErrorCategoryType O;
3423 //===----------------------------------------------------------------------===//
3424 // External interface
3425 //===----------------------------------------------------------------------===//
3427 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3429 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3430 LLVMContext &Context) {
3431 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3432 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3433 M->setMaterializer(R);
3434 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3435 R->releaseBuffer(); // Never take ownership on error.
3436 delete M; // Also deletes R.
3440 R->materializeForwardReferencedFunctions();
3446 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3447 DataStreamer *streamer,
3448 LLVMContext &Context,
3449 std::string *ErrMsg) {
3450 Module *M = new Module(name, Context);
3451 BitcodeReader *R = new BitcodeReader(streamer, Context);
3452 M->setMaterializer(R);
3453 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3455 *ErrMsg = EC.message();
3456 delete M; // Also deletes R.
3462 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3463 LLVMContext &Context) {
3464 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3467 Module *M = ModuleOrErr.get();
3468 // Read in the entire module, and destroy the BitcodeReader.
3469 if (std::error_code EC = M->materializeAllPermanently(true)) {
3474 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3475 // written. We must defer until the Module has been fully materialized.
3480 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3481 LLVMContext &Context) {
3482 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3483 ErrorOr<std::string> Triple = R->parseTriple();
3486 if (Triple.getError())
3488 return Triple.get();