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() {
45 std::vector<Type*>().swap(TypeList);
49 std::vector<AttributeSet>().swap(MAttributes);
50 std::vector<BasicBlock*>().swap(FunctionBBs);
51 std::vector<Function*>().swap(FunctionsWithBodies);
52 DeferredFunctionInfo.clear();
55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
58 //===----------------------------------------------------------------------===//
59 // Helper functions to implement forward reference resolution, etc.
60 //===----------------------------------------------------------------------===//
62 /// ConvertToString - Convert a string from a record into an std::string, return
64 template<typename StrTy>
65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
67 if (Idx > Record.size())
70 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71 Result += (char)Record[i];
75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 default: // Map unknown/new linkages to external
78 case 0: return GlobalValue::ExternalLinkage;
79 case 1: return GlobalValue::WeakAnyLinkage;
80 case 2: return GlobalValue::AppendingLinkage;
81 case 3: return GlobalValue::InternalLinkage;
82 case 4: return GlobalValue::LinkOnceAnyLinkage;
83 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
84 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
85 case 7: return GlobalValue::ExternalWeakLinkage;
86 case 8: return GlobalValue::CommonLinkage;
87 case 9: return GlobalValue::PrivateLinkage;
88 case 10: return GlobalValue::WeakODRLinkage;
89 case 11: return GlobalValue::LinkOnceODRLinkage;
90 case 12: return GlobalValue::AvailableExternallyLinkage;
92 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
94 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
98 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
100 default: // Map unknown visibilities to default.
101 case 0: return GlobalValue::DefaultVisibility;
102 case 1: return GlobalValue::HiddenVisibility;
103 case 2: return GlobalValue::ProtectedVisibility;
107 static GlobalValue::DLLStorageClassTypes
108 GetDecodedDLLStorageClass(unsigned Val) {
110 default: // Map unknown values to default.
111 case 0: return GlobalValue::DefaultStorageClass;
112 case 1: return GlobalValue::DLLImportStorageClass;
113 case 2: return GlobalValue::DLLExportStorageClass;
117 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
119 case 0: return GlobalVariable::NotThreadLocal;
120 default: // Map unknown non-zero value to general dynamic.
121 case 1: return GlobalVariable::GeneralDynamicTLSModel;
122 case 2: return GlobalVariable::LocalDynamicTLSModel;
123 case 3: return GlobalVariable::InitialExecTLSModel;
124 case 4: return GlobalVariable::LocalExecTLSModel;
128 static int GetDecodedCastOpcode(unsigned Val) {
131 case bitc::CAST_TRUNC : return Instruction::Trunc;
132 case bitc::CAST_ZEXT : return Instruction::ZExt;
133 case bitc::CAST_SEXT : return Instruction::SExt;
134 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
135 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
136 case bitc::CAST_UITOFP : return Instruction::UIToFP;
137 case bitc::CAST_SITOFP : return Instruction::SIToFP;
138 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
139 case bitc::CAST_FPEXT : return Instruction::FPExt;
140 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
141 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
142 case bitc::CAST_BITCAST : return Instruction::BitCast;
143 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
146 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
149 case bitc::BINOP_ADD:
150 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
151 case bitc::BINOP_SUB:
152 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
153 case bitc::BINOP_MUL:
154 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
155 case bitc::BINOP_UDIV: return Instruction::UDiv;
156 case bitc::BINOP_SDIV:
157 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
158 case bitc::BINOP_UREM: return Instruction::URem;
159 case bitc::BINOP_SREM:
160 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
161 case bitc::BINOP_SHL: return Instruction::Shl;
162 case bitc::BINOP_LSHR: return Instruction::LShr;
163 case bitc::BINOP_ASHR: return Instruction::AShr;
164 case bitc::BINOP_AND: return Instruction::And;
165 case bitc::BINOP_OR: return Instruction::Or;
166 case bitc::BINOP_XOR: return Instruction::Xor;
170 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
172 default: return AtomicRMWInst::BAD_BINOP;
173 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
174 case bitc::RMW_ADD: return AtomicRMWInst::Add;
175 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
176 case bitc::RMW_AND: return AtomicRMWInst::And;
177 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
178 case bitc::RMW_OR: return AtomicRMWInst::Or;
179 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
180 case bitc::RMW_MAX: return AtomicRMWInst::Max;
181 case bitc::RMW_MIN: return AtomicRMWInst::Min;
182 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
183 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
187 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
189 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
190 case bitc::ORDERING_UNORDERED: return Unordered;
191 case bitc::ORDERING_MONOTONIC: return Monotonic;
192 case bitc::ORDERING_ACQUIRE: return Acquire;
193 case bitc::ORDERING_RELEASE: return Release;
194 case bitc::ORDERING_ACQREL: return AcquireRelease;
195 default: // Map unknown orderings to sequentially-consistent.
196 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
200 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
202 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
203 default: // Map unknown scopes to cross-thread.
204 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
208 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
210 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
211 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
217 /// @brief A class for maintaining the slot number definition
218 /// as a placeholder for the actual definition for forward constants defs.
219 class ConstantPlaceHolder : public ConstantExpr {
220 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
222 // allocate space for exactly one operand
223 void *operator new(size_t s) {
224 return User::operator new(s, 1);
226 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
227 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
228 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
231 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
232 static bool classof(const Value *V) {
233 return isa<ConstantExpr>(V) &&
234 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
238 /// Provide fast operand accessors
239 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
243 // FIXME: can we inherit this from ConstantExpr?
245 struct OperandTraits<ConstantPlaceHolder> :
246 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
251 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
260 WeakVH &OldV = ValuePtrs[Idx];
266 // Handle constants and non-constants (e.g. instrs) differently for
268 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
269 ResolveConstants.push_back(std::make_pair(PHC, Idx));
272 // If there was a forward reference to this value, replace it.
273 Value *PrevVal = OldV;
274 OldV->replaceAllUsesWith(V);
280 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
285 if (Value *V = ValuePtrs[Idx]) {
286 assert(Ty == V->getType() && "Type mismatch in constant table!");
287 return cast<Constant>(V);
290 // Create and return a placeholder, which will later be RAUW'd.
291 Constant *C = new ConstantPlaceHolder(Ty, Context);
296 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
300 if (Value *V = ValuePtrs[Idx]) {
301 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
305 // No type specified, must be invalid reference.
306 if (!Ty) return nullptr;
308 // Create and return a placeholder, which will later be RAUW'd.
309 Value *V = new Argument(Ty);
314 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
315 /// resolves any forward references. The idea behind this is that we sometimes
316 /// get constants (such as large arrays) which reference *many* forward ref
317 /// constants. Replacing each of these causes a lot of thrashing when
318 /// building/reuniquing the constant. Instead of doing this, we look at all the
319 /// uses and rewrite all the place holders at once for any constant that uses
321 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
322 // Sort the values by-pointer so that they are efficient to look up with a
324 std::sort(ResolveConstants.begin(), ResolveConstants.end());
326 SmallVector<Constant*, 64> NewOps;
328 while (!ResolveConstants.empty()) {
329 Value *RealVal = operator[](ResolveConstants.back().second);
330 Constant *Placeholder = ResolveConstants.back().first;
331 ResolveConstants.pop_back();
333 // Loop over all users of the placeholder, updating them to reference the
334 // new value. If they reference more than one placeholder, update them all
336 while (!Placeholder->use_empty()) {
337 auto UI = Placeholder->user_begin();
340 // If the using object isn't uniqued, just update the operands. This
341 // handles instructions and initializers for global variables.
342 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
343 UI.getUse().set(RealVal);
347 // Otherwise, we have a constant that uses the placeholder. Replace that
348 // constant with a new constant that has *all* placeholder uses updated.
349 Constant *UserC = cast<Constant>(U);
350 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
353 if (!isa<ConstantPlaceHolder>(*I)) {
354 // Not a placeholder reference.
356 } else if (*I == Placeholder) {
357 // Common case is that it just references this one placeholder.
360 // Otherwise, look up the placeholder in ResolveConstants.
361 ResolveConstantsTy::iterator It =
362 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
363 std::pair<Constant*, unsigned>(cast<Constant>(*I),
365 assert(It != ResolveConstants.end() && It->first == *I);
366 NewOp = operator[](It->second);
369 NewOps.push_back(cast<Constant>(NewOp));
372 // Make the new constant.
374 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
375 NewC = ConstantArray::get(UserCA->getType(), NewOps);
376 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
377 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
378 } else if (isa<ConstantVector>(UserC)) {
379 NewC = ConstantVector::get(NewOps);
381 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
382 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
385 UserC->replaceAllUsesWith(NewC);
386 UserC->destroyConstant();
390 // Update all ValueHandles, they should be the only users at this point.
391 Placeholder->replaceAllUsesWith(RealVal);
396 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
405 WeakVH &OldV = MDValuePtrs[Idx];
411 // If there was a forward reference to this value, replace it.
412 MDNode *PrevVal = cast<MDNode>(OldV);
413 OldV->replaceAllUsesWith(V);
414 MDNode::deleteTemporary(PrevVal);
415 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
417 MDValuePtrs[Idx] = V;
420 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
424 if (Value *V = MDValuePtrs[Idx]) {
425 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
429 // Create and return a placeholder, which will later be RAUW'd.
430 Value *V = MDNode::getTemporary(Context, None);
431 MDValuePtrs[Idx] = V;
435 Type *BitcodeReader::getTypeByID(unsigned ID) {
436 // The type table size is always specified correctly.
437 if (ID >= TypeList.size())
440 if (Type *Ty = TypeList[ID])
443 // If we have a forward reference, the only possible case is when it is to a
444 // named struct. Just create a placeholder for now.
445 return TypeList[ID] = StructType::create(Context);
449 //===----------------------------------------------------------------------===//
450 // Functions for parsing blocks from the bitcode file
451 //===----------------------------------------------------------------------===//
454 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
455 /// been decoded from the given integer. This function must stay in sync with
456 /// 'encodeLLVMAttributesForBitcode'.
457 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
458 uint64_t EncodedAttrs) {
459 // FIXME: Remove in 4.0.
461 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
462 // the bits above 31 down by 11 bits.
463 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
464 assert((!Alignment || isPowerOf2_32(Alignment)) &&
465 "Alignment must be a power of two.");
468 B.addAlignmentAttr(Alignment);
469 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
470 (EncodedAttrs & 0xffff));
473 error_code BitcodeReader::ParseAttributeBlock() {
474 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
475 return Error(InvalidRecord);
477 if (!MAttributes.empty())
478 return Error(InvalidMultipleBlocks);
480 SmallVector<uint64_t, 64> Record;
482 SmallVector<AttributeSet, 8> Attrs;
484 // Read all the records.
486 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
488 switch (Entry.Kind) {
489 case BitstreamEntry::SubBlock: // Handled for us already.
490 case BitstreamEntry::Error:
491 return Error(MalformedBlock);
492 case BitstreamEntry::EndBlock:
493 return error_code::success();
494 case BitstreamEntry::Record:
495 // The interesting case.
501 switch (Stream.readRecord(Entry.ID, Record)) {
502 default: // Default behavior: ignore.
504 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
505 // FIXME: Remove in 4.0.
506 if (Record.size() & 1)
507 return Error(InvalidRecord);
509 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
511 decodeLLVMAttributesForBitcode(B, Record[i+1]);
512 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
515 MAttributes.push_back(AttributeSet::get(Context, Attrs));
519 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
520 for (unsigned i = 0, e = Record.size(); i != e; ++i)
521 Attrs.push_back(MAttributeGroups[Record[i]]);
523 MAttributes.push_back(AttributeSet::get(Context, Attrs));
531 // Returns Attribute::None on unrecognized codes.
532 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
535 return Attribute::None;
536 case bitc::ATTR_KIND_ALIGNMENT:
537 return Attribute::Alignment;
538 case bitc::ATTR_KIND_ALWAYS_INLINE:
539 return Attribute::AlwaysInline;
540 case bitc::ATTR_KIND_BUILTIN:
541 return Attribute::Builtin;
542 case bitc::ATTR_KIND_BY_VAL:
543 return Attribute::ByVal;
544 case bitc::ATTR_KIND_IN_ALLOCA:
545 return Attribute::InAlloca;
546 case bitc::ATTR_KIND_COLD:
547 return Attribute::Cold;
548 case bitc::ATTR_KIND_INLINE_HINT:
549 return Attribute::InlineHint;
550 case bitc::ATTR_KIND_IN_REG:
551 return Attribute::InReg;
552 case bitc::ATTR_KIND_MIN_SIZE:
553 return Attribute::MinSize;
554 case bitc::ATTR_KIND_NAKED:
555 return Attribute::Naked;
556 case bitc::ATTR_KIND_NEST:
557 return Attribute::Nest;
558 case bitc::ATTR_KIND_NO_ALIAS:
559 return Attribute::NoAlias;
560 case bitc::ATTR_KIND_NO_BUILTIN:
561 return Attribute::NoBuiltin;
562 case bitc::ATTR_KIND_NO_CAPTURE:
563 return Attribute::NoCapture;
564 case bitc::ATTR_KIND_NO_DUPLICATE:
565 return Attribute::NoDuplicate;
566 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
567 return Attribute::NoImplicitFloat;
568 case bitc::ATTR_KIND_NO_INLINE:
569 return Attribute::NoInline;
570 case bitc::ATTR_KIND_NON_LAZY_BIND:
571 return Attribute::NonLazyBind;
572 case bitc::ATTR_KIND_NON_NULL:
573 return Attribute::NonNull;
574 case bitc::ATTR_KIND_NO_RED_ZONE:
575 return Attribute::NoRedZone;
576 case bitc::ATTR_KIND_NO_RETURN:
577 return Attribute::NoReturn;
578 case bitc::ATTR_KIND_NO_UNWIND:
579 return Attribute::NoUnwind;
580 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
581 return Attribute::OptimizeForSize;
582 case bitc::ATTR_KIND_OPTIMIZE_NONE:
583 return Attribute::OptimizeNone;
584 case bitc::ATTR_KIND_READ_NONE:
585 return Attribute::ReadNone;
586 case bitc::ATTR_KIND_READ_ONLY:
587 return Attribute::ReadOnly;
588 case bitc::ATTR_KIND_RETURNED:
589 return Attribute::Returned;
590 case bitc::ATTR_KIND_RETURNS_TWICE:
591 return Attribute::ReturnsTwice;
592 case bitc::ATTR_KIND_S_EXT:
593 return Attribute::SExt;
594 case bitc::ATTR_KIND_STACK_ALIGNMENT:
595 return Attribute::StackAlignment;
596 case bitc::ATTR_KIND_STACK_PROTECT:
597 return Attribute::StackProtect;
598 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
599 return Attribute::StackProtectReq;
600 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
601 return Attribute::StackProtectStrong;
602 case bitc::ATTR_KIND_STRUCT_RET:
603 return Attribute::StructRet;
604 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
605 return Attribute::SanitizeAddress;
606 case bitc::ATTR_KIND_SANITIZE_THREAD:
607 return Attribute::SanitizeThread;
608 case bitc::ATTR_KIND_SANITIZE_MEMORY:
609 return Attribute::SanitizeMemory;
610 case bitc::ATTR_KIND_UW_TABLE:
611 return Attribute::UWTable;
612 case bitc::ATTR_KIND_Z_EXT:
613 return Attribute::ZExt;
617 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
618 Attribute::AttrKind *Kind) {
619 *Kind = GetAttrFromCode(Code);
620 if (*Kind == Attribute::None)
621 return Error(InvalidValue);
622 return error_code::success();
625 error_code BitcodeReader::ParseAttributeGroupBlock() {
626 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
627 return Error(InvalidRecord);
629 if (!MAttributeGroups.empty())
630 return Error(InvalidMultipleBlocks);
632 SmallVector<uint64_t, 64> Record;
634 // Read all the records.
636 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
638 switch (Entry.Kind) {
639 case BitstreamEntry::SubBlock: // Handled for us already.
640 case BitstreamEntry::Error:
641 return Error(MalformedBlock);
642 case BitstreamEntry::EndBlock:
643 return error_code::success();
644 case BitstreamEntry::Record:
645 // The interesting case.
651 switch (Stream.readRecord(Entry.ID, Record)) {
652 default: // Default behavior: ignore.
654 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
655 if (Record.size() < 3)
656 return Error(InvalidRecord);
658 uint64_t GrpID = Record[0];
659 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
662 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
663 if (Record[i] == 0) { // Enum attribute
664 Attribute::AttrKind Kind;
665 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
668 B.addAttribute(Kind);
669 } else if (Record[i] == 1) { // Align attribute
670 Attribute::AttrKind Kind;
671 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
673 if (Kind == Attribute::Alignment)
674 B.addAlignmentAttr(Record[++i]);
676 B.addStackAlignmentAttr(Record[++i]);
677 } else { // String attribute
678 assert((Record[i] == 3 || Record[i] == 4) &&
679 "Invalid attribute group entry");
680 bool HasValue = (Record[i++] == 4);
681 SmallString<64> KindStr;
682 SmallString<64> ValStr;
684 while (Record[i] != 0 && i != e)
685 KindStr += Record[i++];
686 assert(Record[i] == 0 && "Kind string not null terminated");
689 // Has a value associated with it.
690 ++i; // Skip the '0' that terminates the "kind" string.
691 while (Record[i] != 0 && i != e)
692 ValStr += Record[i++];
693 assert(Record[i] == 0 && "Value string not null terminated");
696 B.addAttribute(KindStr.str(), ValStr.str());
700 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
707 error_code BitcodeReader::ParseTypeTable() {
708 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
709 return Error(InvalidRecord);
711 return ParseTypeTableBody();
714 error_code BitcodeReader::ParseTypeTableBody() {
715 if (!TypeList.empty())
716 return Error(InvalidMultipleBlocks);
718 SmallVector<uint64_t, 64> Record;
719 unsigned NumRecords = 0;
721 SmallString<64> TypeName;
723 // Read all the records for this type table.
725 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
727 switch (Entry.Kind) {
728 case BitstreamEntry::SubBlock: // Handled for us already.
729 case BitstreamEntry::Error:
730 return Error(MalformedBlock);
731 case BitstreamEntry::EndBlock:
732 if (NumRecords != TypeList.size())
733 return Error(MalformedBlock);
734 return error_code::success();
735 case BitstreamEntry::Record:
736 // The interesting case.
742 Type *ResultTy = nullptr;
743 switch (Stream.readRecord(Entry.ID, Record)) {
745 return Error(InvalidValue);
746 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
747 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
748 // type list. This allows us to reserve space.
749 if (Record.size() < 1)
750 return Error(InvalidRecord);
751 TypeList.resize(Record[0]);
753 case bitc::TYPE_CODE_VOID: // VOID
754 ResultTy = Type::getVoidTy(Context);
756 case bitc::TYPE_CODE_HALF: // HALF
757 ResultTy = Type::getHalfTy(Context);
759 case bitc::TYPE_CODE_FLOAT: // FLOAT
760 ResultTy = Type::getFloatTy(Context);
762 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
763 ResultTy = Type::getDoubleTy(Context);
765 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
766 ResultTy = Type::getX86_FP80Ty(Context);
768 case bitc::TYPE_CODE_FP128: // FP128
769 ResultTy = Type::getFP128Ty(Context);
771 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
772 ResultTy = Type::getPPC_FP128Ty(Context);
774 case bitc::TYPE_CODE_LABEL: // LABEL
775 ResultTy = Type::getLabelTy(Context);
777 case bitc::TYPE_CODE_METADATA: // METADATA
778 ResultTy = Type::getMetadataTy(Context);
780 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
781 ResultTy = Type::getX86_MMXTy(Context);
783 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
784 if (Record.size() < 1)
785 return Error(InvalidRecord);
787 ResultTy = IntegerType::get(Context, Record[0]);
789 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
790 // [pointee type, address space]
791 if (Record.size() < 1)
792 return Error(InvalidRecord);
793 unsigned AddressSpace = 0;
794 if (Record.size() == 2)
795 AddressSpace = Record[1];
796 ResultTy = getTypeByID(Record[0]);
798 return Error(InvalidType);
799 ResultTy = PointerType::get(ResultTy, AddressSpace);
802 case bitc::TYPE_CODE_FUNCTION_OLD: {
803 // FIXME: attrid is dead, remove it in LLVM 4.0
804 // FUNCTION: [vararg, attrid, retty, paramty x N]
805 if (Record.size() < 3)
806 return Error(InvalidRecord);
807 SmallVector<Type*, 8> ArgTys;
808 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
809 if (Type *T = getTypeByID(Record[i]))
815 ResultTy = getTypeByID(Record[2]);
816 if (!ResultTy || ArgTys.size() < Record.size()-3)
817 return Error(InvalidType);
819 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
822 case bitc::TYPE_CODE_FUNCTION: {
823 // FUNCTION: [vararg, retty, paramty x N]
824 if (Record.size() < 2)
825 return Error(InvalidRecord);
826 SmallVector<Type*, 8> ArgTys;
827 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
828 if (Type *T = getTypeByID(Record[i]))
834 ResultTy = getTypeByID(Record[1]);
835 if (!ResultTy || ArgTys.size() < Record.size()-2)
836 return Error(InvalidType);
838 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
841 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
842 if (Record.size() < 1)
843 return Error(InvalidRecord);
844 SmallVector<Type*, 8> EltTys;
845 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
846 if (Type *T = getTypeByID(Record[i]))
851 if (EltTys.size() != Record.size()-1)
852 return Error(InvalidType);
853 ResultTy = StructType::get(Context, EltTys, Record[0]);
856 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
857 if (ConvertToString(Record, 0, TypeName))
858 return Error(InvalidRecord);
861 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
862 if (Record.size() < 1)
863 return Error(InvalidRecord);
865 if (NumRecords >= TypeList.size())
866 return Error(InvalidTYPETable);
868 // Check to see if this was forward referenced, if so fill in the temp.
869 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
871 Res->setName(TypeName);
872 TypeList[NumRecords] = nullptr;
873 } else // Otherwise, create a new struct.
874 Res = StructType::create(Context, TypeName);
877 SmallVector<Type*, 8> EltTys;
878 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
879 if (Type *T = getTypeByID(Record[i]))
884 if (EltTys.size() != Record.size()-1)
885 return Error(InvalidRecord);
886 Res->setBody(EltTys, Record[0]);
890 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
891 if (Record.size() != 1)
892 return Error(InvalidRecord);
894 if (NumRecords >= TypeList.size())
895 return Error(InvalidTYPETable);
897 // Check to see if this was forward referenced, if so fill in the temp.
898 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
900 Res->setName(TypeName);
901 TypeList[NumRecords] = nullptr;
902 } else // Otherwise, create a new struct with no body.
903 Res = StructType::create(Context, TypeName);
908 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
909 if (Record.size() < 2)
910 return Error(InvalidRecord);
911 if ((ResultTy = getTypeByID(Record[1])))
912 ResultTy = ArrayType::get(ResultTy, Record[0]);
914 return Error(InvalidType);
916 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
917 if (Record.size() < 2)
918 return Error(InvalidRecord);
919 if ((ResultTy = getTypeByID(Record[1])))
920 ResultTy = VectorType::get(ResultTy, Record[0]);
922 return Error(InvalidType);
926 if (NumRecords >= TypeList.size())
927 return Error(InvalidTYPETable);
928 assert(ResultTy && "Didn't read a type?");
929 assert(!TypeList[NumRecords] && "Already read type?");
930 TypeList[NumRecords++] = ResultTy;
934 error_code BitcodeReader::ParseValueSymbolTable() {
935 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
936 return Error(InvalidRecord);
938 SmallVector<uint64_t, 64> Record;
940 // Read all the records for this value table.
941 SmallString<128> ValueName;
943 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
945 switch (Entry.Kind) {
946 case BitstreamEntry::SubBlock: // Handled for us already.
947 case BitstreamEntry::Error:
948 return Error(MalformedBlock);
949 case BitstreamEntry::EndBlock:
950 return error_code::success();
951 case BitstreamEntry::Record:
952 // The interesting case.
958 switch (Stream.readRecord(Entry.ID, Record)) {
959 default: // Default behavior: unknown type.
961 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
962 if (ConvertToString(Record, 1, ValueName))
963 return Error(InvalidRecord);
964 unsigned ValueID = Record[0];
965 if (ValueID >= ValueList.size() || !ValueList[ValueID])
966 return Error(InvalidRecord);
967 Value *V = ValueList[ValueID];
969 V->setName(StringRef(ValueName.data(), ValueName.size()));
973 case bitc::VST_CODE_BBENTRY: {
974 if (ConvertToString(Record, 1, ValueName))
975 return Error(InvalidRecord);
976 BasicBlock *BB = getBasicBlock(Record[0]);
978 return Error(InvalidRecord);
980 BB->setName(StringRef(ValueName.data(), ValueName.size()));
988 error_code BitcodeReader::ParseMetadata() {
989 unsigned NextMDValueNo = MDValueList.size();
991 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
992 return Error(InvalidRecord);
994 SmallVector<uint64_t, 64> Record;
996 // Read all the records.
998 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1000 switch (Entry.Kind) {
1001 case BitstreamEntry::SubBlock: // Handled for us already.
1002 case BitstreamEntry::Error:
1003 return Error(MalformedBlock);
1004 case BitstreamEntry::EndBlock:
1005 return error_code::success();
1006 case BitstreamEntry::Record:
1007 // The interesting case.
1011 bool IsFunctionLocal = false;
1014 unsigned Code = Stream.readRecord(Entry.ID, Record);
1016 default: // Default behavior: ignore.
1018 case bitc::METADATA_NAME: {
1019 // Read name of the named metadata.
1020 SmallString<8> Name(Record.begin(), Record.end());
1022 Code = Stream.ReadCode();
1024 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1025 unsigned NextBitCode = Stream.readRecord(Code, Record);
1026 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1028 // Read named metadata elements.
1029 unsigned Size = Record.size();
1030 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1031 for (unsigned i = 0; i != Size; ++i) {
1032 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1034 return Error(InvalidRecord);
1035 NMD->addOperand(MD);
1039 case bitc::METADATA_FN_NODE:
1040 IsFunctionLocal = true;
1042 case bitc::METADATA_NODE: {
1043 if (Record.size() % 2 == 1)
1044 return Error(InvalidRecord);
1046 unsigned Size = Record.size();
1047 SmallVector<Value*, 8> Elts;
1048 for (unsigned i = 0; i != Size; i += 2) {
1049 Type *Ty = getTypeByID(Record[i]);
1051 return Error(InvalidRecord);
1052 if (Ty->isMetadataTy())
1053 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1054 else if (!Ty->isVoidTy())
1055 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1057 Elts.push_back(nullptr);
1059 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1060 IsFunctionLocal = false;
1061 MDValueList.AssignValue(V, NextMDValueNo++);
1064 case bitc::METADATA_STRING: {
1065 SmallString<8> String(Record.begin(), Record.end());
1066 Value *V = MDString::get(Context, String);
1067 MDValueList.AssignValue(V, NextMDValueNo++);
1070 case bitc::METADATA_KIND: {
1071 if (Record.size() < 2)
1072 return Error(InvalidRecord);
1074 unsigned Kind = Record[0];
1075 SmallString<8> Name(Record.begin()+1, Record.end());
1077 unsigned NewKind = TheModule->getMDKindID(Name.str());
1078 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1079 return Error(ConflictingMETADATA_KINDRecords);
1086 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1087 /// the LSB for dense VBR encoding.
1088 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1093 // There is no such thing as -0 with integers. "-0" really means MININT.
1097 // FIXME: Delete this in LLVM 4.0 and just assert that the aliasee is a
1099 static GlobalObject &
1100 getGlobalObjectInExpr(const DenseMap<GlobalAlias *, Constant *> &Map,
1102 auto *GO = dyn_cast<GlobalObject>(&C);
1106 auto *GA = dyn_cast<GlobalAlias>(&C);
1108 return getGlobalObjectInExpr(Map, *Map.find(GA)->second);
1110 auto &CE = cast<ConstantExpr>(C);
1111 assert(CE.getOpcode() == Instruction::BitCast ||
1112 CE.getOpcode() == Instruction::GetElementPtr ||
1113 CE.getOpcode() == Instruction::AddrSpaceCast);
1114 if (CE.getOpcode() == Instruction::GetElementPtr)
1115 assert(cast<GEPOperator>(CE).hasAllZeroIndices());
1116 return getGlobalObjectInExpr(Map, *CE.getOperand(0));
1119 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1120 /// values and aliases that we can.
1121 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 // FIXME: Delete this in LLVM 4.0
1145 // Older versions of llvm could write an alias pointing to another. We cannot
1146 // construct those aliases, so we first collect an alias to aliasee expression
1147 // and then compute the actual aliasee.
1148 DenseMap<GlobalAlias *, Constant *> AliasInit;
1150 while (!AliasInitWorklist.empty()) {
1151 unsigned ValID = AliasInitWorklist.back().second;
1152 if (ValID >= ValueList.size()) {
1153 AliasInits.push_back(AliasInitWorklist.back());
1155 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1156 AliasInit.insert(std::make_pair(AliasInitWorklist.back().first, C));
1158 return Error(ExpectedConstant);
1160 AliasInitWorklist.pop_back();
1163 for (auto &Pair : AliasInit) {
1164 auto &GO = getGlobalObjectInExpr(AliasInit, *Pair.second);
1165 Pair.first->setAliasee(&GO);
1168 while (!FunctionPrefixWorklist.empty()) {
1169 unsigned ValID = FunctionPrefixWorklist.back().second;
1170 if (ValID >= ValueList.size()) {
1171 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1173 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1174 FunctionPrefixWorklist.back().first->setPrefixData(C);
1176 return Error(ExpectedConstant);
1178 FunctionPrefixWorklist.pop_back();
1181 return error_code::success();
1184 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1185 SmallVector<uint64_t, 8> Words(Vals.size());
1186 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1187 BitcodeReader::decodeSignRotatedValue);
1189 return APInt(TypeBits, Words);
1192 error_code BitcodeReader::ParseConstants() {
1193 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1194 return Error(InvalidRecord);
1196 SmallVector<uint64_t, 64> Record;
1198 // Read all the records for this value table.
1199 Type *CurTy = Type::getInt32Ty(Context);
1200 unsigned NextCstNo = ValueList.size();
1202 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1204 switch (Entry.Kind) {
1205 case BitstreamEntry::SubBlock: // Handled for us already.
1206 case BitstreamEntry::Error:
1207 return Error(MalformedBlock);
1208 case BitstreamEntry::EndBlock:
1209 if (NextCstNo != ValueList.size())
1210 return Error(InvalidConstantReference);
1212 // Once all the constants have been read, go through and resolve forward
1214 ValueList.ResolveConstantForwardRefs();
1215 return error_code::success();
1216 case BitstreamEntry::Record:
1217 // The interesting case.
1224 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1226 default: // Default behavior: unknown constant
1227 case bitc::CST_CODE_UNDEF: // UNDEF
1228 V = UndefValue::get(CurTy);
1230 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1232 return Error(InvalidRecord);
1233 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1234 return Error(InvalidRecord);
1235 CurTy = TypeList[Record[0]];
1236 continue; // Skip the ValueList manipulation.
1237 case bitc::CST_CODE_NULL: // NULL
1238 V = Constant::getNullValue(CurTy);
1240 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1241 if (!CurTy->isIntegerTy() || Record.empty())
1242 return Error(InvalidRecord);
1243 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1245 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1246 if (!CurTy->isIntegerTy() || Record.empty())
1247 return Error(InvalidRecord);
1249 APInt VInt = ReadWideAPInt(Record,
1250 cast<IntegerType>(CurTy)->getBitWidth());
1251 V = ConstantInt::get(Context, VInt);
1255 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1257 return Error(InvalidRecord);
1258 if (CurTy->isHalfTy())
1259 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1260 APInt(16, (uint16_t)Record[0])));
1261 else if (CurTy->isFloatTy())
1262 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1263 APInt(32, (uint32_t)Record[0])));
1264 else if (CurTy->isDoubleTy())
1265 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1266 APInt(64, Record[0])));
1267 else if (CurTy->isX86_FP80Ty()) {
1268 // Bits are not stored the same way as a normal i80 APInt, compensate.
1269 uint64_t Rearrange[2];
1270 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1271 Rearrange[1] = Record[0] >> 48;
1272 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1273 APInt(80, Rearrange)));
1274 } else if (CurTy->isFP128Ty())
1275 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1276 APInt(128, Record)));
1277 else if (CurTy->isPPC_FP128Ty())
1278 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1279 APInt(128, Record)));
1281 V = UndefValue::get(CurTy);
1285 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1287 return Error(InvalidRecord);
1289 unsigned Size = Record.size();
1290 SmallVector<Constant*, 16> Elts;
1292 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1293 for (unsigned i = 0; i != Size; ++i)
1294 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1295 STy->getElementType(i)));
1296 V = ConstantStruct::get(STy, Elts);
1297 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1298 Type *EltTy = ATy->getElementType();
1299 for (unsigned i = 0; i != Size; ++i)
1300 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1301 V = ConstantArray::get(ATy, Elts);
1302 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1303 Type *EltTy = VTy->getElementType();
1304 for (unsigned i = 0; i != Size; ++i)
1305 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1306 V = ConstantVector::get(Elts);
1308 V = UndefValue::get(CurTy);
1312 case bitc::CST_CODE_STRING: // STRING: [values]
1313 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1315 return Error(InvalidRecord);
1317 SmallString<16> Elts(Record.begin(), Record.end());
1318 V = ConstantDataArray::getString(Context, Elts,
1319 BitCode == bitc::CST_CODE_CSTRING);
1322 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1324 return Error(InvalidRecord);
1326 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1327 unsigned Size = Record.size();
1329 if (EltTy->isIntegerTy(8)) {
1330 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1331 if (isa<VectorType>(CurTy))
1332 V = ConstantDataVector::get(Context, Elts);
1334 V = ConstantDataArray::get(Context, Elts);
1335 } else if (EltTy->isIntegerTy(16)) {
1336 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1337 if (isa<VectorType>(CurTy))
1338 V = ConstantDataVector::get(Context, Elts);
1340 V = ConstantDataArray::get(Context, Elts);
1341 } else if (EltTy->isIntegerTy(32)) {
1342 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1343 if (isa<VectorType>(CurTy))
1344 V = ConstantDataVector::get(Context, Elts);
1346 V = ConstantDataArray::get(Context, Elts);
1347 } else if (EltTy->isIntegerTy(64)) {
1348 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1349 if (isa<VectorType>(CurTy))
1350 V = ConstantDataVector::get(Context, Elts);
1352 V = ConstantDataArray::get(Context, Elts);
1353 } else if (EltTy->isFloatTy()) {
1354 SmallVector<float, 16> Elts(Size);
1355 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1356 if (isa<VectorType>(CurTy))
1357 V = ConstantDataVector::get(Context, Elts);
1359 V = ConstantDataArray::get(Context, Elts);
1360 } else if (EltTy->isDoubleTy()) {
1361 SmallVector<double, 16> Elts(Size);
1362 std::transform(Record.begin(), Record.end(), Elts.begin(),
1364 if (isa<VectorType>(CurTy))
1365 V = ConstantDataVector::get(Context, Elts);
1367 V = ConstantDataArray::get(Context, Elts);
1369 return Error(InvalidTypeForValue);
1374 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1375 if (Record.size() < 3)
1376 return Error(InvalidRecord);
1377 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1379 V = UndefValue::get(CurTy); // Unknown binop.
1381 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1382 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1384 if (Record.size() >= 4) {
1385 if (Opc == Instruction::Add ||
1386 Opc == Instruction::Sub ||
1387 Opc == Instruction::Mul ||
1388 Opc == Instruction::Shl) {
1389 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1390 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1391 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1392 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1393 } else if (Opc == Instruction::SDiv ||
1394 Opc == Instruction::UDiv ||
1395 Opc == Instruction::LShr ||
1396 Opc == Instruction::AShr) {
1397 if (Record[3] & (1 << bitc::PEO_EXACT))
1398 Flags |= SDivOperator::IsExact;
1401 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1405 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1406 if (Record.size() < 3)
1407 return Error(InvalidRecord);
1408 int Opc = GetDecodedCastOpcode(Record[0]);
1410 V = UndefValue::get(CurTy); // Unknown cast.
1412 Type *OpTy = getTypeByID(Record[1]);
1414 return Error(InvalidRecord);
1415 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1416 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1417 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1421 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1422 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1423 if (Record.size() & 1)
1424 return Error(InvalidRecord);
1425 SmallVector<Constant*, 16> Elts;
1426 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1427 Type *ElTy = getTypeByID(Record[i]);
1429 return Error(InvalidRecord);
1430 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1432 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1433 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1435 bitc::CST_CODE_CE_INBOUNDS_GEP);
1438 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1439 if (Record.size() < 3)
1440 return Error(InvalidRecord);
1442 Type *SelectorTy = Type::getInt1Ty(Context);
1444 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1445 // vector. Otherwise, it must be a single bit.
1446 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1447 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1448 VTy->getNumElements());
1450 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1452 ValueList.getConstantFwdRef(Record[1],CurTy),
1453 ValueList.getConstantFwdRef(Record[2],CurTy));
1456 case bitc::CST_CODE_CE_EXTRACTELT
1457 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1458 if (Record.size() < 3)
1459 return Error(InvalidRecord);
1461 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1463 return Error(InvalidRecord);
1464 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1465 Constant *Op1 = nullptr;
1466 if (Record.size() == 4) {
1467 Type *IdxTy = getTypeByID(Record[2]);
1469 return Error(InvalidRecord);
1470 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1471 } else // TODO: Remove with llvm 4.0
1472 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1474 return Error(InvalidRecord);
1475 V = ConstantExpr::getExtractElement(Op0, Op1);
1478 case bitc::CST_CODE_CE_INSERTELT
1479 : { // CE_INSERTELT: [opval, opval, opty, opval]
1480 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1481 if (Record.size() < 3 || !OpTy)
1482 return Error(InvalidRecord);
1483 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1484 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1485 OpTy->getElementType());
1486 Constant *Op2 = nullptr;
1487 if (Record.size() == 4) {
1488 Type *IdxTy = getTypeByID(Record[2]);
1490 return Error(InvalidRecord);
1491 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1492 } else // TODO: Remove with llvm 4.0
1493 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1495 return Error(InvalidRecord);
1496 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1499 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1500 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1501 if (Record.size() < 3 || !OpTy)
1502 return Error(InvalidRecord);
1503 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1504 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1505 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1506 OpTy->getNumElements());
1507 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1508 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1511 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1512 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1514 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1515 if (Record.size() < 4 || !RTy || !OpTy)
1516 return Error(InvalidRecord);
1517 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1518 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1519 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1520 RTy->getNumElements());
1521 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1522 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1525 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1526 if (Record.size() < 4)
1527 return Error(InvalidRecord);
1528 Type *OpTy = getTypeByID(Record[0]);
1530 return Error(InvalidRecord);
1531 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1532 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1534 if (OpTy->isFPOrFPVectorTy())
1535 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1537 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1540 // This maintains backward compatibility, pre-asm dialect keywords.
1541 // FIXME: Remove with the 4.0 release.
1542 case bitc::CST_CODE_INLINEASM_OLD: {
1543 if (Record.size() < 2)
1544 return Error(InvalidRecord);
1545 std::string AsmStr, ConstrStr;
1546 bool HasSideEffects = Record[0] & 1;
1547 bool IsAlignStack = Record[0] >> 1;
1548 unsigned AsmStrSize = Record[1];
1549 if (2+AsmStrSize >= Record.size())
1550 return Error(InvalidRecord);
1551 unsigned ConstStrSize = Record[2+AsmStrSize];
1552 if (3+AsmStrSize+ConstStrSize > Record.size())
1553 return Error(InvalidRecord);
1555 for (unsigned i = 0; i != AsmStrSize; ++i)
1556 AsmStr += (char)Record[2+i];
1557 for (unsigned i = 0; i != ConstStrSize; ++i)
1558 ConstrStr += (char)Record[3+AsmStrSize+i];
1559 PointerType *PTy = cast<PointerType>(CurTy);
1560 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1561 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1564 // This version adds support for the asm dialect keywords (e.g.,
1566 case bitc::CST_CODE_INLINEASM: {
1567 if (Record.size() < 2)
1568 return Error(InvalidRecord);
1569 std::string AsmStr, ConstrStr;
1570 bool HasSideEffects = Record[0] & 1;
1571 bool IsAlignStack = (Record[0] >> 1) & 1;
1572 unsigned AsmDialect = Record[0] >> 2;
1573 unsigned AsmStrSize = Record[1];
1574 if (2+AsmStrSize >= Record.size())
1575 return Error(InvalidRecord);
1576 unsigned ConstStrSize = Record[2+AsmStrSize];
1577 if (3+AsmStrSize+ConstStrSize > Record.size())
1578 return Error(InvalidRecord);
1580 for (unsigned i = 0; i != AsmStrSize; ++i)
1581 AsmStr += (char)Record[2+i];
1582 for (unsigned i = 0; i != ConstStrSize; ++i)
1583 ConstrStr += (char)Record[3+AsmStrSize+i];
1584 PointerType *PTy = cast<PointerType>(CurTy);
1585 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1586 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1587 InlineAsm::AsmDialect(AsmDialect));
1590 case bitc::CST_CODE_BLOCKADDRESS:{
1591 if (Record.size() < 3)
1592 return Error(InvalidRecord);
1593 Type *FnTy = getTypeByID(Record[0]);
1595 return Error(InvalidRecord);
1597 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1599 return Error(InvalidRecord);
1601 // If the function is already parsed we can insert the block address right
1604 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1605 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1607 return Error(InvalidID);
1610 V = BlockAddress::get(Fn, BBI);
1612 // Otherwise insert a placeholder and remember it so it can be inserted
1613 // when the function is parsed.
1614 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1615 Type::getInt8Ty(Context),
1616 false, GlobalValue::InternalLinkage,
1618 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1625 ValueList.AssignValue(V, NextCstNo);
1630 error_code BitcodeReader::ParseUseLists() {
1631 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1632 return Error(InvalidRecord);
1634 SmallVector<uint64_t, 64> Record;
1636 // Read all the records.
1638 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1640 switch (Entry.Kind) {
1641 case BitstreamEntry::SubBlock: // Handled for us already.
1642 case BitstreamEntry::Error:
1643 return Error(MalformedBlock);
1644 case BitstreamEntry::EndBlock:
1645 return error_code::success();
1646 case BitstreamEntry::Record:
1647 // The interesting case.
1651 // Read a use list record.
1653 switch (Stream.readRecord(Entry.ID, Record)) {
1654 default: // Default behavior: unknown type.
1656 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1657 unsigned RecordLength = Record.size();
1658 if (RecordLength < 1)
1659 return Error(InvalidRecord);
1660 UseListRecords.push_back(Record);
1667 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1668 /// remember where it is and then skip it. This lets us lazily deserialize the
1670 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1671 // Get the function we are talking about.
1672 if (FunctionsWithBodies.empty())
1673 return Error(InsufficientFunctionProtos);
1675 Function *Fn = FunctionsWithBodies.back();
1676 FunctionsWithBodies.pop_back();
1678 // Save the current stream state.
1679 uint64_t CurBit = Stream.GetCurrentBitNo();
1680 DeferredFunctionInfo[Fn] = CurBit;
1682 // Skip over the function block for now.
1683 if (Stream.SkipBlock())
1684 return Error(InvalidRecord);
1685 return error_code::success();
1688 error_code BitcodeReader::GlobalCleanup() {
1689 // Patch the initializers for globals and aliases up.
1690 ResolveGlobalAndAliasInits();
1691 if (!GlobalInits.empty() || !AliasInits.empty())
1692 return Error(MalformedGlobalInitializerSet);
1694 // Look for intrinsic functions which need to be upgraded at some point
1695 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1698 if (UpgradeIntrinsicFunction(FI, NewFn))
1699 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1702 // Look for global variables which need to be renamed.
1703 for (Module::global_iterator
1704 GI = TheModule->global_begin(), GE = TheModule->global_end();
1706 GlobalVariable *GV = GI++;
1707 UpgradeGlobalVariable(GV);
1710 // Force deallocation of memory for these vectors to favor the client that
1711 // want lazy deserialization.
1712 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1713 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1714 return error_code::success();
1717 error_code BitcodeReader::ParseModule(bool Resume) {
1719 Stream.JumpToBit(NextUnreadBit);
1720 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1721 return Error(InvalidRecord);
1723 SmallVector<uint64_t, 64> Record;
1724 std::vector<std::string> SectionTable;
1725 std::vector<std::string> GCTable;
1727 // Read all the records for this module.
1729 BitstreamEntry Entry = Stream.advance();
1731 switch (Entry.Kind) {
1732 case BitstreamEntry::Error:
1733 return Error(MalformedBlock);
1734 case BitstreamEntry::EndBlock:
1735 return GlobalCleanup();
1737 case BitstreamEntry::SubBlock:
1739 default: // Skip unknown content.
1740 if (Stream.SkipBlock())
1741 return Error(InvalidRecord);
1743 case bitc::BLOCKINFO_BLOCK_ID:
1744 if (Stream.ReadBlockInfoBlock())
1745 return Error(MalformedBlock);
1747 case bitc::PARAMATTR_BLOCK_ID:
1748 if (error_code EC = ParseAttributeBlock())
1751 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1752 if (error_code EC = ParseAttributeGroupBlock())
1755 case bitc::TYPE_BLOCK_ID_NEW:
1756 if (error_code EC = ParseTypeTable())
1759 case bitc::VALUE_SYMTAB_BLOCK_ID:
1760 if (error_code EC = ParseValueSymbolTable())
1762 SeenValueSymbolTable = true;
1764 case bitc::CONSTANTS_BLOCK_ID:
1765 if (error_code EC = ParseConstants())
1767 if (error_code EC = ResolveGlobalAndAliasInits())
1770 case bitc::METADATA_BLOCK_ID:
1771 if (error_code EC = ParseMetadata())
1774 case bitc::FUNCTION_BLOCK_ID:
1775 // If this is the first function body we've seen, reverse the
1776 // FunctionsWithBodies list.
1777 if (!SeenFirstFunctionBody) {
1778 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1779 if (error_code EC = GlobalCleanup())
1781 SeenFirstFunctionBody = true;
1784 if (error_code EC = RememberAndSkipFunctionBody())
1786 // For streaming bitcode, suspend parsing when we reach the function
1787 // bodies. Subsequent materialization calls will resume it when
1788 // necessary. For streaming, the function bodies must be at the end of
1789 // the bitcode. If the bitcode file is old, the symbol table will be
1790 // at the end instead and will not have been seen yet. In this case,
1791 // just finish the parse now.
1792 if (LazyStreamer && SeenValueSymbolTable) {
1793 NextUnreadBit = Stream.GetCurrentBitNo();
1794 return error_code::success();
1797 case bitc::USELIST_BLOCK_ID:
1798 if (error_code EC = ParseUseLists())
1804 case BitstreamEntry::Record:
1805 // The interesting case.
1811 switch (Stream.readRecord(Entry.ID, Record)) {
1812 default: break; // Default behavior, ignore unknown content.
1813 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1814 if (Record.size() < 1)
1815 return Error(InvalidRecord);
1816 // Only version #0 and #1 are supported so far.
1817 unsigned module_version = Record[0];
1818 switch (module_version) {
1820 return Error(InvalidValue);
1822 UseRelativeIDs = false;
1825 UseRelativeIDs = true;
1830 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1832 if (ConvertToString(Record, 0, S))
1833 return Error(InvalidRecord);
1834 TheModule->setTargetTriple(S);
1837 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1839 if (ConvertToString(Record, 0, S))
1840 return Error(InvalidRecord);
1841 TheModule->setDataLayout(S);
1844 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1846 if (ConvertToString(Record, 0, S))
1847 return Error(InvalidRecord);
1848 TheModule->setModuleInlineAsm(S);
1851 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1852 // FIXME: Remove in 4.0.
1854 if (ConvertToString(Record, 0, S))
1855 return Error(InvalidRecord);
1859 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1861 if (ConvertToString(Record, 0, S))
1862 return Error(InvalidRecord);
1863 SectionTable.push_back(S);
1866 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1868 if (ConvertToString(Record, 0, S))
1869 return Error(InvalidRecord);
1870 GCTable.push_back(S);
1873 // GLOBALVAR: [pointer type, isconst, initid,
1874 // linkage, alignment, section, visibility, threadlocal,
1875 // unnamed_addr, dllstorageclass]
1876 case bitc::MODULE_CODE_GLOBALVAR: {
1877 if (Record.size() < 6)
1878 return Error(InvalidRecord);
1879 Type *Ty = getTypeByID(Record[0]);
1881 return Error(InvalidRecord);
1882 if (!Ty->isPointerTy())
1883 return Error(InvalidTypeForValue);
1884 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1885 Ty = cast<PointerType>(Ty)->getElementType();
1887 bool isConstant = Record[1];
1888 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1889 unsigned Alignment = (1 << Record[4]) >> 1;
1890 std::string Section;
1892 if (Record[5]-1 >= SectionTable.size())
1893 return Error(InvalidID);
1894 Section = SectionTable[Record[5]-1];
1896 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1897 // Local linkage must have default visibility.
1898 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1899 // FIXME: Change to an error if non-default in 4.0.
1900 Visibility = GetDecodedVisibility(Record[6]);
1902 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1903 if (Record.size() > 7)
1904 TLM = GetDecodedThreadLocalMode(Record[7]);
1906 bool UnnamedAddr = false;
1907 if (Record.size() > 8)
1908 UnnamedAddr = Record[8];
1910 bool ExternallyInitialized = false;
1911 if (Record.size() > 9)
1912 ExternallyInitialized = Record[9];
1914 GlobalVariable *NewGV =
1915 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1916 TLM, AddressSpace, ExternallyInitialized);
1917 NewGV->setAlignment(Alignment);
1918 if (!Section.empty())
1919 NewGV->setSection(Section);
1920 NewGV->setVisibility(Visibility);
1921 NewGV->setUnnamedAddr(UnnamedAddr);
1923 if (Record.size() > 10)
1924 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1926 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1928 ValueList.push_back(NewGV);
1930 // Remember which value to use for the global initializer.
1931 if (unsigned InitID = Record[2])
1932 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1935 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1936 // alignment, section, visibility, gc, unnamed_addr,
1938 case bitc::MODULE_CODE_FUNCTION: {
1939 if (Record.size() < 8)
1940 return Error(InvalidRecord);
1941 Type *Ty = getTypeByID(Record[0]);
1943 return Error(InvalidRecord);
1944 if (!Ty->isPointerTy())
1945 return Error(InvalidTypeForValue);
1947 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1949 return Error(InvalidTypeForValue);
1951 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1954 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1955 bool isProto = Record[2];
1956 Func->setLinkage(GetDecodedLinkage(Record[3]));
1957 Func->setAttributes(getAttributes(Record[4]));
1959 Func->setAlignment((1 << Record[5]) >> 1);
1961 if (Record[6]-1 >= SectionTable.size())
1962 return Error(InvalidID);
1963 Func->setSection(SectionTable[Record[6]-1]);
1965 // Local linkage must have default visibility.
1966 if (!Func->hasLocalLinkage())
1967 // FIXME: Change to an error if non-default in 4.0.
1968 Func->setVisibility(GetDecodedVisibility(Record[7]));
1969 if (Record.size() > 8 && Record[8]) {
1970 if (Record[8]-1 > GCTable.size())
1971 return Error(InvalidID);
1972 Func->setGC(GCTable[Record[8]-1].c_str());
1974 bool UnnamedAddr = false;
1975 if (Record.size() > 9)
1976 UnnamedAddr = Record[9];
1977 Func->setUnnamedAddr(UnnamedAddr);
1978 if (Record.size() > 10 && Record[10] != 0)
1979 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1981 if (Record.size() > 11)
1982 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1984 UpgradeDLLImportExportLinkage(Func, Record[3]);
1986 ValueList.push_back(Func);
1988 // If this is a function with a body, remember the prototype we are
1989 // creating now, so that we can match up the body with them later.
1991 FunctionsWithBodies.push_back(Func);
1992 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1996 // ALIAS: [alias type, aliasee val#, linkage]
1997 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
1998 case bitc::MODULE_CODE_ALIAS: {
1999 if (Record.size() < 3)
2000 return Error(InvalidRecord);
2001 Type *Ty = getTypeByID(Record[0]);
2003 return Error(InvalidRecord);
2004 auto *PTy = dyn_cast<PointerType>(Ty);
2006 return Error(InvalidTypeForValue);
2009 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2010 GetDecodedLinkage(Record[2]), "", TheModule);
2011 // Old bitcode files didn't have visibility field.
2012 // Local linkage must have default visibility.
2013 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2014 // FIXME: Change to an error if non-default in 4.0.
2015 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2016 if (Record.size() > 4)
2017 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2019 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2020 if (Record.size() > 5)
2021 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2022 ValueList.push_back(NewGA);
2023 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2026 /// MODULE_CODE_PURGEVALS: [numvals]
2027 case bitc::MODULE_CODE_PURGEVALS:
2028 // Trim down the value list to the specified size.
2029 if (Record.size() < 1 || Record[0] > ValueList.size())
2030 return Error(InvalidRecord);
2031 ValueList.shrinkTo(Record[0]);
2038 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2039 TheModule = nullptr;
2041 if (error_code EC = InitStream())
2044 // Sniff for the signature.
2045 if (Stream.Read(8) != 'B' ||
2046 Stream.Read(8) != 'C' ||
2047 Stream.Read(4) != 0x0 ||
2048 Stream.Read(4) != 0xC ||
2049 Stream.Read(4) != 0xE ||
2050 Stream.Read(4) != 0xD)
2051 return Error(InvalidBitcodeSignature);
2053 // We expect a number of well-defined blocks, though we don't necessarily
2054 // need to understand them all.
2056 if (Stream.AtEndOfStream())
2057 return error_code::success();
2059 BitstreamEntry Entry =
2060 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2062 switch (Entry.Kind) {
2063 case BitstreamEntry::Error:
2064 return Error(MalformedBlock);
2065 case BitstreamEntry::EndBlock:
2066 return error_code::success();
2068 case BitstreamEntry::SubBlock:
2070 case bitc::BLOCKINFO_BLOCK_ID:
2071 if (Stream.ReadBlockInfoBlock())
2072 return Error(MalformedBlock);
2074 case bitc::MODULE_BLOCK_ID:
2075 // Reject multiple MODULE_BLOCK's in a single bitstream.
2077 return Error(InvalidMultipleBlocks);
2079 if (error_code EC = ParseModule(false))
2082 return error_code::success();
2085 if (Stream.SkipBlock())
2086 return Error(InvalidRecord);
2090 case BitstreamEntry::Record:
2091 // There should be no records in the top-level of blocks.
2093 // The ranlib in Xcode 4 will align archive members by appending newlines
2094 // to the end of them. If this file size is a multiple of 4 but not 8, we
2095 // have to read and ignore these final 4 bytes :-(
2096 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2097 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2098 Stream.AtEndOfStream())
2099 return error_code::success();
2101 return Error(InvalidRecord);
2106 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2107 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2108 return Error(InvalidRecord);
2110 SmallVector<uint64_t, 64> Record;
2112 // Read all the records for this module.
2114 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2116 switch (Entry.Kind) {
2117 case BitstreamEntry::SubBlock: // Handled for us already.
2118 case BitstreamEntry::Error:
2119 return Error(MalformedBlock);
2120 case BitstreamEntry::EndBlock:
2121 return error_code::success();
2122 case BitstreamEntry::Record:
2123 // The interesting case.
2128 switch (Stream.readRecord(Entry.ID, Record)) {
2129 default: break; // Default behavior, ignore unknown content.
2130 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2132 if (ConvertToString(Record, 0, S))
2133 return Error(InvalidRecord);
2142 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2143 if (error_code EC = InitStream())
2146 // Sniff for the signature.
2147 if (Stream.Read(8) != 'B' ||
2148 Stream.Read(8) != 'C' ||
2149 Stream.Read(4) != 0x0 ||
2150 Stream.Read(4) != 0xC ||
2151 Stream.Read(4) != 0xE ||
2152 Stream.Read(4) != 0xD)
2153 return Error(InvalidBitcodeSignature);
2155 // We expect a number of well-defined blocks, though we don't necessarily
2156 // need to understand them all.
2158 BitstreamEntry Entry = Stream.advance();
2160 switch (Entry.Kind) {
2161 case BitstreamEntry::Error:
2162 return Error(MalformedBlock);
2163 case BitstreamEntry::EndBlock:
2164 return error_code::success();
2166 case BitstreamEntry::SubBlock:
2167 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2168 return ParseModuleTriple(Triple);
2170 // Ignore other sub-blocks.
2171 if (Stream.SkipBlock())
2172 return Error(MalformedBlock);
2175 case BitstreamEntry::Record:
2176 Stream.skipRecord(Entry.ID);
2182 /// ParseMetadataAttachment - Parse metadata attachments.
2183 error_code BitcodeReader::ParseMetadataAttachment() {
2184 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2185 return Error(InvalidRecord);
2187 SmallVector<uint64_t, 64> Record;
2189 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2191 switch (Entry.Kind) {
2192 case BitstreamEntry::SubBlock: // Handled for us already.
2193 case BitstreamEntry::Error:
2194 return Error(MalformedBlock);
2195 case BitstreamEntry::EndBlock:
2196 return error_code::success();
2197 case BitstreamEntry::Record:
2198 // The interesting case.
2202 // Read a metadata attachment record.
2204 switch (Stream.readRecord(Entry.ID, Record)) {
2205 default: // Default behavior: ignore.
2207 case bitc::METADATA_ATTACHMENT: {
2208 unsigned RecordLength = Record.size();
2209 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2210 return Error(InvalidRecord);
2211 Instruction *Inst = InstructionList[Record[0]];
2212 for (unsigned i = 1; i != RecordLength; i = i+2) {
2213 unsigned Kind = Record[i];
2214 DenseMap<unsigned, unsigned>::iterator I =
2215 MDKindMap.find(Kind);
2216 if (I == MDKindMap.end())
2217 return Error(InvalidID);
2218 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2219 Inst->setMetadata(I->second, cast<MDNode>(Node));
2220 if (I->second == LLVMContext::MD_tbaa)
2221 InstsWithTBAATag.push_back(Inst);
2229 /// ParseFunctionBody - Lazily parse the specified function body block.
2230 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2231 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2232 return Error(InvalidRecord);
2234 InstructionList.clear();
2235 unsigned ModuleValueListSize = ValueList.size();
2236 unsigned ModuleMDValueListSize = MDValueList.size();
2238 // Add all the function arguments to the value table.
2239 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2240 ValueList.push_back(I);
2242 unsigned NextValueNo = ValueList.size();
2243 BasicBlock *CurBB = nullptr;
2244 unsigned CurBBNo = 0;
2248 // Read all the records.
2249 SmallVector<uint64_t, 64> Record;
2251 BitstreamEntry Entry = Stream.advance();
2253 switch (Entry.Kind) {
2254 case BitstreamEntry::Error:
2255 return Error(MalformedBlock);
2256 case BitstreamEntry::EndBlock:
2257 goto OutOfRecordLoop;
2259 case BitstreamEntry::SubBlock:
2261 default: // Skip unknown content.
2262 if (Stream.SkipBlock())
2263 return Error(InvalidRecord);
2265 case bitc::CONSTANTS_BLOCK_ID:
2266 if (error_code EC = ParseConstants())
2268 NextValueNo = ValueList.size();
2270 case bitc::VALUE_SYMTAB_BLOCK_ID:
2271 if (error_code EC = ParseValueSymbolTable())
2274 case bitc::METADATA_ATTACHMENT_ID:
2275 if (error_code EC = ParseMetadataAttachment())
2278 case bitc::METADATA_BLOCK_ID:
2279 if (error_code EC = ParseMetadata())
2285 case BitstreamEntry::Record:
2286 // The interesting case.
2292 Instruction *I = nullptr;
2293 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2295 default: // Default behavior: reject
2296 return Error(InvalidValue);
2297 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2298 if (Record.size() < 1 || Record[0] == 0)
2299 return Error(InvalidRecord);
2300 // Create all the basic blocks for the function.
2301 FunctionBBs.resize(Record[0]);
2302 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2303 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2304 CurBB = FunctionBBs[0];
2307 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2308 // This record indicates that the last instruction is at the same
2309 // location as the previous instruction with a location.
2312 // Get the last instruction emitted.
2313 if (CurBB && !CurBB->empty())
2315 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2316 !FunctionBBs[CurBBNo-1]->empty())
2317 I = &FunctionBBs[CurBBNo-1]->back();
2320 return Error(InvalidRecord);
2321 I->setDebugLoc(LastLoc);
2325 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2326 I = nullptr; // Get the last instruction emitted.
2327 if (CurBB && !CurBB->empty())
2329 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2330 !FunctionBBs[CurBBNo-1]->empty())
2331 I = &FunctionBBs[CurBBNo-1]->back();
2332 if (!I || Record.size() < 4)
2333 return Error(InvalidRecord);
2335 unsigned Line = Record[0], Col = Record[1];
2336 unsigned ScopeID = Record[2], IAID = Record[3];
2338 MDNode *Scope = nullptr, *IA = nullptr;
2339 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2340 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2341 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2342 I->setDebugLoc(LastLoc);
2347 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2350 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2351 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2352 OpNum+1 > Record.size())
2353 return Error(InvalidRecord);
2355 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2357 return Error(InvalidRecord);
2358 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2359 InstructionList.push_back(I);
2360 if (OpNum < Record.size()) {
2361 if (Opc == Instruction::Add ||
2362 Opc == Instruction::Sub ||
2363 Opc == Instruction::Mul ||
2364 Opc == Instruction::Shl) {
2365 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2366 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2367 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2368 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2369 } else if (Opc == Instruction::SDiv ||
2370 Opc == Instruction::UDiv ||
2371 Opc == Instruction::LShr ||
2372 Opc == Instruction::AShr) {
2373 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2374 cast<BinaryOperator>(I)->setIsExact(true);
2375 } else if (isa<FPMathOperator>(I)) {
2377 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2378 FMF.setUnsafeAlgebra();
2379 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2381 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2383 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2384 FMF.setNoSignedZeros();
2385 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2386 FMF.setAllowReciprocal();
2388 I->setFastMathFlags(FMF);
2394 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2397 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2398 OpNum+2 != Record.size())
2399 return Error(InvalidRecord);
2401 Type *ResTy = getTypeByID(Record[OpNum]);
2402 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2403 if (Opc == -1 || !ResTy)
2404 return Error(InvalidRecord);
2405 Instruction *Temp = nullptr;
2406 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2408 InstructionList.push_back(Temp);
2409 CurBB->getInstList().push_back(Temp);
2412 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2414 InstructionList.push_back(I);
2417 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2418 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2421 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2422 return Error(InvalidRecord);
2424 SmallVector<Value*, 16> GEPIdx;
2425 while (OpNum != Record.size()) {
2427 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2428 return Error(InvalidRecord);
2429 GEPIdx.push_back(Op);
2432 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2433 InstructionList.push_back(I);
2434 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2435 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2439 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2440 // EXTRACTVAL: [opty, opval, n x indices]
2443 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2444 return Error(InvalidRecord);
2446 SmallVector<unsigned, 4> EXTRACTVALIdx;
2447 for (unsigned RecSize = Record.size();
2448 OpNum != RecSize; ++OpNum) {
2449 uint64_t Index = Record[OpNum];
2450 if ((unsigned)Index != Index)
2451 return Error(InvalidValue);
2452 EXTRACTVALIdx.push_back((unsigned)Index);
2455 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2456 InstructionList.push_back(I);
2460 case bitc::FUNC_CODE_INST_INSERTVAL: {
2461 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2464 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2465 return Error(InvalidRecord);
2467 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2468 return Error(InvalidRecord);
2470 SmallVector<unsigned, 4> INSERTVALIdx;
2471 for (unsigned RecSize = Record.size();
2472 OpNum != RecSize; ++OpNum) {
2473 uint64_t Index = Record[OpNum];
2474 if ((unsigned)Index != Index)
2475 return Error(InvalidValue);
2476 INSERTVALIdx.push_back((unsigned)Index);
2479 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2480 InstructionList.push_back(I);
2484 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2485 // obsolete form of select
2486 // handles select i1 ... in old bitcode
2488 Value *TrueVal, *FalseVal, *Cond;
2489 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2490 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2491 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2492 return Error(InvalidRecord);
2494 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2495 InstructionList.push_back(I);
2499 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2500 // new form of select
2501 // handles select i1 or select [N x i1]
2503 Value *TrueVal, *FalseVal, *Cond;
2504 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2505 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2506 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2507 return Error(InvalidRecord);
2509 // select condition can be either i1 or [N x i1]
2510 if (VectorType* vector_type =
2511 dyn_cast<VectorType>(Cond->getType())) {
2513 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2514 return Error(InvalidTypeForValue);
2517 if (Cond->getType() != Type::getInt1Ty(Context))
2518 return Error(InvalidTypeForValue);
2521 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2522 InstructionList.push_back(I);
2526 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2529 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2530 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2531 return Error(InvalidRecord);
2532 I = ExtractElementInst::Create(Vec, Idx);
2533 InstructionList.push_back(I);
2537 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2539 Value *Vec, *Elt, *Idx;
2540 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2541 popValue(Record, OpNum, NextValueNo,
2542 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2543 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2544 return Error(InvalidRecord);
2545 I = InsertElementInst::Create(Vec, Elt, Idx);
2546 InstructionList.push_back(I);
2550 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2552 Value *Vec1, *Vec2, *Mask;
2553 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2554 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2555 return Error(InvalidRecord);
2557 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2558 return Error(InvalidRecord);
2559 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2560 InstructionList.push_back(I);
2564 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2565 // Old form of ICmp/FCmp returning bool
2566 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2567 // both legal on vectors but had different behaviour.
2568 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2569 // FCmp/ICmp returning bool or vector of bool
2573 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2574 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2575 OpNum+1 != Record.size())
2576 return Error(InvalidRecord);
2578 if (LHS->getType()->isFPOrFPVectorTy())
2579 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2581 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2582 InstructionList.push_back(I);
2586 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2588 unsigned Size = Record.size();
2590 I = ReturnInst::Create(Context);
2591 InstructionList.push_back(I);
2596 Value *Op = nullptr;
2597 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2598 return Error(InvalidRecord);
2599 if (OpNum != Record.size())
2600 return Error(InvalidRecord);
2602 I = ReturnInst::Create(Context, Op);
2603 InstructionList.push_back(I);
2606 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2607 if (Record.size() != 1 && Record.size() != 3)
2608 return Error(InvalidRecord);
2609 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2611 return Error(InvalidRecord);
2613 if (Record.size() == 1) {
2614 I = BranchInst::Create(TrueDest);
2615 InstructionList.push_back(I);
2618 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2619 Value *Cond = getValue(Record, 2, NextValueNo,
2620 Type::getInt1Ty(Context));
2621 if (!FalseDest || !Cond)
2622 return Error(InvalidRecord);
2623 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2624 InstructionList.push_back(I);
2628 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2630 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2631 // "New" SwitchInst format with case ranges. The changes to write this
2632 // format were reverted but we still recognize bitcode that uses it.
2633 // Hopefully someday we will have support for case ranges and can use
2634 // this format again.
2636 Type *OpTy = getTypeByID(Record[1]);
2637 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2639 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2640 BasicBlock *Default = getBasicBlock(Record[3]);
2641 if (!OpTy || !Cond || !Default)
2642 return Error(InvalidRecord);
2644 unsigned NumCases = Record[4];
2646 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2647 InstructionList.push_back(SI);
2649 unsigned CurIdx = 5;
2650 for (unsigned i = 0; i != NumCases; ++i) {
2651 SmallVector<ConstantInt*, 1> CaseVals;
2652 unsigned NumItems = Record[CurIdx++];
2653 for (unsigned ci = 0; ci != NumItems; ++ci) {
2654 bool isSingleNumber = Record[CurIdx++];
2657 unsigned ActiveWords = 1;
2658 if (ValueBitWidth > 64)
2659 ActiveWords = Record[CurIdx++];
2660 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2662 CurIdx += ActiveWords;
2664 if (!isSingleNumber) {
2666 if (ValueBitWidth > 64)
2667 ActiveWords = Record[CurIdx++];
2669 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2671 CurIdx += ActiveWords;
2673 // FIXME: It is not clear whether values in the range should be
2674 // compared as signed or unsigned values. The partially
2675 // implemented changes that used this format in the past used
2676 // unsigned comparisons.
2677 for ( ; Low.ule(High); ++Low)
2678 CaseVals.push_back(ConstantInt::get(Context, Low));
2680 CaseVals.push_back(ConstantInt::get(Context, Low));
2682 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2683 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2684 cve = CaseVals.end(); cvi != cve; ++cvi)
2685 SI->addCase(*cvi, DestBB);
2691 // Old SwitchInst format without case ranges.
2693 if (Record.size() < 3 || (Record.size() & 1) == 0)
2694 return Error(InvalidRecord);
2695 Type *OpTy = getTypeByID(Record[0]);
2696 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2697 BasicBlock *Default = getBasicBlock(Record[2]);
2698 if (!OpTy || !Cond || !Default)
2699 return Error(InvalidRecord);
2700 unsigned NumCases = (Record.size()-3)/2;
2701 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2702 InstructionList.push_back(SI);
2703 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2704 ConstantInt *CaseVal =
2705 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2706 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2707 if (!CaseVal || !DestBB) {
2709 return Error(InvalidRecord);
2711 SI->addCase(CaseVal, DestBB);
2716 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2717 if (Record.size() < 2)
2718 return Error(InvalidRecord);
2719 Type *OpTy = getTypeByID(Record[0]);
2720 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2721 if (!OpTy || !Address)
2722 return Error(InvalidRecord);
2723 unsigned NumDests = Record.size()-2;
2724 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2725 InstructionList.push_back(IBI);
2726 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2727 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2728 IBI->addDestination(DestBB);
2731 return Error(InvalidRecord);
2738 case bitc::FUNC_CODE_INST_INVOKE: {
2739 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2740 if (Record.size() < 4)
2741 return Error(InvalidRecord);
2742 AttributeSet PAL = getAttributes(Record[0]);
2743 unsigned CCInfo = Record[1];
2744 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2745 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2749 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2750 return Error(InvalidRecord);
2752 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2753 FunctionType *FTy = !CalleeTy ? nullptr :
2754 dyn_cast<FunctionType>(CalleeTy->getElementType());
2756 // Check that the right number of fixed parameters are here.
2757 if (!FTy || !NormalBB || !UnwindBB ||
2758 Record.size() < OpNum+FTy->getNumParams())
2759 return Error(InvalidRecord);
2761 SmallVector<Value*, 16> Ops;
2762 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2763 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2764 FTy->getParamType(i)));
2766 return Error(InvalidRecord);
2769 if (!FTy->isVarArg()) {
2770 if (Record.size() != OpNum)
2771 return Error(InvalidRecord);
2773 // Read type/value pairs for varargs params.
2774 while (OpNum != Record.size()) {
2776 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2777 return Error(InvalidRecord);
2782 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2783 InstructionList.push_back(I);
2784 cast<InvokeInst>(I)->setCallingConv(
2785 static_cast<CallingConv::ID>(CCInfo));
2786 cast<InvokeInst>(I)->setAttributes(PAL);
2789 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2791 Value *Val = nullptr;
2792 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2793 return Error(InvalidRecord);
2794 I = ResumeInst::Create(Val);
2795 InstructionList.push_back(I);
2798 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2799 I = new UnreachableInst(Context);
2800 InstructionList.push_back(I);
2802 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2803 if (Record.size() < 1 || ((Record.size()-1)&1))
2804 return Error(InvalidRecord);
2805 Type *Ty = getTypeByID(Record[0]);
2807 return Error(InvalidRecord);
2809 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2810 InstructionList.push_back(PN);
2812 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2814 // With the new function encoding, it is possible that operands have
2815 // negative IDs (for forward references). Use a signed VBR
2816 // representation to keep the encoding small.
2818 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2820 V = getValue(Record, 1+i, NextValueNo, Ty);
2821 BasicBlock *BB = getBasicBlock(Record[2+i]);
2823 return Error(InvalidRecord);
2824 PN->addIncoming(V, BB);
2830 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2831 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2833 if (Record.size() < 4)
2834 return Error(InvalidRecord);
2835 Type *Ty = getTypeByID(Record[Idx++]);
2837 return Error(InvalidRecord);
2838 Value *PersFn = nullptr;
2839 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2840 return Error(InvalidRecord);
2842 bool IsCleanup = !!Record[Idx++];
2843 unsigned NumClauses = Record[Idx++];
2844 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2845 LP->setCleanup(IsCleanup);
2846 for (unsigned J = 0; J != NumClauses; ++J) {
2847 LandingPadInst::ClauseType CT =
2848 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2851 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2853 return Error(InvalidRecord);
2856 assert((CT != LandingPadInst::Catch ||
2857 !isa<ArrayType>(Val->getType())) &&
2858 "Catch clause has a invalid type!");
2859 assert((CT != LandingPadInst::Filter ||
2860 isa<ArrayType>(Val->getType())) &&
2861 "Filter clause has invalid type!");
2866 InstructionList.push_back(I);
2870 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2871 if (Record.size() != 4)
2872 return Error(InvalidRecord);
2874 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2875 Type *OpTy = getTypeByID(Record[1]);
2876 Value *Size = getFnValueByID(Record[2], OpTy);
2877 unsigned Align = Record[3];
2879 return Error(InvalidRecord);
2880 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2881 InstructionList.push_back(I);
2884 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2887 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2888 OpNum+2 != Record.size())
2889 return Error(InvalidRecord);
2891 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2892 InstructionList.push_back(I);
2895 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2896 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2899 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2900 OpNum+4 != Record.size())
2901 return Error(InvalidRecord);
2904 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2905 if (Ordering == NotAtomic || Ordering == Release ||
2906 Ordering == AcquireRelease)
2907 return Error(InvalidRecord);
2908 if (Ordering != NotAtomic && Record[OpNum] == 0)
2909 return Error(InvalidRecord);
2910 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2912 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2913 Ordering, SynchScope);
2914 InstructionList.push_back(I);
2917 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2920 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2921 popValue(Record, OpNum, NextValueNo,
2922 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2923 OpNum+2 != Record.size())
2924 return Error(InvalidRecord);
2926 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2927 InstructionList.push_back(I);
2930 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2931 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2934 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2935 popValue(Record, OpNum, NextValueNo,
2936 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2937 OpNum+4 != Record.size())
2938 return Error(InvalidRecord);
2940 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2941 if (Ordering == NotAtomic || Ordering == Acquire ||
2942 Ordering == AcquireRelease)
2943 return Error(InvalidRecord);
2944 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2945 if (Ordering != NotAtomic && Record[OpNum] == 0)
2946 return Error(InvalidRecord);
2948 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2949 Ordering, SynchScope);
2950 InstructionList.push_back(I);
2953 case bitc::FUNC_CODE_INST_CMPXCHG: {
2954 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2957 Value *Ptr, *Cmp, *New;
2958 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2959 popValue(Record, OpNum, NextValueNo,
2960 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2961 popValue(Record, OpNum, NextValueNo,
2962 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2963 (OpNum + 3 != Record.size() && OpNum + 4 != Record.size()))
2964 return Error(InvalidRecord);
2965 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2966 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2967 return Error(InvalidRecord);
2968 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2970 AtomicOrdering FailureOrdering;
2971 if (Record.size() < 7)
2973 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2975 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2977 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2979 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2980 InstructionList.push_back(I);
2983 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2984 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2987 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2988 popValue(Record, OpNum, NextValueNo,
2989 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2990 OpNum+4 != Record.size())
2991 return Error(InvalidRecord);
2992 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2993 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2994 Operation > AtomicRMWInst::LAST_BINOP)
2995 return Error(InvalidRecord);
2996 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2997 if (Ordering == NotAtomic || Ordering == Unordered)
2998 return Error(InvalidRecord);
2999 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3000 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3001 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3002 InstructionList.push_back(I);
3005 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3006 if (2 != Record.size())
3007 return Error(InvalidRecord);
3008 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3009 if (Ordering == NotAtomic || Ordering == Unordered ||
3010 Ordering == Monotonic)
3011 return Error(InvalidRecord);
3012 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3013 I = new FenceInst(Context, Ordering, SynchScope);
3014 InstructionList.push_back(I);
3017 case bitc::FUNC_CODE_INST_CALL: {
3018 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3019 if (Record.size() < 3)
3020 return Error(InvalidRecord);
3022 AttributeSet PAL = getAttributes(Record[0]);
3023 unsigned CCInfo = Record[1];
3027 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3028 return Error(InvalidRecord);
3030 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3031 FunctionType *FTy = nullptr;
3032 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3033 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3034 return Error(InvalidRecord);
3036 SmallVector<Value*, 16> Args;
3037 // Read the fixed params.
3038 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3039 if (FTy->getParamType(i)->isLabelTy())
3040 Args.push_back(getBasicBlock(Record[OpNum]));
3042 Args.push_back(getValue(Record, OpNum, NextValueNo,
3043 FTy->getParamType(i)));
3045 return Error(InvalidRecord);
3048 // Read type/value pairs for varargs params.
3049 if (!FTy->isVarArg()) {
3050 if (OpNum != Record.size())
3051 return Error(InvalidRecord);
3053 while (OpNum != Record.size()) {
3055 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3056 return Error(InvalidRecord);
3061 I = CallInst::Create(Callee, Args);
3062 InstructionList.push_back(I);
3063 cast<CallInst>(I)->setCallingConv(
3064 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3065 CallInst::TailCallKind TCK = CallInst::TCK_None;
3067 TCK = CallInst::TCK_Tail;
3068 if (CCInfo & (1 << 14))
3069 TCK = CallInst::TCK_MustTail;
3070 cast<CallInst>(I)->setTailCallKind(TCK);
3071 cast<CallInst>(I)->setAttributes(PAL);
3074 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3075 if (Record.size() < 3)
3076 return Error(InvalidRecord);
3077 Type *OpTy = getTypeByID(Record[0]);
3078 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3079 Type *ResTy = getTypeByID(Record[2]);
3080 if (!OpTy || !Op || !ResTy)
3081 return Error(InvalidRecord);
3082 I = new VAArgInst(Op, ResTy);
3083 InstructionList.push_back(I);
3088 // Add instruction to end of current BB. If there is no current BB, reject
3092 return Error(InvalidInstructionWithNoBB);
3094 CurBB->getInstList().push_back(I);
3096 // If this was a terminator instruction, move to the next block.
3097 if (isa<TerminatorInst>(I)) {
3099 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3102 // Non-void values get registered in the value table for future use.
3103 if (I && !I->getType()->isVoidTy())
3104 ValueList.AssignValue(I, NextValueNo++);
3109 // Check the function list for unresolved values.
3110 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3111 if (!A->getParent()) {
3112 // We found at least one unresolved value. Nuke them all to avoid leaks.
3113 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3114 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3115 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3119 return Error(NeverResolvedValueFoundInFunction);
3123 // FIXME: Check for unresolved forward-declared metadata references
3124 // and clean up leaks.
3126 // See if anything took the address of blocks in this function. If so,
3127 // resolve them now.
3128 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3129 BlockAddrFwdRefs.find(F);
3130 if (BAFRI != BlockAddrFwdRefs.end()) {
3131 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3132 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3133 unsigned BlockIdx = RefList[i].first;
3134 if (BlockIdx >= FunctionBBs.size())
3135 return Error(InvalidID);
3137 GlobalVariable *FwdRef = RefList[i].second;
3138 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3139 FwdRef->eraseFromParent();
3142 BlockAddrFwdRefs.erase(BAFRI);
3145 // Trim the value list down to the size it was before we parsed this function.
3146 ValueList.shrinkTo(ModuleValueListSize);
3147 MDValueList.shrinkTo(ModuleMDValueListSize);
3148 std::vector<BasicBlock*>().swap(FunctionBBs);
3149 return error_code::success();
3152 /// Find the function body in the bitcode stream
3153 error_code BitcodeReader::FindFunctionInStream(Function *F,
3154 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3155 while (DeferredFunctionInfoIterator->second == 0) {
3156 if (Stream.AtEndOfStream())
3157 return Error(CouldNotFindFunctionInStream);
3158 // ParseModule will parse the next body in the stream and set its
3159 // position in the DeferredFunctionInfo map.
3160 if (error_code EC = ParseModule(true))
3163 return error_code::success();
3166 //===----------------------------------------------------------------------===//
3167 // GVMaterializer implementation
3168 //===----------------------------------------------------------------------===//
3171 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3172 if (const Function *F = dyn_cast<Function>(GV)) {
3173 return F->isDeclaration() &&
3174 DeferredFunctionInfo.count(const_cast<Function*>(F));
3179 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3180 Function *F = dyn_cast<Function>(GV);
3181 // If it's not a function or is already material, ignore the request.
3182 if (!F || !F->isMaterializable())
3183 return error_code::success();
3185 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3186 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3187 // If its position is recorded as 0, its body is somewhere in the stream
3188 // but we haven't seen it yet.
3189 if (DFII->second == 0 && LazyStreamer)
3190 if (error_code EC = FindFunctionInStream(F, DFII))
3193 // Move the bit stream to the saved position of the deferred function body.
3194 Stream.JumpToBit(DFII->second);
3196 if (error_code EC = ParseFunctionBody(F))
3199 // Upgrade any old intrinsic calls in the function.
3200 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3201 E = UpgradedIntrinsics.end(); I != E; ++I) {
3202 if (I->first != I->second) {
3203 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3205 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3206 UpgradeIntrinsicCall(CI, I->second);
3211 return error_code::success();
3214 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3215 const Function *F = dyn_cast<Function>(GV);
3216 if (!F || F->isDeclaration())
3218 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3221 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3222 Function *F = dyn_cast<Function>(GV);
3223 // If this function isn't dematerializable, this is a noop.
3224 if (!F || !isDematerializable(F))
3227 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3229 // Just forget the function body, we can remat it later.
3234 error_code BitcodeReader::MaterializeModule(Module *M) {
3235 assert(M == TheModule &&
3236 "Can only Materialize the Module this BitcodeReader is attached to.");
3237 // Iterate over the module, deserializing any functions that are still on
3239 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3241 if (F->isMaterializable()) {
3242 if (error_code EC = Materialize(F))
3246 // At this point, if there are any function bodies, the current bit is
3247 // pointing to the END_BLOCK record after them. Now make sure the rest
3248 // of the bits in the module have been read.
3252 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3253 // delete the old functions to clean up. We can't do this unless the entire
3254 // module is materialized because there could always be another function body
3255 // with calls to the old function.
3256 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3257 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3258 if (I->first != I->second) {
3259 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3261 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3262 UpgradeIntrinsicCall(CI, I->second);
3264 if (!I->first->use_empty())
3265 I->first->replaceAllUsesWith(I->second);
3266 I->first->eraseFromParent();
3269 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3271 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3272 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3274 UpgradeDebugInfo(*M);
3275 return error_code::success();
3278 error_code BitcodeReader::InitStream() {
3280 return InitLazyStream();
3281 return InitStreamFromBuffer();
3284 error_code BitcodeReader::InitStreamFromBuffer() {
3285 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3286 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3288 if (Buffer->getBufferSize() & 3) {
3289 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3290 return Error(InvalidBitcodeSignature);
3292 return Error(BitcodeStreamInvalidSize);
3295 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3296 // The magic number is 0x0B17C0DE stored in little endian.
3297 if (isBitcodeWrapper(BufPtr, BufEnd))
3298 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3299 return Error(InvalidBitcodeWrapperHeader);
3301 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3302 Stream.init(*StreamFile);
3304 return error_code::success();
3307 error_code BitcodeReader::InitLazyStream() {
3308 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3310 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3311 StreamFile.reset(new BitstreamReader(Bytes));
3312 Stream.init(*StreamFile);
3314 unsigned char buf[16];
3315 if (Bytes->readBytes(0, 16, buf) == -1)
3316 return Error(BitcodeStreamInvalidSize);
3318 if (!isBitcode(buf, buf + 16))
3319 return Error(InvalidBitcodeSignature);
3321 if (isBitcodeWrapper(buf, buf + 4)) {
3322 const unsigned char *bitcodeStart = buf;
3323 const unsigned char *bitcodeEnd = buf + 16;
3324 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3325 Bytes->dropLeadingBytes(bitcodeStart - buf);
3326 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3328 return error_code::success();
3332 class BitcodeErrorCategoryType : public error_category {
3333 const char *name() const override {
3334 return "llvm.bitcode";
3336 std::string message(int IE) const override {
3337 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3339 case BitcodeReader::BitcodeStreamInvalidSize:
3340 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3341 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3342 return "Conflicting METADATA_KIND records";
3343 case BitcodeReader::CouldNotFindFunctionInStream:
3344 return "Could not find function in stream";
3345 case BitcodeReader::ExpectedConstant:
3346 return "Expected a constant";
3347 case BitcodeReader::InsufficientFunctionProtos:
3348 return "Insufficient function protos";
3349 case BitcodeReader::InvalidBitcodeSignature:
3350 return "Invalid bitcode signature";
3351 case BitcodeReader::InvalidBitcodeWrapperHeader:
3352 return "Invalid bitcode wrapper header";
3353 case BitcodeReader::InvalidConstantReference:
3354 return "Invalid ronstant reference";
3355 case BitcodeReader::InvalidID:
3356 return "Invalid ID";
3357 case BitcodeReader::InvalidInstructionWithNoBB:
3358 return "Invalid instruction with no BB";
3359 case BitcodeReader::InvalidRecord:
3360 return "Invalid record";
3361 case BitcodeReader::InvalidTypeForValue:
3362 return "Invalid type for value";
3363 case BitcodeReader::InvalidTYPETable:
3364 return "Invalid TYPE table";
3365 case BitcodeReader::InvalidType:
3366 return "Invalid type";
3367 case BitcodeReader::MalformedBlock:
3368 return "Malformed block";
3369 case BitcodeReader::MalformedGlobalInitializerSet:
3370 return "Malformed global initializer set";
3371 case BitcodeReader::InvalidMultipleBlocks:
3372 return "Invalid multiple blocks";
3373 case BitcodeReader::NeverResolvedValueFoundInFunction:
3374 return "Never resolved value found in function";
3375 case BitcodeReader::InvalidValue:
3376 return "Invalid value";
3378 llvm_unreachable("Unknown error type!");
3383 const error_category &BitcodeReader::BitcodeErrorCategory() {
3384 static BitcodeErrorCategoryType O;
3388 //===----------------------------------------------------------------------===//
3389 // External interface
3390 //===----------------------------------------------------------------------===//
3392 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3394 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3395 LLVMContext &Context) {
3396 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3397 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3398 M->setMaterializer(R);
3399 if (error_code EC = R->ParseBitcodeInto(M)) {
3400 delete M; // Also deletes R.
3403 // Have the BitcodeReader dtor delete 'Buffer'.
3404 R->setBufferOwned(true);
3406 R->materializeForwardReferencedFunctions();
3412 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3413 DataStreamer *streamer,
3414 LLVMContext &Context,
3415 std::string *ErrMsg) {
3416 Module *M = new Module(name, Context);
3417 BitcodeReader *R = new BitcodeReader(streamer, Context);
3418 M->setMaterializer(R);
3419 if (error_code EC = R->ParseBitcodeInto(M)) {
3421 *ErrMsg = EC.message();
3422 delete M; // Also deletes R.
3425 R->setBufferOwned(false); // no buffer to delete
3429 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3430 LLVMContext &Context) {
3431 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3434 Module *M = ModuleOrErr.get();
3436 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3437 // there was an error.
3438 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3440 // Read in the entire module, and destroy the BitcodeReader.
3441 if (error_code EC = M->materializeAllPermanently()) {
3446 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3447 // written. We must defer until the Module has been fully materialized.
3452 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3453 LLVMContext& Context,
3454 std::string *ErrMsg) {
3455 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3456 // Don't let the BitcodeReader dtor delete 'Buffer'.
3457 R->setBufferOwned(false);
3459 std::string Triple("");
3460 if (error_code EC = R->ParseTriple(Triple))
3462 *ErrMsg = EC.message();